7.OpenCV的响应鼠标事件
前言
OpenCV可在用户触发鼠标事件时,调用鼠标回调函数完成事件处理。
一、响应鼠标事件
鼠标回调函数的基本格式如下:
def mouseCallback(event, x, y, flag, param):...
mouseCallback为自定义函数名称
event为调用时传递给函数的鼠标事件对象
x和y为出发鼠标事件时,鼠标指针在窗口中的坐标(x,y)
flag为触发鼠标事件时,鼠标拖动或按键盘的操作
1、右键画矩形、左键画圆
img = np.zeros((200,500,3), dtype='uint8') + 255
def draw(event, x, y, flag, param): # 定义鼠标回调函数
if event == cv2.EVENT_LBUTTONDBLCLK: #双击鼠标左键时画圆
cv2.circle(img,(x,y),20,(255,0,0),-1)
elif event == cv2.EVENT_RBUTTONDBLCLK:
cv2.rectangle(img,(x,y),(x+60,y+30),(0,0,255),-1) #双击鼠标右键时画矩形
cv2.imshow("drawing",img)
cv2.namedWindow("drawing")
cv2.setMouseCallback("drawing",draw) # 为窗口绑定回调函数
while(True):
cv2.imshow("drawing",img)
k = cv2.waitKey(1)
if k == 27:
break
cv2.destroyAllWindows()
2、使用鼠标指针选点绘制多边形
img = np.zeros((576,1024,3), dtype='uint8')+ 255
font = cv2.FONT_HERSHEY_PLAIN
xys = []
def draw(event,x,y,flag,param):
global xys, img
if event == cv2.EVENT_LBUTTONUP:
xy = '(%s,%s)'%(x,y)
cv2.putText(img,xy,(x,y),font,2,(0,0,0),1,cv2.LINE_AA)
xys.append([x,y])
cv2.circle(img,(x,y),5,(0,0,255),-1)
elif event == cv2.EVENT_RBUTTONUP:
pts = np.array(xys,np.int32)
cv2.polylines(img,[pts],True,(0,0,0),2)
xys = []
elif event == cv2.EVENT_RBUTTONDBLCLK:
img = np.zeros((576,1024,3), dtype='uint8')+ 255 #双击鼠标左键时重置图像
cv2.imshow("drawing",img)
cv2.namedWindow("drawing")
cv2.setMouseCallback("drawing",draw) # 为窗口绑定回调函数
cv2.imshow("drawing",img)
k = cv2.waitKey(0)
if k == 27:
cv2.destroyAllWindows()
3、按住鼠标左键移动绘图,双击左键清除绘图
img=np.zeros((1200,1320,3), np.uint8) + 255 #创建一幅白色图像
drawing = False
def draw(event,x,y,flag,param): #定义鼠标回调函数
global img,drawing
if event == cv2.EVENT_LBUTTONDOWN:
drawing = True
elif event == cv2.EVENT_MOUSEMOVE:
if drawing == True:
cv2.circle(img,(x,y),5,(0,0,255),-1)
elif event == cv2.EVENT_LBUTTONUP:
drawing = False
elif event==cv2.EVENT_RBUTTONDBLCLK:
img=np.zeros((1200,1320,3), np.uint8)+255 #双击鼠标左键时重置图像
cv2.imshow('drawing',img) #显示图像
cv2.namedWindow('drawing') #命名图像窗口
cv2.setMouseCallback('drawing',draw) #为窗口绑定回调函数
cv2.imshow('drawing',img) #显示图像
cv2.waitKey(0)
cv2.destroyAllWindows()
二、OpenCV-Python资源下载
OpenCV-Python测试用图片、中文官方文档、opencv-4.5.4源码
总结
以上内容介绍了OpenCV-Python响应鼠标的三个例子,有关Python、数据科学、人工智能等文章后续会不定期发布,请大家多多关注,一键三连哟(●’◡’●)。