Mouse as a Paint-Brush

1回调函数

cv2.setMouseCallback(windowName, onMouse [, param])

  • windowName:显示窗口名称
  • onMouse:鼠标响应处理函数

鼠标回调函数,该函数在鼠标事件发生时执行。 鼠标事件可以是与鼠标相关的任何内容,如左键向下,左键向上,左键双击等。它为我们提供了每个鼠标事件的坐标(x,y)。 通过这个活动和地点,我们可以做任何我们喜欢的事情。

下面代码输出了鼠标事件的种类
代码

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 滑动
EVENT_LBUTTONDOWN 1 左键点击
EVENT_RBUTTONDOWN 2 右键点击
EVENT_MBUTTONDOWN 3 中间点击
EVENT_LBUTTONUP 4 左键释放
EVENT_RBUTTONUP 5 右键释放
EVENT_MBUTTONUP 6 中间释放
EVENT_LBUTTONDBLCLK 7 左键双击
EVENT_RBUTTONDBLCLK 8 右键双击
EVENT_MBUTTONDBLCLK 9 中间双击

应用一

创建了一个简单的应用程序,只要我们双击它就可以在图像上绘制一个圆圈.
代码

import numpy as np
import cv2

# mouse callback function
def draw_circle(event,x,y,flags,param):
    if event == cv2.EVENT_LBUTTONDBLCLK:
        cv2.circle(img,(x,y),100,(255,0,0),-1)

# Create a black image, a window and bind the function to window
img = np.zeros((512,512,3), np.uint8)
cv2.namedWindow('image')
cv2.setMouseCallback('image',draw_circle)

while(1):
    cv2.imshow('image',img)
    if cv2.waitKey(20) & 0xFF == 27:
        break
cv2.destroyAllWindows()

clipboard.png

双击鼠标左键:

clipboard.png

应用二

通过拖动鼠标绘制矩形或圆形(取决于我们选择的模式),就像在Paint应用程序中一样。 所以我们的鼠标回调函数有两个部分,一个用于绘制矩形,另一个用于绘制圆形.在主循环中,设置键'm'设置键盘绑定以在矩形和圆之间切换.

代码

import numpy as np
import cv2

drawing = False # true if mouse is pressed
mode = True # if True, draw rectangle. Press 'm' to toggle to curve
ix,iy = -1,-1

# mouse callback function
def draw_circle(event,x,y,flags,param):
    global ix,iy,drawing,mode

    if event == cv2.EVENT_LBUTTONDOWN:
        drawing = True
        ix,iy = x,y

    elif event == cv2.EVENT_MOUSEMOVE:
        if drawing == True:
            if mode == True:
                cv2.rectangle(img,(ix,iy),(x,y),(0,255,0),-1)
            else:
                cv2.circle(img,(x,y),5,(0,0,255),-1)

    elif event == cv2.EVENT_LBUTTONUP:
        drawing = False
        if mode == True:
            cv2.rectangle(img,(ix,iy),(x,y),(0,255,0),-1)
        else:
            cv2.circle(img,(x,y),5,(0,0,255),-1)

img = np.zeros((512,512,3), np.uint8)
cv2.namedWindow('image')
cv2.setMouseCallback('image',draw_circle)

while(1):
    cv2.imshow('image',img)
    k = cv2.waitKey(1) & 0xFF
    if k == ord('m'):
        mode = not mode
    elif k == 27:
        break

cv2.destroyAllWindows()

clipboard.png
按住鼠标左键滑动
clipboard.png
按“m”键,再次按住鼠标左键滑动
clipboard.png


sakurala
84 声望37 粉丝

目前正在学习以及巩固opencv-python知识.