1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
# 触发鼠标移动事件
# cv2.CV_EVENT_MOUSEMOVE
# 触发左键抬起事件
# cv2.CV_EVENT_LBUTTONUP
# 触发右键按下事件
# cv2.CV_EVENT_RBUTTONDOWN
# 触发右键抬起事件
# cv2.CV_EVENT_RBUTTONUP
# 触发左键双击事件
# cv2.CV_EVENT_LBUTTONDBLCLK
# 触发右键双击事件
# cv2.CV_EVENT_RBUTTONDBLCLK
coordinates = []
window_name = 'draw'
def on_mouse_callback(event, x, y, flag, param):
# 左键点击,画点
if event == cv2.EVENT_LBUTTONDOWN:
xy = f'{x},{y}'
coordinates.append((x, y))
cv2.circle(img, (x, y), 1, (0, 0, 255), thickness=-1)
cv2.putText(img,
xy, (x, y),
cv2.FONT_HERSHEY_PLAIN,
1.0, (0, 0, 0),
thickness=1)
cv2.imshow(window_name, img)
# 右键单击,画不规则图形
elif event == cv2.EVENT_RBUTTONDOWN:
pts = np.array(coordinates, np.int32) # 顶点集
#顶点坐标转为rowsx1x2, row为顶点数
pts = pts.reshape((-1, 1, 2))
cv2.polylines(img, [pts], True, (255, 255, 255), 2)
cv2.imshow(window_name, img)
# 右键双击,填充颜色
elif event == cv2.EVENT_RBUTTONDBLCLK:
area = np.array(coordinates)
# 可以绘制多个图形
cv2.fillPoly(img, [area], (255, 255, 255))
# 绘制凸多边形
# cv2.fillConvexPoly(img, area, (255, 255, 255))
cv2.imshow(window_name, img)
coordinates.clear()
cv2.namedWindow(window_name)
cv2.setMouseCallback(window_name, on_mouse_callback)
cv2.imshow(window_name, img)
cv2.waitKey(0)
cv2.destroyAllWindows()
|