In this blog, we will learn how to use OpenCV cv2.putText() function for writing text on images in real-time. Most of you might have used cv2.putText(), if not this is how it looks like.
cv2.putText(img, text, position, font, fontScale, color, thickness, lineType, bottomLeftOrigin)
The above function draws the text on the input image at the specified position. If the specified font is unable to render any character, it is replaced by a question mark.
Another important thing that we will be using is OpenCV cv2.waitKey() function. This returns -1 when no key is pressed otherwise returns the ASCII value of the key pressed or a 32-bit integer value depending upon the platform or keyboard modifier(Num lock etc.). You can find this by printing the key as shown below.
1 2 3 4 5 6 7 8 9 10 |
import cv2 import numpy as np img = np.zeros((500,500,3),dtype = 'uint8') # Create a dummy image while True: cv2.imshow('a',img) k = cv2.waitKey(0) print(k) if k == ord('q'): break cv2.destroyAllWindows() |
If it returns a 32-bit integer, then use cv2.waitKey() & 0xFF which leaves only the last 8 bits of the original 32 bit.
ord(‘q’) converts the character to an int while chr(113) does exactly the opposite as shown in the code below.
1 2 3 4 |
>>> ord('q') 113 >>> chr(113) 'q' |
I hope you understand all this, now let’s get started
Steps:
- Read the image and initialize the counter that will be used for changing the position of the text.
- Inside an infinite while loop,
- display the image and use cv2.waitKey() for a keypress.
- Convert this key into character using chr() and draw it on the image using cv2.putText().
- Increase the counter.
- Provide the termination condition
- On exit, destroy all windows.
Below is the code for this
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import cv2 # Read the image img = cv2.imread('D:/downloads/original_image.png') # initialize counter i = 0 while True: # Display the image cv2.imshow('a',img) # wait for keypress k = cv2.waitKey(0) # specify the font and draw the key using puttext font = cv2.FONT_HERSHEY_SIMPLEX cv2.putText(img,chr(k),(140+i,250), font, .5,(255,255,255),2,cv2.LINE_AA) i+=10 if k == ord('q'): break cv2.destroyAllWindows() |
The output looks like this
Hope you enjoy reading. In the next blog, we will learn how to write text on images at mouse click position.
If you have any doubt/suggestion please feel free to ask and I will do my best to help or improve myself. Good-bye until next time.