OpenCV can also be used to write text on images. We can write text with different size and style on images with different background and foreground styles using OpenCV. In this tutorial we will write text on images using opencv cv2.putText()
method.
Parameters for this method are as follows.
- Image
- Text - text string that we want to write
- Coordinates - Text drawing start point (Bottom-Left)
- Font Face - Font faces to be drawn, view details below.
- Font Scale - Factor that is multiplied by the font-specific base size.
- Color - Color of text
- Thickness - Thickness of font
View more details at This URL. Font Face provided by opencv are as follows.
FONT_HERSHEY_SIMPLEX = 0,
FONT_HERSHEY_PLAIN = 1,
FONT_HERSHEY_DUPLEX = 2,
FONT_HERSHEY_COMPLEX = 3,
FONT_HERSHEY_TRIPLEX = 4,
FONT_HERSHEY_COMPLEX_SMALL = 5,
FONT_HERSHEY_SCRIPT_SIMPLEX = 6,
FONT_HERSHEY_SCRIPT_COMPLEX = 7,
FONT_ITALIC = 16
Now we can write some text on image using opencv.
import cv2
image = cv2.imread("images/default.png")
# define font face
font = cv2.FONT_HERSHEY_SIMPLEX
# font color, scale and thickness
color = (255, 0, 0)
font_scale = 1
thickness = 1
# draw two text string on (80, 80) and (400, 300)
image = cv2.putText(image, "This is some text", (80, 80), font, font_scale, color, thickness)
image = cv2.putText(image, "This text string is in center", (400, 300), font, font_scale, color, thickness)
# show image
cv2.imshow("image", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
Now we can also iterate over each of font face and view how it looks like for same text.
import cv2
image = cv2.imread("images/plane.png")
# all font faces
all_fonts = {
"FONT_HERSHEY_SIMPLEX" : 0,
"FONT_HERSHEY_PLAIN" : 1,
"FONT_HERSHEY_DUPLEX" : 2,
"FONT_HERSHEY_COMPLEX" : 3,
"FONT_HERSHEY_TRIPLEX" : 4,
"FONT_HERSHEY_COMPLEX_SMALL" : 5,
"FONT_HERSHEY_SCRIPT_SIMPLEX" : 6,
"FONT_HERSHEY_SCRIPT_COMPLEX" : 7,
"FONT_ITALIC" : 16
}
# iterate and draw text using all font face.
for i, key in enumerate(all_fonts):
image = cv2.putText(image, f"This text is using {key}", (80, 80 + (50 * i)), all_fonts[key], font_scale, (0, 0, 255), thickness)
cv2.imshow("image", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
So, this way we can use multiple font face for drawing on images using opencv. We can increase font scale and thickness to increase font size and its area according to scale. For more details for writing text on images using opencv, view official opencv documentation.
Comments (0)