首页 > 解决方案 > 使用 OpenCV (putText) 设置文本宽度

问题描述

我正在使用 openCV 编辑视频文件的某些帧。
我正在使用 putText 在框架中插入文本
我被困在文本宽度超过
我搜索过的框架宽度的位置,但在此平台上找不到任何合适的解决方案

我的代码如下:

while(cap.isOpened()):

      ret, frame = cap.read()
      if ret==True:

            x = 0
            y = 478
            w = 640
            h = 40

            font = cv2.FONT_HERSHEY_COMPLEX_SMALL
            font_color = (255, 255, 255)
            thick = 1
            text = "A very long text here blaaah blaaah blaaah blaaah blaaah blaaah . . . . . "
            font_size = 0.9
            (text_width, text_height) = cv2.getTextSize(text, font, font_size, thick)[0]

            if text_width > w :
                    # statements to fit width

            loc_x = x + int(w/2) - int(text_width/2)
            loc_y = y + int(h/2) + int(text_height/2)
            frame = cv2.putText(frame,text,(loc_x,loc_y),font,font_size,font_color,thick,cv2.LINE_AA)
            cv2.imwrite("frame.png",frame)

例如, 我也不希望文本在下一行下降,我希望文本应该缩小宽度以适应框架,如果它超过 我想减少WIDTH而不是HEIGHT
在此处输入图像描述


标签: pythonopencvopencv-python

解决方案


您可以创建一个文本高度和宽度大小的空白 NumPy 数组(我必须将 15 添加到文本高度,否则文本无法正确显示)并将您的文本放在上面。

import cv2
import numpy as np

img = cv2.imread('messi.jpg')
font = cv2.FONT_HERSHEY_COMPLEX_SMALL
font_color = (255, 255, 255)
thick = 1
text = "A very long text here blaaah blaaah blaaah blaaah blaaah blaaah . . . . . "
font_size = 0.9
(text_width, text_height) = cv2.getTextSize(text, font, font_size, thick)[0]
text_height += 15

mask = np.zeros((text_height, text_width), dtype=np.uint8)
mask = cv2.putText(mask,text,(0,15),font,font_size,font_color,thick,cv2.LINE_AA)

掩码1

现在将此蒙版的宽度调整为您的图像宽度。

mask = cv2.resize(mask, (img.shape[1], text_height))

mask_resized

此文本需要放在您的原始图像上,这可以通过按位或完成,但在此之前,我们需要使蒙版具有 3 个通道,因为尺寸应该匹配。用于cv2.merge此任务。

mask = cv2.merge((mask, mask, mask))
img[-text_height:, :, :] = cv2.bitwise_or(img[-text_height:, :, :], mask)

原始图像结果

您可以在任何需要的地方进行调整,只需注意尺寸匹配即可。


推荐阅读