Displaying the coordinates of the points clicked on the image using Python-OpenCV
Interacting with images is an essential task in computer vision applications. Using OpenCV in Python, we can capture mouse events such as clicks and display the corresponding pixel coordinates directly on the image. This technique is commonly used in annotation, region-of-interest (ROI) selection and debugging computer vision algorithms.
Prerequisites: OpenCV module
Install OpenCV using pip if not already installed:
pip install opencv-python
Understanding Mouse Events in OpenCV
OpenCV allows us to track different types of mouse events. To see all available events, run:
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
Algorithm
- Import the cv2 module.
- Read an image using cv2.imread().
- Display the image in a window using cv2.imshow().
- Define a user-defined function (click_event) that will handle mouse events.
- Set the mouse callback for the image window using cv2.setMouseCallback().
- In the callback, left-click shows (x, y) coordinates, right-click shows RGB values of the pixel.
- Use cv2.waitKey(0) to keep the window open until a key is pressed.
- Close the window with cv2.destroyAllWindows().
We will be using the below colored version of the Lena image.

Python Implementation
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, f"{x},{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, g, r = img[y, x]
cv2.putText(img, f"{b},{g},{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: