CV2 在窗口上 按下鼠标左键 滑动鼠标 画圆或矩形

以下时代码:

import numpy as np
import cv2

path = r"lena_color.jpg"
image = cv2.imread(path)
print(image.shape)

drawing = False
mode = True  # True, 画矩形, m切换
ix = -1
iy = -1


def draw_circle(event, x, y, flags, param): # 按下鼠标 并拖动画图形, 包括按下, move, up
    global ix, iy, drawing, mode

    if event == cv2.EVENT_LBUTTONDOWN: # 按下左键 开始画
        drawing = True
        ix, iy = x, y  # 矩形起点 就是 鼠标的点
    elif event == cv2.EVENT_MOUSEMOVE:  # 鼠标移动
        if drawing:
            if mode:
                cv2.rectangle(image, (ix, iy), (x, y), (0, 255, 0), -1)
            else:
                cv2.circle(image, (x, y), 5, (0, 0, 255), -1)
    elif event == cv2.EVENT_LBUTTONUP:  # 结束画画
        drawing = False
        if mode:
            cv2.rectangle(image, (ix, iy), (x, y), (0, 255, 0), -1)
        else:
            cv2.circle(image, (x, y), 5, (0, 0, 255), -1)


cv2.namedWindow("image")
cv2.setMouseCallback("image", draw_circle)

while(1):
    cv2.imshow("image", image)
    k = cv2.waitKey(1) & 0xFF  
    if k == ord('m'):
        mode = not mode
    elif k == 27:  # ESC键 退出窗口
        break

cv2.destroyAllWindows()

 

你可能感兴趣的:(Python)