opencv-python(3):把鼠标当做画笔

haohaoxuexi
hahaha


本节学习的函数是:cv2.setMouseCallback()

鼠标事件可以是鼠标上的任何动作,比如左键按下,左键松开,左键双击等。我们可以通过鼠标事件获得与鼠标对应的图片上的坐标。

1、鼠标事件种类

代码:

import numpy as np
import cv2
events=[i for i in dir(cv2) if 'EVENT' in i]
print(events)

import numpy as np
import cv2
events=[i for i in dir(cv2) if 'EVENT' in i]
print(events)
输出结果如下
['EVENT_FLAG_ALTKEY', 
'EVENT_FLAG_CTRLKEY', 
'EVENT_FLAG_LBUTTON', 
'EVENT_FLAG_MBUTTON', 
'EVENT_FLAG_RBUTTON', 
'EVENT_FLAG_SHIFTKEY', 
'EVENT_LBUTTONDBLCLK', 
'EVENT_LBUTTONDOWN', 
'EVENT_LBUTTONUP', 
'EVENT_MBUTTONDBLCLK', 
'EVENT_MBUTTONDOWN', 
'EVENT_MBUTTONUP', 
'EVENT_MOUSEHWHEEL', 
'EVENT_MOUSEMOVE', 
'EVENT_MOUSEWHEEL', 
'EVENT_RBUTTONDBLCLK', 
'EVENT_RBUTTONDOWN', 
'EVENT_RBUTTONUP']

它们的含义是:

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         中间释放

补:

cv2_EVENT_FLAG_LBUTTON 左键拖拽  
cv2_EVENT_FLAG_RBUTTON 右键拖拽  
cv2_EVENT_FLAG_MBUTTON 中间拖拽  

2、在双击的地方绘制圆

代码如下:

haohaoxuexi


import numpy as np
import cv2
def draw_circle(event,x,y,flags,param):
    if event==cv2.EVENT_LBUTTONDBLCLK:
        cv2.circle(img,(x,y),60,(255,0,0),3)
#img=np.zeros((512,512,3),np.uint8)
img=cv2.imread('C:\\Users\\WLX\\Desktop\\2.jpg',cv2.IMREAD_COLOR)
cv2.namedWindow('image')
cv2.setMouseCallback('image',draw_circle)
while(1):
    cv2.imshow('image',img)
    if cv2.waitKey(20)&0xFF==27:
        break
cv2.imwrite('C:\\Users\\WLX\\Desktop\\fsf.jpg',img)
cv2.destroyAllWindows()


 
  

结果:

opencv-python(3):把鼠标当做画笔_第1张图片

3、高级一点的示例

根据选择模式选择画圈或者画矩形

import numpy as np
import cv2
drawing=False
mode=True
ix,iy=-1,-1
def draw_circle(event,x,y,flags,param):
    global ix,iy,drawing,mode#global 全局变量
    if event==cv2.EVENT_LBUTTONDOWN:
        drawing==True
        ix,iy=x,y
    elif event==cv2.EVENT_MOUSEMOVE and flags==cv2.EVENT_FLAG_LBUTTON:
        if drawing==True:
            if mode==True:
                cv2.rectangle(img,(ix,iy),(x,y),(0,255,0),3)
            else:
                cv2.circle(img,(x,y),3,(0,0,255),-1)
    elif event==cv2.EVENT_LBUTTONUP:
        drawing==False
        if mode==True:
            cv2.rectangle(img,(ix,iy),(x,y),(0,255,0),3)
        else:
            cv2.circle(img,(x,y),5,(0,0,255),-1)        
img=cv2.imread('C:\\Users\\WLX\\Desktop\\2.jpg',cv2.IMREAD_COLOR)
cv2.namedWindow('image')
cv2.setMouseCallback('image',draw_circle)
while(1):
    cv2.imshow('image',img)
    k=cv2.waitKey(20)&0xFF
    if k==ord('m'):
        mode=not mode
    elif k==27:
        break
cv2.imwrite('C:\\Users\\WLX\\Desktop\\fsf.jpg',img)
cv2.destroyAllWindows()

结果:

opencv-python(3):把鼠标当做画笔_第2张图片

fff

 
  
 
  
 
  
 
 

你可能感兴趣的:(python-opencv)