python - 使用 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)
解决方案
您可以创建一个文本高度和宽度大小的空白 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)
现在将此蒙版的宽度调整为您的图像宽度。
mask = cv2.resize(mask, (img.shape[1], text_height))
此文本需要放在您的原始图像上,这可以通过按位或完成,但在此之前,我们需要使蒙版具有 3 个通道,因为尺寸应该匹配。用于cv2.merge
此任务。
mask = cv2.merge((mask, mask, mask))
img[-text_height:, :, :] = cv2.bitwise_or(img[-text_height:, :, :], mask)
您可以在任何需要的地方进行调整,只需注意尺寸匹配即可。
推荐阅读
- c# - 多流TCP c#
- qt - 如何修改 Qt 标签中的文本?
- docker - 如何连接在不同网络上运行的不同 docker 容器
- python - 'datetime.date' 对象在使用 timedelta 时没有属性 'days' 错误
- javascript - 如何在不使用 eval() 或窗口的情况下将字符串转换为 javascript 中的变量?
- stripe-payments - 如何使用 Stripe.createPaymentMethod() 传递元数据?
- html - 表格行填充剩余高度 Chrome 与 Firefox
- android - 重复属性 application@appComponentFactory
- opencv - 读取图像并保存,增加图像大小
- python - 基于条件查询结果后设置的参数的 MySQL/SQL 查询 - 该函数是在 Python 读取 CSV 文件之前编写的