cv2.putText() is an OpenCV function used to write text directly on an image. It lets you choose the text content, position, color, thickness, and font style. This is commonly used for labeling objects, adding captions, or marking coordinates on images during computer vision tasks.
Note: For this article we will use a sample image "logo.png", to download click here.
Example: This example loads an image and writes a single text string on it using default settings.
Pythonimport cv2
img = cv2.imread("logo.png")
img = cv2.putText(img, "Hello", (40, 40), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2)
cv2.imshow("Output", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Output
[Output] Explanation: cv2.putText() writes "Hello" at position (40, 40) using a simple font, size 1, blue color (255, 0, 0) and thickness 2.
Syntax
cv2.putText(image, text, org, font, fontScale, color, thickness=1, lineType=cv2.LINE_8, bottomLeftOrigin=False)
Parameters:
- image: Image on which text is drawn
- text: Text string
- org: Bottom-left coordinate of the text
- font: Font style (e.g., FONT_HERSHEY_SIMPLEX)
- fontScale: Size multiplier of the font
- color: Text color in BGR (e.g., (0, 255, 0))
- thickness: Line thickness
- lineType: Type of line (e.g., cv2.LINE_AA for smooth text)
- bottomLeftOrigin: If True, text origin is taken from bottom-left of the image
Examples
Example 1: This example adds a simple text label in the top-left corner of an image.
Pythonimport cv2
img = cv2.imread("logo.png")
img = cv2.putText(img, "OpenCV", (30, 40), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
cv2.imshow("Output", img)
cv2.waitKey(0)
Output
[Output1]Image with OpenCV written in green.Explanation: "OpenCV" is placed at (30, 40) and drawn in green (0, 255, 0) using a smooth font size 1.
Example 2: This example positions text near the bottom of the image using a different color and thicker font.
Pythonimport cv2
img = cv2.imread("logo.png")
img = cv2.putText(img, "Sample Text", (20, 230), cv2.FONT_HERSHEY_SIMPLEX, 1.2, (0, 0, 255), 3)
cv2.imshow("Output", img)
cv2.waitKey(0)
Output
[Output2]Image with Sample Text in red at the bottom.Explanation: "Sample Text" uses a thicker red color (0, 0, 255) and font scale 1.2.
Example 3: Here the text is drawn with the image origin interpreted from the bottom-left by enabling bottomLeftOrigin=True.
Pythonimport cv2
img = cv2.imread("logo.png")
img = cv2.putText(img, "Inverted", (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 0), 2, bottomLeftOrigin=True)
cv2.imshow("Output", img)
cv2.waitKey(0)
Output
[Output3]Text appears inverted vertically depending on the image coordinate orientation.Explanation: bottomLeftOrigin=True makes OpenCV treat the bottom-left of the image as the origin, reversing how the Y-coordinate grows.