在圆 OpenCV 内绘制文本 [英] Draw Text inside circle OpenCV
问题描述
有没有什么方便的方法可以将文本直接绘制到 OpenCV 圆中?在谷歌中没有找到任何类似的答案.
如果我只是将圆的 Centroid_X 和 Centroid_Y 用于 putText,我会得到如下图所示的内容,但我希望文本完全适合圆并且找不到任何优雅的方式在圆圈内绘制文本.
cv2.putText(frame, text, (cX, cY), FONT, 1.5, TEXT_COLOUR, int(TEXT_THICKNESS), cv2.LINE_AA)
出现问题是因为位置给了
Is there any convenient way to draw text right into OpenCV circle? Haven't found any similar answer in Google.
If I simply use circle's Centroid_X and Centroid_Y for putText I get something like in the picture below but I want Text completely fit circle and cannot find any elegant way to draw text inside circle.
cv2.putText(frame, text, (cX, cY), FONT, 1.5, TEXT_COLOUR, int(TEXT_THICKNESS), cv2.LINE_AA)
The problem occurs due to the fact that the position given to cv2.putText
defines the origin (bottom left corner of the rectangular area that fits the drawn text).
In order to have the text centered around some given point, you first need to measure the size of this rectangular area (bounding box). This can be done using the function cv2.getTextSize
.
Now, to have the text centered, the origin needs to move down by half the height of the bouding box, and to the left by half the width of the bounding box.
text_origin = (CENTER[0] - text_size[0] / 2, CENTER[1] + text_size[1] / 2)
Code:
import cv2
import numpy as np
img = np.zeros((128, 128, 3), dtype=np.uint8)
CENTER = (64, 64)
cv2.circle(img, CENTER, 48, (127,0,127), -1)
TEXT_FACE = cv2.FONT_HERSHEY_DUPLEX
TEXT_SCALE = 1.5
TEXT_THICKNESS = 2
TEXT = "0"
text_size, _ = cv2.getTextSize(TEXT, TEXT_FACE, TEXT_SCALE, TEXT_THICKNESS)
text_origin = (CENTER[0] - text_size[0] / 2, CENTER[1] + text_size[1] / 2)
cv2.putText(img, TEXT, text_origin, TEXT_FACE, TEXT_SCALE, (127,255,127), TEXT_THICKNESS, cv2.LINE_AA)
cv2.imwrite('centertext_out.png', img)
Output image:
这篇关于在圆 OpenCV 内绘制文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!