0
0
Computer-visionHow-ToBeginner ยท 3 min read

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 is cv2.LINE_AA for 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() and cv2.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

ParameterDescriptionExample
imgImage to draw text onimg = np.zeros((300,600,3), np.uint8)
textText string to write'Hello'
orgBottom-left corner (x,y) of text(50, 150)
fontFaceFont typecv2.FONT_HERSHEY_SIMPLEX
fontScaleFont size scale2
colorText color in BGR(255, 0, 0) for blue
thicknessThickness of text strokes3
lineTypeLine type for text edgescv2.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.