How to write text on a image in windows using python opencv2 How to write text on a image in windows using python opencv2 windows windows

How to write text on a image in windows using python opencv2


This code uses cv2.putText to overlay text on an image. You need NumPy and OpenCV installed.

import numpy as npimport cv2# Create a black imageimg = np.zeros((512,512,3), np.uint8)# Write some Textfont                   = cv2.FONT_HERSHEY_SIMPLEXbottomLeftCornerOfText = (10,500)fontScale              = 1fontColor              = (255,255,255)lineType               = 2cv2.putText(img,'Hello World!',     bottomLeftCornerOfText,     font,     fontScale,    fontColor,    lineType)#Display the imagecv2.imshow("img",img)#Save imagecv2.imwrite("out.jpg", img)cv2.waitKey(0)


Was CV_FONT_HERSHEY_SIMPLEX in cv(1)?Here's all I have available for cv2 "FONT":

FONT_HERSHEY_COMPLEXFONT_HERSHEY_COMPLEX_SMALLFONT_HERSHEY_DUPLEXFONT_HERSHEY_PLAINFONT_HERSHEY_SCRIPT_COMPLEXFONT_HERSHEY_SCRIPT_SIMPLEXFONT_HERSHEY_SIMPLEXFONT_HERSHEY_TRIPLEXFONT_ITALIC

Dropping the 'CV_' seems to work for me.

cv2.putText(image,"Hello World!!!", (x,y), cv2.FONT_HERSHEY_SIMPLEX, 2, 255)


I had a similar problem. I would suggest using the PIL library in python as it draws the text in any given font, compared to limited fonts in OpenCV. With PIL you can choose any font installed on your system.

from PIL import ImageFont, ImageDraw, Imageimport numpy as npimport cv2image = cv2.imread("lena.png")# Convert to PIL Imagecv2_im_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)pil_im = Image.fromarray(cv2_im_rgb)draw = ImageDraw.Draw(pil_im)# Choose a fontfont = ImageFont.truetype("Roboto-Regular.ttf", 50)# Draw the textdraw.text((0, 0), "Your Text Here", font=font)# Save the imagecv2_im_processed = cv2.cvtColor(np.array(pil_im), cv2.COLOR_RGB2BGR)cv2.imwrite("result.png", cv2_im_processed)

result.png