我使用以下方法在图像上绘制一个矩形
cv2.rectangle(frame,(x,y),(x1,y1),(0,255,0),2)
Run Code Online (Sandbox Code Playgroud)
我想绘制带有文本信息的矩形。我该怎么做?是否有任何可用的现成实现?还是应该匹配矩形的左上角坐标,并尝试使用cv2 rect元素显示不同的cv2文本元素?
您能指导我执行任何代码实现/解决方法吗?
PS:我不想使用object_detection。TF提供的可视化工具。
Shr*_*hak 14
也许对你来说太晚了,但我们可以这样做:
x1,y1 为左上点
x2,y2 为右下点
# For bounding box
img = cv2.rectangle(img, (x1, y1), (x2, y2), color, 2)
# For the text background
# Finds space required by the text so that we can put a background with that amount of width.
(w, h), _ = cv2.getTextSize(
label, cv2.FONT_HERSHEY_SIMPLEX, 0.6, 1)
# Prints the text.
img = cv2.rectangle(img, (x1, y1 - 20), (x1 + w, y1), color, -1)
img = cv2.putText(img, label, (x1, y1 - 5),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, text_color, 1)
# For printing text
img = cv2.putText(img, 'test', (x1, y1),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255,255,255), 1)
Run Code Online (Sandbox Code Playgroud)
小智 5
您可能需要使用一个函数来扩展您的代码,该函数将您的文本作为输入, position_x, position_y .. 它将测量字母的大小并基于此动态设置矩形宽度。
您可以使用: cv2.getTextSize(text, font, font_scale, depth)
获取它将使用多少像素,然后使用它来定义矩形宽度。
您可以用来cv2.putText()在矩形顶部覆盖文本信息。例如,您可以抓取轮廓坐标,绘制一个矩形,然后通过向上移动将其放在文本上方。
x,y,w,h = cv2.boundingRect(contour)
image = cv2.rectangle(image, (x, y), (x + w, y + h), (36,255,12), 1)
cv2.putText(image, 'Fedex', (x, y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (36,255,12), 2)
Run Code Online (Sandbox Code Playgroud)
你会得到这样的东西