1 import numpy as np
2 import matplotlib.pyplot as plt
3 from numpy.core.defchararray import count
4 import cv2 as cv
5
6
7 drawing = False #按下鼠标为真
8 ix, iy = -1, -1
9
10 def draw_rectangle(event, x, y, flags, param):
11 global ix, iy, drawing, img
12 if event == cv.EVENT_LBUTTONDOWN:
13 print("you has choosen the start point of the rectangle")
14 drawing = True
15 ix, iy = x, y
16 elif event == cv.EVENT_MOUSEMOVE:
17 if drawing == True:
18 px, py = x, y
19 img = mask.copy() #每次绘制使用一个原始的图像的copy, 这样绘制矩形框时,就没有问题 这里是关键
20 cv.rectangle(img, (ix, iy), (px,py),(255, 0, 255), -1)
21 elif event == cv.EVENT_LBUTTONUP:
22 drawing = False
23 px, py = x, y
24 cv.rectangle(img, (ix, iy), (px, py),(255, 0, 255), -1)
25
26 img_source = cv.imread("duo.jpg")
27 img = np.zeros(img_source.shape)
28 mask = img.copy() #拷贝一个原图,用以更新背景
29 cv.namedWindow('image', cv.WINDOW_AUTOSIZE)
30 cv.setMouseCallback("image", draw_rectangle)
31 while True:
32 if cv.waitKey(1) == 27: #esc退出窗口
33 break
34 cv.imshow("image", img)
35
36 cv.destroyAllWindows()
37