Introduction
In this tutorial, I will show how you can find Coordinates of the Clicked Points on an Image using a python program. Or you can say this topic is Capturing Mouse Events in Python.
It is very useful when you will try to make your mouse a paintbrush(for finding the coordinates of each point, around a specific object on an image).
In the program, I've used the Python OpenCV library to handle mouse events. As per the OpenCV Documentation, the library offers to work with several Mouse Events. Let's find out them.
☛Related: Draw Messi's Face using a Python Program | Animation with Python
List of all Mouse Events
These three lines of python code will display the names of all the mouse events that OpenCV offers.
Code
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']
Since we are only trying to find the coordinates of the clicked points, "cv2.EVENT_LBUTTONDOWN" can make our task done. Let's come to the main program.
The Main Program
Import the module
import cv2
The 'Capture_Event()' function
Whenever the left mouse button is pressed, this function will print the x-y coordinates of that 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 function
The main function reads an image through cv2.imread() function, displays that image, set the cv2.setMouseCallback() function, and give options to destroy the windows.
Read what file formats OpenCV supports in the cv2.imread() function from here.
I've added a single comment line before each line of the code. It will help you to know the objectives of the program better.
# The Main Function
if __name__=="__main__":
# Read the Image.
img = cv2.imread('Messi.jpg', 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()