Sub topic 11
Adding Text Labels
This chapter covers cv2.putText, the function that writes text onto an image. It assumes you have read the earlier chapters on loading images and on drawing conventions: (x, y) points, BGR color tuples, and drawing on a copy. You should be comfortable with img.shape and with tuples in Python.
What putText does
cv2.putText rasterizes a string into the pixel array. After the call the text is ordinary pixels, so you can't edit or move it. Like the other drawing functions, it modifies the array in place and also returns it.
import cv2
img = cv2.imread("photo.jpg")
if img is None:
raise FileNotFoundError("Could not read photo.jpg")
canvas = img.copy()
cv2.putText(
canvas, # image to draw on (modified in place)
"Label", # text, ASCII only
(50, 40), # org: (x, y) of the bottom-left corner of the text
cv2.FONT_HERSHEY_SIMPLEX, # fontFace
1.0, # fontScale
(255, 255, 255), # color in BGR
2, # thickness in pixels
cv2.LINE_AA, # lineType: anti-aliased
)
cv2.imwrite("labeled.jpg", canvas)The parameters, in order:
| Parameter | Meaning | Common mistake |
|---|---|---|
| `org` | `(x, y)` of the bottom-left corner of the first character, on the text baseline | Treating it as the top-left corner, so the text lands one line too high |
| `fontFace` | One of the `cv2.FONT_HERSHEY_*` constants | Expecting system fonts such as Arial |
| `fontScale` | Multiplier on the font's base glyph size | Treating it as a pixel height |
| `color` | BGR tuple | Passing RGB, so red text comes out blue |
| `thickness` | Stroke width in whole pixels | Passing a float, which raises an error |
| `lineType` | `cv2.LINE_8` (default), `cv2.LINE_4` or `cv2.LINE_AA` | Leaving the default and getting jagged edges |
The origin is the baseline
The baseline is the imaginary line that letters sit on. Most letters rest on it. Descenders, the tails of g, j, p, q and y, hang below it.
This is the most common source of misplaced labels. If you pass org=(10, 0), the text sits on the top edge of the image and almost all of it is off-screen. Text that falls outside the image is clipped without an error.
Passing bottomLeftOrigin=True as the last argument flips the text vertically, as if the image's y-axis pointed up. You rarely want this.
Fonts and scale
OpenCV ships a small set of Hershey vector fonts. They are drawn as strokes, not loaded from font files.
| Constant | Style |
|---|---|
| `FONT_HERSHEY_SIMPLEX` | Normal sans-serif, a good default |
| `FONT_HERSHEY_PLAIN` | Small sans-serif, compact |
| `FONT_HERSHEY_DUPLEX` | Heavier sans-serif |
| `FONT_HERSHEY_COMPLEX` | Serif |
| `FONT_HERSHEY_TRIPLEX` | Heavier serif |
| `FONT_HERSHEY_COMPLEX_SMALL` | Smaller serif |
| `FONT_HERSHEY_SCRIPT_SIMPLEX` | Handwriting style |
| `FONT_HERSHEY_SCRIPT_COMPLEX` | Heavier handwriting style |
You can combine any of these with cv2.FONT_ITALIC using the bitwise OR operator, for example cv2.FONT_HERSHEY_SIMPLEX | cv2.FONT_ITALIC.
fontScale multiplies the base size. With FONT_HERSHEY_SIMPLEX, a scale of 1.0 gives capital letters roughly 22 pixels tall. A scale that looks right on a 640-pixel-wide image looks tiny on a 4000-pixel-wide photo. When your images vary in size, scale the font with the image, for example scale = w / 1000. Round the thickness to an integer of at least 1, for example max(1, round(scale * 2)).
Measuring text with getTextSize
To place text precisely, you need to know how big it will be. cv2.getTextSize takes the text, font, scale and thickness, and returns ((width, height), baseline).
widthandheightdescribe the text above the baseline. Descenders are not included inheight.baselineis the distance in pixels from the baseline down to the lowest point of the text, which covers descenders.
The total vertical extent is height + baseline. The call draws nothing, so you can call it as often as you like.
Centering text
Once you have the width and height, centering is arithmetic. The bottom-left origin must be shifted left by half the width and down by half the height.
import cv2
img = cv2.imread("photo.jpg")
if img is None:
raise FileNotFoundError("Could not read photo.jpg")
canvas = img.copy()
h, w = canvas.shape[:2]
text = "Centered"
font = cv2.FONT_HERSHEY_SIMPLEX
scale = 1.5
thickness = 3
(tw, th), baseline = cv2.getTextSize(text, font, scale, thickness)
org = ((w - tw) // 2, (h + th) // 2)
cv2.putText(canvas, text, org, font, scale, (0, 255, 255), thickness, cv2.LINE_AA)
cv2.imwrite("centered.jpg", canvas)The + th in the y coordinate moves the baseline down so the glyphs, which extend upward from it, are vertically centered. Descenders hang slightly below the middle. That is usually acceptable. If you need exact centering of a string with descenders, use (h + th - baseline) // 2 instead.
Labels that stay readable
White text on a bright sky disappears. The standard fix is to draw a filled rectangle behind the text, which is the same pattern detectors use for class labels. The helper below does three things:
- It measures the text.
- It sizes the box from that measurement.
- It clamps the box so it never leaves the image.
import cv2
def draw_label(
image,
text,
top_left,
font=cv2.FONT_HERSHEY_SIMPLEX,
scale=0.6,
thickness=1,
text_color=(255, 255, 255),
bg_color=(0, 0, 0),
pad=4,
):
"""Draw text on a filled box whose top-left corner is near top_left."""
(tw, th), baseline = cv2.getTextSize(text, font, scale, thickness)
img_h, img_w = image.shape[:2]
box_w = tw + 2 * pad
box_h = th + baseline + 2 * pad
# Keep the whole box inside the image
x = max(0, min(top_left[0], img_w - box_w))
y = max(0, min(top_left[1], img_h - box_h))
cv2.rectangle(image, (x, y), (x + box_w, y + box_h), bg_color, -1)
# The baseline sits th pixels below the top of the glyphs
cv2.putText(
image, text, (x + pad, y + pad + th), font, scale, text_color, thickness, cv2.LINE_AA
)
return image
img = cv2.imread("photo.jpg")
if img is None:
raise FileNotFoundError("Could not read photo.jpg")
canvas = img.copy()
cv2.rectangle(canvas, (100, 80), (300, 220), (0, 255, 0), 2)
draw_label(canvas, "person 0.92", (100, 80 - 30))
cv2.imwrite("labeled_box.jpg", canvas)The label is placed 30 pixels above the top of the rectangle. If the rectangle is near the top edge, the clamp pushes the label down instead of letting it be clipped.
Multiple lines
putText does not handle newline characters. A \n in the string is drawn as a question mark or ignored, depending on the build. To write several lines, split the string yourself and move the origin down for each one.
import cv2
img = cv2.imread("photo.jpg")
if img is None:
raise FileNotFoundError("Could not read photo.jpg")
canvas = img.copy()
font = cv2.FONT_HERSHEY_SIMPLEX
scale = 0.8
thickness = 2
lines = ["Width: %d" % canvas.shape[1], "Height: %d" % canvas.shape[0], "Channels: 3"]
(_, th), baseline = cv2.getTextSize("Ag", font, scale, thickness)
line_height = th + baseline + 6 # 6 px of extra spacing
x, y = 20, 20 + th
for line in lines:
cv2.putText(canvas, line, (x, y), font, scale, (0, 255, 0), thickness, cv2.LINE_AA)
y += line_height
cv2.imwrite("multiline.jpg", canvas)Measuring "Ag" gives a line height that includes both a tall letter and a descender. This keeps spacing consistent whatever the actual text says.
Edge cases and gotchas
- ASCII only. The Hershey fonts contain basic Latin characters. Accented letters, CJK characters and emoji are drawn as
?. For other scripts, render the text with Pillow (ImageDraw.textand a TrueType font) or withcv2.freetypefrom theopencv-contrib-pythonpackage. If you use Pillow, convert BGR to RGB before handing it the array and convert back afterwards. - Integer coordinates.
orgmust be a tuple of Python ints. Values from NumPy division, such asw / 2, are floats and raise aTypeErrorin recent OpenCV versions. Use//orint(). - Integer thickness. Thickness is an int of at least 1. The
-1fill value that works for shapes is not meaningful for text. - Grayscale images. On a single-channel image, only the first value of the color tuple is used. Pass
(255,)or a plain number. - Aliasing. Without
cv2.LINE_AA, small text looks jagged. Anti-aliasing is slightly slower, which rarely matters outside real-time video. - Draw after resizing. Text drawn before a resize is scaled with the image and becomes blurry or misshapen. Resize first, then add labels at the final resolution.
- Original is modified.
putTextwrites into the array you pass. Draw onimg.copy()if you still need the clean image.
Exercises
Exercise
You call cv2.putText(canvas, "Top", (10, 0), cv2.FONTHERSHEYSIMPLEX, 1, (255, 255, 255), 2) and see almost nothing in the image. Why, and how do you fix it?
Show answer
The origin is the bottom-left of the text on the baseline, so y = 0 puts the baseline on the top edge and the glyphs extend upward, outside the image, where they are clipped. Move the baseline down by at least the text height. Call cv2.getTextSize to get ((tw, th), baseline), then use an origin such as (10, th + 10).
Exercise
Write the line of code that computes the origin needed to center the string text horizontally in an image of width w, given (tw, th), baseline = cv2.getTextSize(text, font, scale, thickness), with the baseline at y = 50.
Show answer
org = ((w - tw) // 2, 50). Integer division keeps the coordinates as ints, which putText requires. The y value is already the baseline position, so no adjustment is needed.
Exercise
Why does draw_label use th + baseline + 2 pad for the box height instead of th + 2 pad?
Show answer
getTextSize reports the height above the baseline in th and reports the space below the baseline, used by descenders such as g and y, separately in baseline. Leaving out baseline would cut the descenders off at the bottom edge of the box.