Opencv3学习笔记(C++&Python双语)---鼠标事件

python代码

简单的示例

def draw_cicle(event,x,y,flags,params):
    if event==cv.EVENT_LBUTTONDBLCLK:
        cv.circle(img,(x,y),100,(255,0,0),-1)
        
img = np.zeros((500,500,3),np.uint8)
cv.namedWindow("image")
cv.setMouseCallback("image",draw_cicle)

while(1):
    cv.imshow("image",img)
    if cv.waitKey(25)&0xFF==ord('q'):
        break
cv.destroyAllWindows()

复杂示例

#高级一点的程序
drawing = False
mode = True
ix,iy = -1,-1

def draw_cicle(event,x,y,flags,params):
    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((500,500,3),np.uint8)
cv.namedWindow("image")
cv.setMouseCallback("image",draw_cicle)
while(1):
    cv.imshow("image",img)
    k=cv.waitKey(1)
    if k==ord('m'):
        mode = not mode
    if k == ord('q'):
        break
cv.destroyAllWindows()

创建滚动条

def nothing(x):
    pass
img = np.zeros((300,512,3),np.uint8)
cv.namedWindow('image')

cv.createTrackbar('R','image',0,255,nothing)
cv.createTrackbar('G','image',0,255,nothing)
cv.createTrackbar('B','image',0,255,nothing)

switch = '0:OFF\n1:ON'
cv.createTrackbar(switch,"image",0,1,nothing)

while(1):
    cv.imshow("image",img)
    k=cv.waitKey(1)
    if k==ord('q'):
        break
    r = cv.getTrackbarPos('R','image')
    g = cv.getTrackbarPos('G','image')
    b = cv.getTrackbarPos('B','image')
    s = cv.getTrackbarPos(switch,'image')
    
    if s ==0:
        img[:]=0
    else:
        img[:]=[b,g,r]
cv.destroyAllWindows()

 

你可能感兴趣的:(opencv,图像识别,计算机视觉)