解决方法:
pip install opencv-python
pip install numpy
import cv2
import numpy as np
# 创建一个空白窗口
image = np.zeros((512, 512, 3), np.uint8)
cv2.namedWindow('Image')
# 定义鼠标事件的回调函数
def draw_rectangle(event, x, y, flags, param):
global drawing, top_left_pt, bottom_right_pt
if event == cv2.EVENT_LBUTTONDOWN:
drawing = True
top_left_pt = (x, y)
elif event == cv2.EVENT_LBUTTONUP:
drawing = False
bottom_right_pt = (x, y)
# 绘制矩形框
cv2.rectangle(image, top_left_pt, bottom_right_pt, (0, 255, 0), 2)
cv2.imshow('Image', image)
# 注册鼠标事件回调函数
cv2.setMouseCallback('Image', draw_rectangle)
while True:
cv2.imshow('Image', image)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cv2.destroyAllWindows()
# 保存BBox标注结果
bbox = (top_left_pt[0], top_left_pt[1], bottom_right_pt[0], bottom_right_pt[1])
with open('bbox.txt', 'w') as f:
f.write(','.join(str(coord) for coord in bbox))
这样,你就可以根据需要使用上述代码示例来创建一个BBox标注工具了。你可以根据自己的需求对代码进行修改和扩展,以实现更复杂的功能,如在图像上绘制多个矩形框、支持键盘操作等。
上一篇:bbmle中的NaN错误