Python OpenCV 把鼠标当画笔

简单演示

查看支持的鼠标事件

print [i for i in dir(cv2) if 'EVENT' in i]

所有鼠标事件回调函数都有一个统一的格式,它们不同的地方仅仅是被调用后的功能。

再双击过的地方画一个圆:

# -*- coding: utf-8 -*-

import cv2
import numpy as np


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


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

while True:
    cv2.imshow('image', img)
    if cv2.waitKey(20) & 0xff == 27:
        break

cv2.destroyAllWindows()

根据选择模式绘制

# -*- coding: utf-8 -*-

import cv2
import numpy as np


#当鼠标按下时变为 True
drawing = False
#如果mode为True绘制矩形, 按下m变成绘制曲线
mode = True
ix, iy = -1, -1

#创建回调函数
def draw(event, x, y, flags, param):
    global ix, iy, drawing, mode
    #当按下左键时返回起始点坐标
    if event == cv2.EVENT_LBUTTONDOWN:
        drawing = True
        ix, iy = x, y
    #当鼠标按下并移动时绘制图形,可以查看移动,flag是否按下
    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), -1)
            else:
                cv2.circle(img, (x, y), 3, (0, 0, 255), -1)

    #当鼠标松开时停止绘画
    elif event == cv2.EVENT_LBUTTONUP:
        drawing = False


img = np.zeros((512, 512, 3), np.uint8)
cv2.namedWindow('image')
cv2.setMouseCallback('image', draw)
while True:
    cv2.imshow('image', img)
    k = cv2.waitKey(1) & 0xff
    if k == ord('m'):
        mode = not mode
    elif k == 27:
        break

猜你喜欢

转载自www.cnblogs.com/wbyixx/p/9393805.html