OpenCV helps us to control and manage different types of mouse events and gives us the flexibility to operate them. There are many types of mouse events. These events can be displayed by running the following code segment :
import cv2
[print(i) for i in dir(cv2) if 'EVENT' in i]
Output :
EVENT_FLAG_ALTKEY
EVENT_FLAG_CTRLKEY
EVENT_FLAG_LBUTTON
EVENT_FLAG_MBUTTON
EVENT_FLAG_RBUTTON
EVENT_FLAG_SHIFTKEY
EVENT_LBUTTONDBLCLK
EVENT_LBUTTONDOWN
EVENT_LBUTTONUP
EVENT_MBUTTONDBLCLK
EVENT_MBUTTONDOWN
EVENT_MBUTTONUP
EVENT_MOUSEHWHEEL
EVENT_MOUSEMOVE
EVENT_MOUSEWHEEL
EVENT_RBUTTONDBLCLK
EVENT_RBUTTONDOWN
EVENT_RBUTTONUP
Now let us see how to display the coordinates of the points clicked on the image. We will be displaying both the points clicked by right-click as well as left-click.
Algorithm :
- Import the cv2 module.
- Import the image using the cv2.imread() function.
- Display the image the image using the cv2.imshow() function.
- Call the cv2.setMouseCallback() function and pass the image window and the user-defined function as parameters.
- In the user-defined function, check for left mouse clicks using the cv2.EVENT_LBUTTONDOWN attribute.
- Display the coordinates on the Shell.
- Display the coordinates on the created window.
- Do the same for right mouse clicks using the cv2.EVENT_RBUTTONDOWN attribute. Change the color while displaying the coordinates on the image to distinguish from left clicks.
- Outside the user-defined function, use the cv2.waitKey(0) and the cv2.destroyAllWindows() functions to close the window and terminate the program.
We will be using the colored version of the Lena image.

Python3
import cv2
def click_event(event, x, y, flags, params):
if event = = cv2.EVENT_LBUTTONDOWN:
print (x, ' ' , y)
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(img, str (x) + ',' +
str (y), (x,y), font,
1 , ( 255 , 0 , 0 ), 2 )
cv2.imshow( 'image' , img)
if event = = cv2.EVENT_RBUTTONDOWN:
print (x, ' ' , y)
font = cv2.FONT_HERSHEY_SIMPLEX
b = img[y, x, 0 ]
g = img[y, x, 1 ]
r = img[y, x, 2 ]
cv2.putText(img, str (b) + ',' +
str (g) + ',' + str (r),
(x,y), font, 1 ,
( 255 , 255 , 0 ), 2 )
cv2.imshow( 'image' , img)
if __name__ = = "__main__" :
img = cv2.imread( 'lena.jpg' , 1 )
cv2.imshow( 'image' , img)
cv2.setMouseCallback( 'image' , click_event)
cv2.waitKey( 0 )
cv2.destroyAllWindows()
|
Output :
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
03 Jan, 2023
Like Article
Save Article