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

Chandra Shaker Balure picture Chandra Shaker Balure · May 17, 2013 · Viewed 183.5k times · Source

I want to put some text on an Image. I am writing the code as:

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

It gives ERROR, saying 'module' object has no attribute 'CV_FONT_HERSHEY_SIMPLEX'

Query Can't I use the font type as above? I searched in internet, but found only the syntax related to to Opencv C++ for initFont. Then I thought of using putText to pass the font type as parameter. But it is not working for me.

Any suggestions?

Answer

Vinay Vemula picture Vinay Vemula · Dec 14, 2015

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

import numpy as np
import cv2

# Create a black image
img = np.zeros((512,512,3), np.uint8)

# Write some Text

font                   = cv2.FONT_HERSHEY_SIMPLEX
bottomLeftCornerOfText = (10,500)
fontScale              = 1
fontColor              = (255,255,255)
lineType               = 2

cv2.putText(img,'Hello World!', 
    bottomLeftCornerOfText, 
    font, 
    fontScale,
    fontColor,
    lineType)

#Display the image
cv2.imshow("img",img)

#Save image
cv2.imwrite("out.jpg", img)

cv2.waitKey(0)