格式都是统一的,不同的是调用后的功能
def mouse_callback(event,x,y,flags,param):
定义完成后需要注册该回调函数
cv2.setMouseCallback(windowName,mouse_callback)
import cv2
events=[i for i in dir(cv2) 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']
所有的鼠标事件回调函数都有一个统一的格式,他们所不同的地方仅仅是被调用后的功能。我们的鼠标事件回调函数只用做一件事:在双击过的地方绘制一个圆圈。
import cv2
import numpy as np
#mouse callback function
def draw_circle(event,x,y,flags,param):
if event==cv2.EVENT_LBUTTONDBLCLK:
cv2.circle(img,(x,y),50,(255,0,255),-1)
print('圆心坐标x=:{0},y=:{1}'.format(x,y))
# 创建图像与窗口并将窗口与回调函数绑定
img=np.zeros((512,512,3),np.uint8)
cv2.namedWindow('image')
cv2.setMouseCallback('image',draw_circle)
while(1):
cv2.imshow('image',img)
if cv2.waitKey(20)&0xFF==27:
break
cv2.destroyAllWindows()
import cv2
import numpy as np
drawing = False # 鼠标未按下时不绘制
mode = True # true时绘制矩形,按'm'变成绘制曲线
ix, iy = -1, -1
# 定义鼠标回调函数
def MouseCallback(event, x, y, flags, param):
global ix, iy, drawing, mode
# 按下左键确定鼠标起始位置
if event == cv2.EVENT_LBUTTONDOWN:
drawing = True
ix, iy = x, y
# 左键按下状态并且移动开始绘制
elif event == cv2.EVENT_MOUSEMOVE and flags == cv2.EVENT_FLAG_LBUTTON:
if drawing is True:
if mode is False:
cv2.rectangle(img, (ix, iy), (x, y), (0, 255, 0), -1)
else:
# 默认开启绘制鼠标轨迹,按m取消
cv2.circle(img, (x, y), 1, (255, 0, 0), -1)
elif event == cv2.EVENT_LBUTTONUP:
if drawing is True:
if mode is True:
cv2.rectangle(img, (ix, iy), (x, y), (0, 255, 0), 1)
drawing = False # 当鼠标松开停止绘画。
img=np.zeros((512,512,3),np.uint8)
cv2.namedWindow('rectangle')
cv2.setMouseCallback('rectangle', MouseCallback)
while(True):
cv2.imshow('rectangle', img)
k = cv2.waitKey(10) & 0xFF
if k == ord('m'):
mode = not mode
elif k == 27:
break