利用鼠标画矩形或者线段
import cv2 as cv
import numpy as np
drawing = False # 如果 mode为true绘制矩形。按下 'm’变成绘制曲线。 默认是false 鼠标按下是true
mode = True
ix, iy = -1,-1
def draw_circle(event,x, y, flags, param):
global ix, iy, drawing, mode
if event == cv.EVENT_MBUTTONDOWN: # cv.EVENT_MBUTTONDOWN = , 中键按下
drawing = True
ix, iy = x, y
elif event == cv.EVENT_MOUSEMOVE: # cv.EVENT_MOUSEMOVE , 鼠标移动
if drawing == True:
if mode == True:
cv.rectangle(img, (ix, iy), (x, y), (0, 255 ,0), -1)
else:
cv.circle(img,(x, y),10,(0, 0, 255), -1)
elif event == cv.EVENT_LBUTTONUP: # cv.EVENT_LBUTTONUP , 左键释放
drawing = False
if mode == True:
cv.rectangle(img,(ix, iy), (x, y),(0, 255, 0), -1)
else:
cv.circle(img,(x, y), 10,(0, 0, 255), -1)
img = np.zeros((512, 512, 3), np.uint8) #黑色图片
cv.namedWindow(‘image’)
cv.setMouseCallback(‘image’,draw_circle)
while(1):
cv.imshow(‘image’, img)
k = cv.waitKey(1)&0xFF
if k == ord(‘m’):
mode = not mode
elif k == 27:
break
输出结果: