Tag Archives: real time text on images

Write Text on images at mouse click position using OpenCV-Python

In the previous blog, we discussed how to write text on images in real-time. In that, we manually specified the position for text placement. This is quite tedious if we were to write text at multiple positions.

So, what if we automate this process. That is we automatically get the coordinates of the image where we click and then put text at that position using cv2.putText() function as we did in the previous blog.

This is what we will do in this blog i.e. write text on images at mouse click position. To do this, we will create a mouse callback function and then bind this function to the image window.

Mouse callback function is executed whenever a mouse event takes place. Mouse event refers to anything we do with the mouse like double click, left click etc. All available events can be found using the following code

Below is an example of a simple mouse callback function that draws a circle where we double click.

We then need to bind this callback function to the image window. This is done using
cv2.setMouseCallback(window_name, mouse_callback_function) as shown below

I hope you understood mouse callback function, now let’s get started

Steps:

  • Create a mouse callback function where on every left double click position we put text on the image.
  • Create or read an image.
  • Create an image window using cv2.namedWindow()
  • Bind the mouse callback function to the image window using cv2.setMouseCallback()
  • Display the new image using an infinite while loop

Code:

In the above code, press ‘q’ to stop writing and left double click anywhere to again start writing.

You can play with mouse callback function using other mouse events. Hope you enjoy reading.

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.