
Introduction
In this tutorial, we will learn how to find the coordinates of clicked points on an image using a Python program. Alternatively, you can consider this tutorial as an exploration of capturing mouse events in Python. This feature is useful when you want to use your mouse like a paintbrush and figure out the coordinates of points around a specific object in an image.
Weāre going to use the Python OpenCV library to handle mouse events. According to the OpenCV Documentation, the library supports different types of mouse events. Letās explore them.
Recommended Post: Learn How to Sketch Lionel Messi using a Python Code
All Mouse Events at a Glance
The OpenCV library offers various mouse events. Letās find out all of them using a Python program.
import cv2 as cv
events = [i for i in dir(cv) if 'EVENT' in i]
print( events )
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ā]
Finding the coordinates of clicked points
As weāre interested in finding the coordinates of clicked points in an image, using ācv2.EVENT_LBUTTONDOWNā will befit for our task. Letās make a program for it.
Importing the module
Letās import the cv2
module.
import cv2
Creating the `Capture_Event` function
The Capture_Event
function takes parameters related to mouse events. It checks if the left mouse button is pressed (ācv2.EVENT_LBUTTONDOWNā) and, if true, prints the coordinates of the clicked point.
def Capture_Event(event, x, y, flags, params):
# If the left mouse button is pressed
if event == cv2.EVENT_LBUTTONDOWN:
# Print the coordinate of the
# clicked point
print(f"({x}, {y})")
The Main Execution Block
The code, within the main execution block, reads and displays the selected image, and sets up a mouse callback function using Capture_Event
, waits for a key press to exit, and then closes all open windows.
Please read the file formats supported by OpenCV in the cv2.imread
function by checking here.
if __name__=="__main__":
# Read the Image.
img = cv2.imread('Your Image Here', 1)
# Show the Image
cv2.imshow('image', img)
# Set the Mouse Callback function, and call
# the Capture_Event function.
cv2.setMouseCallback('image', Capture_Event)
# Press any key to exit
cv2.waitKey(0)
# Destroy all the windows
cv2.destroyAllWindows()
Output
Watch the entire video to understand how the program above finds the coordinates of clicked points in an image.