In this tutorial, we will use an example to show you how to bind and process mouse events using cv2.setMouseCallback() in python opencv.
1.Read and show an image in opencv
import cv2 img = cv2.imread('C:/Users/N/Desktop/test.png') cv2.imshow('image', img)
2.Bind mouse event using cv2.setMouseCallback()
cv2.setMouseCallback('image', drawCircle)
In this code, we will use drawCircle() function to process mouse event.
3.Implement mouse event process function
def drawCircle(event, x, y, flags, param): if event == cv2.EVENT_MOUSEMOVE: print('({}, {})'.format(x, y)) imgCopy = img.copy() cv2.circle(imgCopy, (x, y), 10, (255, 0, 0), -1) cv2.imshow('image', imgCopy)
4.Release resources
cv2.waitKey(0) cv2.destroyAllWindows()
Run this code, you will see this result.