Write Text on images in real-time using OpenCV-Python

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.

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.

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

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.

Leave a Reply