How to use OpenCV to retrieve mouse moving coordinates?

To obtain the coordinates of mouse movement using OpenCV, you can achieve it through the following steps:

  1. Import the OpenCV and numpy libraries.
import cv2
import numpy as np
  1. Create a callback function to fetch the coordinates of the mouse movement.
def get_mouse_position(event, x, y, flags, param):
    if event == cv2.EVENT_MOUSEMOVE:
        print("Mouse position:", x, y)
  1. Create a window, attach mouse events, and callback functions.
cv2.namedWindow("image")
cv2.setMouseCallback("image", get_mouse_position)
  1. Load the image and display the window, waiting for mouse movement events.
image = cv2.imread("image.jpg")
cv2.imshow("image", image)
cv2.waitKey(0)

The complete example code is shown below:

import cv2
import numpy as np

def get_mouse_position(event, x, y, flags, param):
    if event == cv2.EVENT_MOUSEMOVE:
        print("Mouse position:", x, y)

cv2.namedWindow("image")
cv2.setMouseCallback("image", get_mouse_position)

image = cv2.imread("image.jpg")
cv2.imshow("image", image)
cv2.waitKey(0)
cv2.destroyAllWindows()

After running the code, the current mouse coordinates will be printed in the console whenever the mouse is moved within the image window.

bannerAds