More functions related to text

OpenCV provides more functions in connection with text drawing. It should be noted that these functions are not for drawing text, but they can be used to complement the aforementioned cv2.putText() function, and they are commented as follows. The first function we are going to see is cv2.getFontScaleFromHeight(). The signature for this function is as follows:

retval = cv2.getFontScaleFromHeight(fontFace, pixelHeight, thickness=1)

This function returns the font scale (fontScale), which is a parameter to use in the cv2.putText() function, to achieve the provided height (in pixels) and taking into account both the font type (fontFace) and thickness.

The second function is cv2.getTextSize():

retval, baseLine = cv2.getTextSize(text, fontFace, fontScale, thickness)

This function can be used to get the text size (width and height) based on the following arguments—text to draw, the font type (fontFace), scale, and thickness. This function returns size and baseLine, which corresponds to the coordinate of the baseline relative to the bottom of the text. The next piece of code shows you the key aspects to see this functionality. The full code is available in the text_drawing_bounding_box.py script:

# assign parameters to use in the drawing functions
font = cv2.FONT_HERSHEY_SIMPLEX
font_scale = 2.5
thickness = 5
text = 'abcdefghijklmnopqrstuvwxyz'
circle_radius = 10

# We get the size of the text
ret, baseline = cv2.getTextSize(text, font, font_scale, thickness)

# We get the text width and text height from ret
text_width, text_height = ret

# We center the text in the image
text_x = int(round((image.shape[1] - text_width) / 2))
text_y = int(round((image.shape[0] + text_height) / 2))

# Draw this point for reference:
cv2.circle(image, (text_x, text_y), circle_radius, colors['green'], -1)

# Draw the rectangle (bounding box of the text)
cv2.rectangle(image, (text_x, text_y + baseline), (text_x + text_width - thickness, text_y - text_height),
colors['blue'], thickness)

# Draw the circles defining the rectangle
cv2.circle(image, (text_x, text_y + baseline), circle_radius, colors['red'], -1)
cv2.circle(image, (text_x + text_width - thickness, text_y - text_height), circle_radius, colors['cyan'], -1)

# Draw the baseline line
cv2.line(image, (text_x, text_y + int(round(thickness/2))), (text_x + text_width - thickness, text_y +
int(round(thickness/2))), colors['yellow'], thickness)
# Write the text centered in the image
cv2.putText(image, text, (text_x, text_y), font, font_scale, colors['magenta'], thickness)

The output of this example is given in the next screenshot:

Pay attention to how the three little points (redcyan, and green) are drawn and also to how the yellow baseline is shown.