opencv处理鼠标事件。cv.setMouseCallback()
查询所有可用的事件
import cv2 as cv events=[i for i in dir(cv) if 'EVENT' in i] print(events)
双击鼠标绘制一个圆
import numpy as np import cv2 as cv def draw_circle(event,x,y,flags,param): if event==cv.EVENT_LBUTTONDBLCLK: cv.circle(img,(x,y),100,(0,0,255),-1,cv.LINE_AA) img=np.zeros((512,512,3),np.uint8) cv.namedWindow('image',cv.WINDOW_NORMAL) # 给窗口绑定鼠标事件 cv.setMouseCallback('image',draw_circle) while(1): cv.imshow('image',img) # 按ESC退出 if cv.waitKey(1)&0XFF==27: break cv.destroyAllWindows()
拖动鼠标绘制矩形或圆形
import cv2 as cv import numpy as np drawing=False mode=True # 如果为真则绘制矩形 ix,iy=-1,-1 def draw_circle(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: if drawing==True: if mode==True: cv.rectangle(img,(ix,iy),(x,y),(0,255,0),-1) else: cv.circle(img,(x,y),5,(0,0,255),-1) elif event==cv.EVENT_LBUTTONUP: drawing=False if mode==True: cv.rectangle(img,(ix,iy),(x,y),(0,255,0),-1) else: cv.circle(img,(x,y),5,(0,0,255),-1) img=np.zeros((512,512,3),np.uint8) cv.namedWindow('img') cv.setMouseCallback('img',draw_circle) while True: cv.imshow('img',img) if cv.waitKey(1)&0XFF==27: break cv.destroyAllWindows()
posted on
浙公网安备 33010602011771号