用python实现在地址为"C:\\Users\\11508\\Desktop\\2024-03\\X.bmp"的图像上用鼠标画一个正方形
时间: 2024-04-15 13:23:45 浏览: 86
要在Python中实现在图像上用鼠标画一个正方形,可以使用OpenCV库。下面是一个简单的示例代码:
```python
import cv2
# 定义全局变量
drawing = False # 是否正在绘制
start_x, start_y = -1, -1 # 正方形的起始坐标
# 鼠标回调函数
def draw_square(event, x, y, flags, param):
global drawing, start_x, start_y
if event == cv2.EVENT_LBUTTONDOWN:
drawing = True
start_x, start_y = x, y
elif event == cv2.EVENT_LBUTTONUP:
drawing = False
side_length = min(abs(x - start_x), abs(y - start_y))
end_x = start_x + side_length
end_y = start_y + side_length
cv2.rectangle(img, (start_x, start_y), (end_x, end_y), (0, 255, 0), 2)
cv2.imshow("Image", img)
# 读取图像
img_path = "C:\\Users\\11508\\Desktop\\2024-03\\X.bmp"
img = cv2.imread(img_path)
# 创建窗口并绑定鼠标回调函数
cv2.namedWindow("Image")
cv2.setMouseCallback("Image", draw_square)
while True:
cv2.imshow("Image", img)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cv2.destroyAllWindows()
```
运行以上代码后,会打开一个窗口显示指定路径的图像。你可以在图像上按住鼠标左键拖动,绘制一个方形,松开鼠标左键后正方形将被制在图像上。按下键盘上的"q"键退出程序。
阅读全文