python OpenCV学习笔记(四):鼠标画图

官方文档 – https://docs.opencv.org/3.4.0/db/d5b/tutorial_py_mouse_handling.html


需要使用到的函数:
setMouseCallback(windowName, onMouse [, param])

一个简单的Demo

鼠标双击,画一个圆

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,(255,0,0),-1)

# 创建一个黑色图片,绑定回调函数
img = np.zeros((512,512,3), np.uint8)
cv.namedWindow('image')
cv.setMouseCallback('image',draw_circle)

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

更多Demo

设计一个可以同时切换模式,画出矩形和圆的应用

import numpy as np
import cv2 as cv

drawing = False # 鼠标点击的时候变为True
mode = True # 如果为True, 绘制矩形。点击'm'切换到曲线
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 is True:
            if mode is 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 is 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('image')
cv.setMouseCallback('image',draw_circle)

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

注意:上段代码画图时,只能扩充,不能随意缩放所画的图形

你可能感兴趣的:(OpenCV)