OPENCV FOR PYTHON 学习笔记 - 鼠标回调事件
import numpy as np import cv2 as cv #鼠标双击画圆 def draw_cycle(event,x,y,flags,param): if event == cv.EVENT_LBUTTONDBLCLK: cv.circle(img,(x,y),100,(255,0,0),-1) #当鼠标按下时变为True drawing = False #mode 为 True 绘制矩形,按下m 变为绘制曲线 mode = True ix,iy = -1,-1 ''' 鼠标事件回调函数 参数1 event 代表了鼠标的各种操作,详细看一下各个event事件: #define CV_EVENT_MOUSEMOVE 0 //滑动 #define CV_EVENT_LBUTTONDOWN 1 //左键点击 #define CV_EVENT_RBUTTONDOWN 2 //右键点击 #define CV_EVENT_MBUTTONDOWN 3 //中键点击 #define CV_EVENT_LBUTTONUP 4 //左键放开 #define CV_EVENT_RBUTTONUP 5 //右键放开 #define CV_EVENT_MBUTTONUP 6 //中键放开 #define CV_EVENT_LBUTTONDBLCLK 7 //左键双击 #define CV_EVENT_RBUTTONDBLCLK 8 //右键双击 #define CV_EVENT_MBUTTONDBLCLK 9 //中键双击 参数2,3 int x,int y,代表鼠标位于窗口的(x,y)坐标位置,即Point(x,y); 参数4 int flags,代表鼠标的拖拽事件,以及键盘鼠标联合事件,共有32种事件: flags: #define CV_EVENT_FLAG_LBUTTON 1 //左鍵拖曳 #define CV_EVENT_FLAG_RBUTTON 2 //右鍵拖曳 #define CV_EVENT_FLAG_MBUTTON 4 //中鍵拖曳 #define CV_EVENT_FLAG_CTRLKEY 8 //(8~15)按Ctrl不放事件 #define CV_EVENT_FLAG_SHIFTKEY 16 //(16~31)按Shift不放事件 #define CV_EVENT_FLAG_ALTKEY 32 //(32~39)按Alt不放事件 ''' def draw_shape(event,x,y,flags,param): global ix,iy,drawing,mode #按下鼠标左键时,返回起始位置坐标 if event == cv.EVENT_LBUTTONDOWN: drawing = True ix,iy = x,y #当鼠标左键按下,并且移动时绘制图形 elif event == cv.EVENT_MOUSEMOVE and flags == cv.EVENT_FLAG_LBUTTON: if drawing == True: if mode == True: cv.rectangle(img,(ix,iy),(x,y),(0,255,0),-1) else: cv.circle(img,(x,y),3,(0,0,255),-1) elif event == cv.EVENT_LBUTTONUP: drawing == False #创建图像和窗口,并将窗口与回调函数绑定 img = np.zeros((512,512,3),np.uint8) cv.namedWindow('img') cv.setMouseCallback('img',draw_shape) while(1): cv.imshow('img',img) if(cv.waitKey(20)&0xFF == ord('q')): break elif (cv.waitKey(20)&0xFF == ord('m')): mode = not mode cv.destroyAllWindows()
本文来自博客园,作者:HappyChen2016,转载请注明原文链接:https://www.cnblogs.com/happychen2016/p/15156682.html