opencv
  1. opencv-mouse-event

Mouse Event - ( User Interaction with OpenCV )

Heading h2

Syntax

cv2.setMouseCallback(window_name, on_mouse, param=None)

Example

import cv2

def draw_circle(event, x, y, flags, param):
    if event == cv2.EVENT_LBUTTONUP:
        cv2.circle(img, (x, y), 50, (0, 255, 0), -1)

img = cv2.imread('image.jpg')
cv2.namedWindow('image')
cv2.setMouseCallback('image', draw_circle)

while True:
    cv2.imshow('image', img)
    if cv2.waitKey(20) & 0xFF == 27:
        break

cv2.destroyAllWindows()

Output

The output displays an image window where the user can click anywhere to draw a circle with the specified parameters.

Explanation

In OpenCV, cv2.setMouseCallback() is used to handle mouse events and perform actions based on user interactions. The function takes in the name of the window, a callback function that handles the event, and an optional parameter.

In the above example, we define a callback function draw_circle() to draw a circle in the image window at the location where the user clicks. We then pass this function to cv2.setMouseCallback() along with the name of the window.

The cv2.imshow() function is used to display the image, and cv2.waitKey() is used to capture any keyboard events. The loop runs until the user presses the "Esc" key.

Use

Mouse events in OpenCV can be used to enable user interaction in various computer vision applications. It can be used for object tracking, object selection, drawing annotations, etc.

Important Points

  • cv2.setMouseCallback() is used to handle mouse events in OpenCV
  • The function takes in the name of the window, a callback function, and an optional parameter
  • Mouse events can be used to enable user interaction in computer vision applications
  • Some common mouse events include left button down, left button up, right button down, right button up, and mouse movement.

Summary

In conclusion, mouse events in OpenCV are an important tool for enabling user interaction in computer vision applications. cv2.setMouseCallback() is used to handle mouse events and perform actions based on user interactions. The function takes in the name of the window, a callback function, and an optional parameter. Some common mouse events include left button down, left button up, right button down, right button up, and mouse movement.

Published on: