Handling Mouse Clicks in OpenCV

Handling mouse clicks in OpenCV enables interactive applications where users can interact with images or video frames. By capturing mouse events, such as clicks or movements, developers can implement functionalities like selecting regions of interest (ROIs), annotating images, or triggering specific actions based on user input. This capability adds an interactive dimension to computer vision applications, allowing for intuitive user interactions and enhanced usability. 

Example program to handle mouse clicks: 

import cv2 

evt=

def mouseClick(event,xPos,yPos,flags,params): 

   global evt 

   global pnt 

   if event==cv2.EVENT_LBUTTONDOWN: 

       print (“Mouse event was:”,event) 

       print (“at position:”, xPos,yPos) 

       evt=event 

       pnt=(xPos,yPos) 

   if event==cv2.EVENT_LBUTTONUP: 

       print (“Mouse event was:”,event) 

       print (“at position:”, xPos,yPos) 

       evt=event 

       pnt=(xPos,yPos) 

   if event==cv2.EVENT_RBUTTONDOWN: 

       print (“Mouse event was:”,event) 

       print (“at position:”, xPos,yPos) 

       evt=event 

       pnt=(xPos,yPos) 

width=640 

height=360 

cam=cv2.VideoCapture(0, cv2. CAP_DSHOW) 

cam.set(cv2.CAP_PROP_FRAME_WIDTH, width) 

cam.set(cv2.CAP_PROP_FRAME_HEIGHT, height) 

cam.set(cv2.CAP_PROP_FPS,30

 

cv2.namedWindow(‘my WEBcam’

cv2.setMouseCallback(‘my WEBcam’,mouseClick) 

while True: 

   ignore, frame=cam.read() 

   if evt==1 or evt==4

       cv2.circle(frame, pnt,15, (255,0,0),2

   cv2.imshow(‘my WEBcam’, frame

   cv2.moveWindow(‘my WEBcam’,0,0

   if cv2.waitKey(1) & 0xff==ord(‘q’): 

       break 

cam.release 

Leave a comment

Your email address will not be published. Required fields are marked *