opencv学习笔记(六): 处理鼠标事件
文章目录
鼠标事件处理函数:cv2.setMouseCallback()
函数原型:cv2.setMouseCallback(const String & winname,
MouseCallback onMouse,
void * userdata = 0
)
参数说明:Parameters
winname Name of the window.
onMouse Callback function for mouse events. See OpenCV samples on how to specify and use the callback.
userdata The optional parameter passed to the callback.
winname 窗口名称
onMouse 鼠标事件的回调函数名
userdata 传递给回调的可选参数
注意:onMouse,鼠标事件的回调函数,具有一定的格式,详见下文
回调函数: onMouse()
cv2.setMouseCallback()中有一个参数为onMouse,注意看英文注释,onMouse是鼠标事件回调函数,需要阅读opencv的示例代码去定义并使用,这里参考opencv_python_tutorials中的说明:
函数原型:function_name(该名称可以自由命名)(int event, int x, int y, int flags, void *userdata)
参数说明:
event one of the cv::MouseEventTypes constants.
x The x-coordinate of the mouse event.
y The y-coordinate of the mouse event.
flags one of the cv::MouseEventFlags constants.
userdata The optional parameter.
event参数:MouseEventTypes(鼠标事件类型)常量,主要取值如下:
x,y参数:x为鼠标事件触发时的横坐标值,y为鼠标事件触发时的纵坐标值
flags,userdata两个参数尚未学习,改天再补。
示例:鼠标左键按下时画圆,中键按下时画矩形,右键按下时添加文字:
import cv2
import numpy as np
#创建回调函数
def drawcircle(event,x,y,flags,params):
if event == cv2.EVENT_LBUTTONDOWN:
cv2.circle(img,(x,y),10,(255,0,0),3)
elif event == cv2.EVENT_RBUTTONDOWN:
cv2.putText(img,'Restar_xt',(x,y),cv2.FONT_HERSHEY_SIMPLEX,1.5,(255,255,0),2)
elif event == cv2.EVENT_MBUTTONDOWN:
cv2.rectangle(img,(x,y),(x-50,y-60),(255,255,0),1)
#创建图像
img = np.zeros((512,512,3),np.uint8)
cv2.namedWindow('img',cv2.WINDOW_AUTOSIZE)
#使能鼠标事件处理函数
cv2.setMouseCallback('img',drawcircle)
while (1):
cv2.imshow('img',img)
if cv2.waitKey(1) == ord('q'):
break
运行结果如下: