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
1 2 3 |
import cv2 events = [i for i in dir(cv2) if 'EVENT' in i] print events |
Below is an example of a simple mouse callback function that draws a circle where we double click.
1 2 3 4 |
# mouse callback function def draw_circle(event,x,y,flags,param): if event == cv2.EVENT_LBUTTONDBLCLK: cv2.circle(img,(x,y),100,(255,0,0),-1) |
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
1 |
cv2.setMouseCallback('img',draw_circle) |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import cv2 import numpy as np font = cv2.FONT_HERSHEY_SIMPLEX # mouse callback function def draw_circle(event,x,y,flags,param): if event == cv2.EVENT_LBUTTONDBLCLK: i = 0 while True: cv2.imshow('image',img) # to display the characters k = cv2.waitKey(0) cv2.putText(img, chr(k) , (x+i,y), font, 0.5, (0, 255, 0), 2, cv2.LINE_AA) i+=10 # Press q to stop writing if k == ord('q'): break # Create a black image, a window and bind the function to window img = np.zeros((512,512,3), np.uint8) cv2.namedWindow('image') cv2.setMouseCallback('image',draw_circle) while True: cv2.imshow('image',img) if cv2.waitKey(20) == 27: break cv2.destroyAllWindows() |
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.