table of Contents
Create a mouse callback function
Example-draw a circle at the double-click position
Create a mouse callback function
This function is executed when a mouse event occurs. There is a specific format for creating a mouse callback function, which is the same everywhere. It differs only in function.
View all mouse events
import cv2 as cv
events = [i for i in dir(cv) if 'EVENT' in i]
print(events)
All events are as follows
CV_EVENT_MOUSEMOVE =0, //鼠标移动
CV_EVENT_LBUTTONDOWN =1, //按下左键
CV_EVENT_RBUTTONDOWN =2, //按下右键
CV_EVENT_MBUTTONDOWN =3, //按下中键
CV_EVENT_LBUTTONUP =4, //放开左键
CV_EVENT_RBUTTONUP =5, //放开右键
CV_EVENT_MBUTTONUP =6, //放开中键
CV_EVENT_LBUTTONDBLCLK =7, //左键双击
CV_EVENT_RBUTTONDBLCLK =8, //右键双击
CV_EVENT_MBUTTONDBLCLK =9, //中键双击
CV_EVENT_MOUSEWHEEL =10, //滚轮滚动
CV_EVENT_MOUSEHWHEEL =11 //横向滚轮滚动(还好我鼠标是G502可以这么干)
CV_EVENT_FLAG_LBUTTON =1, //左键拖拽
CV_EVENT_FLAG_RBUTTON =2, //右键拖拽
CV_EVENT_FLAG_MBUTTON =4, //中键拖拽
CV_EVENT_FLAG_CTRLKEY =8, //按住CTRL拖拽
CV_EVENT_FLAG_SHIFTKEY =16, //按住Shift拖拽
CV_EVENT_FLAG_ALTKEY =32 //按住ALT拖拽
Learn the use of cv.setMouseCallback( windowName, onMouse, param=None )
This function always runs in the program, anytime when your mouse moves, this function is called
Example-draw a circle at the double-click position
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)
if __name__ == '__main__':
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) & 0xFF==27: ##27是Esc的ASCII码
break
cv.destroyAllWindows()