S A*_*rew 9 python opencv image image-processing python-3.x
我有一个项目,opencv我使用cv2.putText(). 目前它看起来如下:
正如您在左上角看到的那样,文本存在但不清晰可见。是否可以将背景设为黑色,以便文本看起来不错。类似于下图:
即使黑色背景覆盖到框架的右侧,也可以。下面是我用来在框架上放置文本的代码:
cv2.putText(frame, "Data: N/A", (5, 30), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 0, 255), 1)
cv2.putText(frame, "Room: C1", (5, 60), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 0, 255), 1)
Run Code Online (Sandbox Code Playgroud)
opencv 中是否有任何可以执行此操作的预构建方法/库。任何人都可以请提出一个好方法吗?
没有预先构建的方法,但一个简单的方法是使用cv2.rectangle+ cv2.putText。您需要做的就是在图像上绘制黑色矩形,然后放置文本。您可以x,y,w,h根据您想要矩形的大小来调整参数。下面是一个例子:
输入图像:
结果:
import cv2
import numpy as np
# Load image, define rectangle bounds
image = cv2.imread('1.jpg')
x,y,w,h = 0,0,175,75
# Draw black background rectangle
cv2.rectangle(image, (x, x), (x + w, y + h), (0,0,0), -1)
# Add text
cv2.putText(image, "THICC flower", (x + int(w/10),y + int(h/2)), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255,255,255), 2)
# Display
cv2.imshow('image', image)
cv2.waitKey()
Run Code Online (Sandbox Code Playgroud)
使用这个功能:
import cv2
def draw_text(img, text,
font=cv2.FONT_HERSHEY_PLAIN,
pos=(0, 0),
font_scale=3,
font_thickness=2,
text_color=(0, 255, 0),
text_color_bg=(0, 0, 0)
):
x, y = pos
text_size, _ = cv2.getTextSize(text, font, font_scale, font_thickness)
text_w, text_h = text_size
cv2.rectangle(img, pos, (x + text_w, y + text_h), text_color_bg, -1)
cv2.putText(img, text, (x, y + text_h + font_scale - 1), font, font_scale, text_color, font_thickness)
return text_size
Run Code Online (Sandbox Code Playgroud)
然后你可以像这样调用函数:
image = 127 * np.ones((100, 200, 3), dtype="uint8")
pos = (10, 10)
w, h = draw_text(image, "hello", pos=(10, 10))
draw_text(image, "world", font_scale=4, pos=(10, 20 + h), text_color_bg=(255, 0, 0))
cv2.imshow("image", image)
cv2.waitKey()
Run Code Online (Sandbox Code Playgroud)
请注意,默认情况下它会绘制黑色背景,但您可以根据需要使用其他颜色。
| 归档时间: |
|
| 查看次数: |
10121 次 |
| 最近记录: |