鼠标事件
打印所有鼠标事件
import cv2 as cv events = [i for i in dir(cv) if 'EVENT' in i] print( events )
#['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']
将窗口与鼠标事件绑定
cv2.setMouseCallback(windowName, MouseCallback, param=None)
windowName:窗口名称
MouseCallback:鼠标响应回调函数
param:响应函数传递的的参数
鼠标响应回调函数
MouseCallback (int event, int x, int y, int flags, void *userdata)
event:一个MouseEventTypes 常量
x:鼠标的x坐标
y:鼠标的y坐标
flags:一个MouseEventFlags常量
userdata:可选参数
MouseEventFlags :
cv.EVENT_FLAG_LBUTTON = 1, 左键拖拽
cv.EVENT_FLAG_RBUTTON = 2, 右键拖拽
cv.EVENT_FLAG_MBUTTON = 4, 中键不放
cv.EVENT_FLAG_CTRLKEY = 8,按住ctrl不放
cv.EVENT_FLAG_SHIFTKEY = 16, 按住shift不放
cv.EVENT_FLAG_ALTKEY = 32 ,按住alt不放
cv.MouseEventTypes :
cv.EVENT_MOUSEMOVE = 0, 鼠标移动
cv.EVENT_LBUTTONDOWN = 1, 左键按下
cv.EVENT_RBUTTONDOWN = 2, 右键按下
cv.EVENT_MBUTTONDOWN = 3, 中键按下
cv.EVENT_LBUTTONUP = 4, 左键释放
cv.EVENT_RBUTTONUP = 5, 右键释放
cv.EVENT_MBUTTONUP = 6, 中键释放
cv.EVENT_LBUTTONDBLCLK = 7, 左键双击
cv.EVENT_RBUTTONDBLCLK = 8, 右键双击
cv.EVENT_MBUTTONDBLCLK = 9, 中健双击
cv.EVENT_MOUSEWHEEL = 10, 滚轮滑动
cv.EVENT_MOUSEHWHEEL = 11 横向滚轮滑动
综合示例
import numpy as np import cv2 as cv drawing = False # true if mouse is pressed ix, iy = -1, -1 def draw_circle(event, x, y, flags, param): global ix, iy, drawing, mode if event == cv.EVENT_LBUTTONDOWN: drawing = True ix, iy = x, y elif event == cv.EVENT_MOUSEMOVE: if drawing is True: cv.circle(img, (ix, iy), abs(y-iy), (0, 0, 255), -1) elif event == cv.EVENT_LBUTTONUP: drawing = False cv.circle(img, (ix, iy), abs(y-iy), (0, 0, 255), -1) img = np.zeros((512, 512, 3), np.uint8) cv.namedWindow('image') cv.setMouseCallback('image', draw_circle) while(1): cv.imshow('image', img) k = cv.waitKey(1) & 0xFF if k == 27: break cv.destroyAllWindows()