gpt4 book ai didi

python - 使用 OpenCV (putText) 设置文本宽度

转载 作者:行者123 更新时间:2023-12-02 16:25:07 25 4
gpt4 key购买 nike

我正在使用 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)


例如,

enter image description here
此外,我不希望文本在下一行下降,我希望文本的宽度应该缩小,以便在超出时适合框架
我要减 宽度 不是 高度

最佳答案

您可以创建一个文本高度和宽度大小的空白 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)

mask1

现在将此蒙版的宽度调整为您的图像宽度。
mask = cv2.resize(mask, (img.shape[1], text_height))

mask_resized

此文本需要放在您的原始图像上,这可以通过按位或完成,但在此之前,我们需要使蒙版具有 3 个 channel ,因为尺寸应该匹配。使用 cv2.merge对于这个任务。
mask = cv2.merge((mask, mask, mask))
img[-text_height:, :, :] = cv2.bitwise_or(img[-text_height:, :, :], mask)

original image result

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

关于python - 使用 OpenCV (putText) 设置文本宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61913537/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com