import cv2 as cv
events = [i for i in dir(cv) if 'EVENT' in i]
print( events ) # 将鼠标事件显示出来
'''
EVENT_FLAG_LBUTTON = 1 摁住左键
EVENT_FLAG_RBUTTON = 2 摁住右键
EVENT_FLAG_MBUTTON = 4 摁住中键
EVENT_FLAG_CTRLKEY = 8 摁住Ctrl
EVENT_FLAG_SHIFTKEY = 16 摁住Shift
EVENT_FLAG_ALTKEY = 32 摁住Alt
EVENT_MOUSEMOVE = 0 鼠标移动
EVENT_LBUTTONDOWN = 1 左键击下
EVENT_RBUTTONDOWN = 2 右键击下
EVENT_MBUTTONDOWN = 3 中键击下
EVENT_LBUTTONUP = 4 左键弹起
EVENT_RBUTTONUP = 5 右键弹起
EVENT_MBUTTONUP = 6 中键弹起
EVENT_LBUTTONDBLCLK = 7 左键双击
EVENT_RBUTTONDBLCLK = 8 右键双击
EVENT_MBUTTONDBLCLK = 9 中键双击
EVENT_MOUSEWHEEL = 10 滚动条向上,flags>0。向下,flags<0
EVENT_MOUSEHWHEEL = 11 滚动条向左,flags>0。向右,flags<0
'''
上半部分对应下面的函数参数中的flags
,下半部分对应event
。
注意:flags是叠加的,比如按住ATL和Shift,flags就是8+16=24。
函数名无所谓,但参数必须是这样
def XXX(event,x,y,flags,param):
pass
cv.namedWindow('image')
cv.setMouseCallback('image', draw_circle)
直接将函数名作为cv.setMouseCallback()
的第二个参数,参数不需要你操心。
import cv2 as cv
import numpy as np
# 鼠标回调函数
def draw_circle(event,x,y,flags,param):
if event == cv.EVENT_LBUTTONDBLCLK: # 左键双击
cv.circle(img,(x,y),100,(255,0,0),-1)
# 创建一个黑色的图像,一个窗口,并绑定到窗口的功能
img = np.zeros((512,512,3), np.uint8)
cv.namedWindow('image')
cv.setMouseCallback('image',draw_circle)
while(1):
cv.imshow('image',img)
if cv.waitKey(20) == 27: # Esc
break
cv.destroyAllWindows()
import cv2 as cv
import numpy as np
# 鼠标回调函数
def show_flags(event,x,y,flags,param):
if event == cv.EVENT_LBUTTONDBLCLK: # 左键双击
print(flags)
# 创建一个黑色的图像,一个窗口,并绑定到窗口的功能
img = np.zeros((512,512,3), np.uint8)
cv.namedWindow('image')
cv.setMouseCallback('image',show_flags)
while(1):
cv.imshow('image',img)
if cv.waitKey() == 27: # Esc
break
cv.destroyAllWindows()
import numpy as np
import cv2 as cv
drawing = False # 如果按下鼠标,则为真
ix,iy = -1,-1
# 鼠标回调函数
def draw(event,x,y,flags,param):
global ix,iy,drawing
if event == cv.EVENT_LBUTTONDOWN: # 左键按下
drawing = True
ix,iy = x,y
elif event == cv.EVENT_MOUSEMOVE: # 鼠标移动
if drawing == True:
cv.rectangle(img,(ix,iy),(x,y),(0,255,0),-1)
elif event == cv.EVENT_LBUTTONUP: # 左键松开
drawing = False
cv.rectangle(img,(ix,iy),(x,y),(0,255,0),-1)
# 创建一个黑色的图像,一个窗口,并绑定到窗口的功能
img = np.zeros((512,512,3), np.uint8)
cv.namedWindow('image')
cv.setMouseCallback('image',draw)
while(1):
cv.imshow('image',img)
if cv.waitKey(20) == 27: # Esc
break
cv.destroyAllWindows()
https://blog.csdn.net/lly1122334/article/details/88975503