opencv(c++opencv):⿏标事件响应setMouseCallback 例⼦⼀:⿏标事件练习
做⼀个简单可切换画图模式的画板
rectangle函数opencv默认初始是 线段模式,
按下“L” 进⼊线段模式,
按下“T” 进⼊矩阵模式。
import numpy as np
mode =0
#创建回调函数
def OnMouseAction(event,x,y,flags,param):
global x1, y1
if mode ==0and event == cv2.EVENT_LBUTTONDOWN:
print("左键点击")
cv2.line(img,(0,0),(x,y),(255,255,0),2)
if mode ==1and event == cv2.EVENT_LBUTTONDOWN:
print("左键点击1")
x1, y1 = x, y
elif mode ==1and event==cv2.EVENT_MOUSEMOVE and flags ==cv2.EVENT_FLAG_LBUTTON: print("左鍵拖曳1")
'''
下⾯把回调函数与OpenCV窗⼝绑定在⼀起
'''
img = np.zeros((500,500,3),np.uint8)
cv2.namedWindow('image')
cv2.setMouseCallback('image',OnMouseAction)
while(1):
cv2.imshow('image',img)
k=cv2.waitKey(1)
if k==ord('l'):
mode =0
elif k==ord('t'):
mode =1
elif k==ord('q'):
break
cv2.destroyAllWindows()
基础知识补充
⼆、操作响应事件
setMouseCallback()函数:
cv2.setMouseCallback('image',OnMouseAction)
OnMouseAction()响应函数:
def OnMouseAction(event,x,y,flags,param):
Event:
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//中键双击
int x,int y,代表⿏标位于窗⼝的(x,y)坐标位置,即Point(x,y);
int flags,代表⿏标的拖拽事件,以及键盘⿏标联合事件,共有32种事件:
EVENT_FLAG_LBUTTON 1//左鍵拖曳
EVENT_FLAG_RBUTTON 2//右鍵拖曳
EVENT_FLAG_MBUTTON 4//中鍵拖曳
EVENT_FLAG_CTRLKEY 8//(8~15)按Ctrl不放事件
EVENT_FLAG_SHIFTKEY 16//(16~31)按Shift不放事件
EVENT_FLAG_ALTKEY 32//(32~39)按Alt不放事件
param 函数指针 标识了所响应的事件函数,相当于⾃定义了⼀个OnMouseAction()函数的ID。
例⼦⼆:测试⿏标事件的代码(基础)
Opencv中setMouseCallback()创建了⼀个⿏标回调函数,每次在图像上单击⿏标左键再抬起的过程,都会分3次调⽤⿏标响应函数,并且响应顺序是:
1.左键单击按下;
2.左键单击抬起;
3.⿏标指针位置移动(即使原地单击,⿏标位置并没有移动);
import cv2
import numpy as np
#创建回调函数
def OnMouseAction(event,x,y,flags,param):
if event == cv2.EVENT_LBUTTONDOWN:
print("左键点击")
elif event==cv2.EVENT_RBUTTONDOWN :
print("右键点击")
elif flags==cv2.EVENT_FLAG_LBUTTON:
print("左鍵拖曳")
elif event==cv2.EVENT_MBUTTONDOWN :
print("中键点击")
'''
创建回调函数的函数setMouseCallback();
下⾯把回调函数与OpenCV窗⼝绑定在⼀起
'''
img = np.zeros((500,500,3),np.uint8)
cv2.namedWindow('image')
cv2.setMouseCallback('image',OnMouseAction)
cv2.imshow('image',img)
cv2.waitKey(30000)
cv2.destroyAllWindows()