Ivan Shelonik
Ivan Shelonik

Reputation: 2028

Draw Text inside circle OpenCV

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)

enter image description here

Upvotes: 4

Views: 5571

Answers (1)

Dan Mašek
Dan Mašek

Reputation: 19041

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:

Upvotes: 5

Related Questions