Sub topic 11
Adding Text Labels to Images with OpenCV
This chapter assumes that you know basic Python, can install packages with pip, and understand that an OpenCV image is a NumPy array. It also assumes that you can load an image with cv2.imread. The examples use OpenCV's default BGR color order.
OpenCV adds text with cv2.putText. The function changes the image array in place. Its basic form is:
cv2.putText(image, text, origin, font, font_scale, color, thickness, line_type)The origin is the lower-left corner of the text, not its upper-left corner. The point uses (x, y) coordinates. Therefore, x increases from left to right, and y increases from top to bottom.
import cv2
img = cv2.imread("photo.jpg")
if img is None:
raise FileNotFoundError("Could not read photo.jpg")
cv2.putText(
img,
"Camera view",
(30, 60),
cv2.FONT_HERSHEY_SIMPLEX,
1.2,
(255, 255, 255),
2,
cv2.LINE_AA,
)
cv2.imwrite("labeled.jpg", img)FONT_HERSHEY_SIMPLEX selects the typeface. The font scale controls the approximate character size. The color is a BGR tuple, so (255, 255, 255) is white and (0, 0, 255) is red. The thickness is measured in pixels. cv2.LINE_AA enables antialiasing, which usually makes text edges look smoother.
Place text using image coordinates
Text can be clipped if its origin is outside the image or too close to an edge. Since the origin marks the baseline, leave enough space above the chosen y coordinate for the character height.
For labels that must fit different image sizes, calculate the font scale or position from the image dimensions instead of using fixed values. You can also measure text before drawing it with cv2.getTextSize.
import cv2
img = cv2.imread("photo.jpg")
if img is None:
raise FileNotFoundError("Could not read photo.jpg")
label = "Object: car"
font = cv2.FONT_HERSHEY_SIMPLEX
scale = 0.8
thickness = 2
(text_width, text_height), baseline = cv2.getTextSize(
label, font, scale, thickness
)
x = 20
y = 30 + text_height
cv2.rectangle(
img,
(x - 8, y - text_height - 8),
(x + text_width + 8, y + baseline + 8),
(0, 0, 0),
-1,
)
cv2.putText(
img,
label,
(x, y),
font,
scale,
(255, 255, 255),
thickness,
cv2.LINE_AA,
)
cv2.imwrite("labeled_with_background.jpg", img)getTextSize returns the text width, text height, and baseline size. The example uses those measurements to draw a black rectangle behind the label. This improves contrast when the image contains bright or complex areas.
Preserve the original image
Drawing functions modify their input array. If you need the unmodified image later, draw on a copy:
annotated = img.copy()
cv2.putText(annotated, "Preview", (20, 40), font, 1, (0, 255, 255), 2, cv2.LINE_AA)This same rule applies to rectangles, circles, polygons, and other annotations.
Exercise
Why might text drawn at origin (20, 20) appear clipped at the top of an image?
Show answer
The origin is the text baseline, so the characters extend upward from y = 20 and may cross the image boundary.