#coding=utf-8
import cv2
import numpy as np
# 全局变量
drawing = False # 是否开始绘制
mode = 'none' # 当前绘制模式
start_x, start_y = -1, -1 # 绘制起点坐标
# 鼠标回调函数
def draw_shape(event, x, y, flags, param):
global drawing, start_x, start_y, mode
if (event & cv2.EVENT_LBUTTONDOWN == cv2.EVENT_LBUTTONDOWN):
drawing = True
start_x, start_y = x, y
elif (event & cv2.EVENT_LBUTTONUP == cv2.EVENT_LBUTTONUP):
drawing = False
if mode == 'rectangle':
cv2.rectangle(img, (start_x, start_y), (x, y), (0, 255, 0), 2)
print("矩形坐标:", (start_x, start_y), (x, y))
elif mode == 'circle':
radius = int(((x - start_x)**2 + (y - start_y)**2)**0.5)
cv2.circle(img, (start_x, start_y), radius, (0, 0, 255), 2)
print("圆形坐标:", (start_x, start_y), "半径:", radius)
elif mode == 'line':
cv2.line(img, (start_x, start_y), (x, y), (255, 0, 0), 2)
print("直线坐标:", (start_x, start_y), (x, y))
# 创建空白图像
img = np.zeros((512, 512, 3), np.uint8)
# 创建窗口并绑定鼠标回调函数
cv2.namedWindow('Drawing', cv2.WINDOW_NORMAL)
cv2.setMouseCallback('Drawing', draw_shape)
# 显示绘制界面,按下键盘按键来绘制图形
while True:
cv2.imshow('Drawing', img)
key = cv2.waitKey(1) & 0xFF
if key == ord('r'):
mode = 'rectangle'
elif key == ord('c'):
mode = 'circle'
elif key == ord('l'):
mode = 'line'
elif key == 27 or key == ord('q'): # 按下 ESC 键退出
break
cv2.destroyAllWindows()
OpenCV之鼠标操作绘制图形
最新推荐文章于 2025-03-17 16:55:40 发布