04. opencv监听鼠标行为

import cv2
import numpy as np
# 创建背景图
img = np.zeros((480, 640, 3), np.uint8)
startpos = (0, 0)
curshape = 0
# 要监听鼠标的行为,必须通过鼠标回调函数实现
def mouse_callback(event, x, y, flags, userdata):
    # 引入全局变量
    global startpos, curshape
    # 引入非本层的局部变量使用关键字nonlocal
    if event == cv2.EVENT_LBUTTONDOWN:
        # 记录起始位置
        startpos = (x, y)
    elif event == cv2.EVENT_LBUTTONUP:
        # 判断要绘制什么类型的图形
        if curshape == 0: # 画直线
            cv2.line(img, startpos, (x, y), (0,0,255), 3)
        elif curshape == 1: # 画矩形
            cv2.rectangle(img, startpos, (x, y), (0,0,255), 3)
        elif curshape == 2: # 画圆
            # 注意计算半径
            cv2.rectangle(img, startpos, (x, y), (0,0,255), 3)

cv2.namedWindow('drawshape', cv2.WINDOW_NORMAL)
cv2.resizeWindow('drawshape', 800, 600)
cv2.setMouseCallback('drawshape', mouse_callback) # 这个还可以传递一个用户的数据,非必传
while True:
    cv2.imshow('drawshape', img)
    # 检测按键
    key = cv2.waitKey(1)
    if key == ord('q'):
        break
    elif key == ord('l'):
        curshape = 0
    elif key == ord('r'):
        curshape = 1
    elif key == ord('c'):
        curshape = 2
cv2.destroyAllWindows()
posted @ 2022-06-23 22:17  理舞  阅读(49)  评论(0编辑  收藏  举报