How to Add Text on Image Using OpenCV in Computer Vision
Use OpenCV's
cv2.putText() function to add text on an image. This function requires the image, text string, position coordinates, font type, font scale, color, thickness, and line type as inputs.Syntax
The cv2.putText() function syntax is:
img: The image where text will be added.text: The string of text to write.org: Bottom-left corner coordinates (x, y) for the text.fontFace: Font type, e.g.,cv2.FONT_HERSHEY_SIMPLEX.fontScale: Size of the font.color: Text color in BGR format, e.g., (255, 0, 0) for blue.thickness: Thickness of the text strokes.lineType: Type of the line, default iscv2.LINE_AAfor anti-aliased lines.
python
cv2.putText(img, text, org, fontFace, fontScale, color, thickness, lineType)
Example
This example loads a blank image, adds blue text at position (50, 150), and displays the image.
python
import cv2 import numpy as np # Create a black image img = np.zeros((300, 600, 3), dtype=np.uint8) # Define text and position text = 'Hello OpenCV' position = (50, 150) # Add text on image cv2.putText(img, text, position, cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 0, 0), 3, cv2.LINE_AA) # Show the image cv2.imshow('Image with Text', img) cv2.waitKey(0) cv2.destroyAllWindows()
Output
A window opens showing a black image with the blue text 'Hello OpenCV' at coordinates (50, 150).
Common Pitfalls
- Using incorrect coordinates can place text outside the visible image area.
- Choosing a font scale or thickness too small or too large can make text unreadable.
- For color, remember OpenCV uses BGR, not RGB, so red is (0, 0, 255).
- Not calling
cv2.imshow()andcv2.waitKey()will prevent the image from displaying.
python
import cv2 import numpy as np img = np.zeros((200, 400, 3), dtype=np.uint8) # Wrong: text outside image # cv2.putText(img, 'Test', (500, 100), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,255,0), 2) # Right: text inside image cv2.putText(img, 'Test', (50, 100), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,255,0), 2) cv2.imshow('Correct Text Position', img) cv2.waitKey(0) cv2.destroyAllWindows()
Output
A window opens showing a black image with green text 'Test' correctly visible at (50, 100).
Quick Reference
| Parameter | Description | Example |
|---|---|---|
| img | Image to draw text on | img = np.zeros((300,600,3), np.uint8) |
| text | Text string to write | 'Hello' |
| org | Bottom-left corner (x,y) of text | (50, 150) |
| fontFace | Font type | cv2.FONT_HERSHEY_SIMPLEX |
| fontScale | Font size scale | 2 |
| color | Text color in BGR | (255, 0, 0) for blue |
| thickness | Thickness of text strokes | 3 |
| lineType | Line type for text edges | cv2.LINE_AA |
Key Takeaways
Use cv2.putText() with correct parameters to add text on images in OpenCV.
Coordinates must be inside the image to see the text.
OpenCV uses BGR color format, not RGB.
Adjust font scale and thickness for clear, readable text.
Always display the image with cv2.imshow() and waitKey() to see results.