本文共 1414 字,大约阅读时间需要 4 分钟。
以下代码示例展示了如何使用OpenCV库来在图像上绘制边框以及添加标签注释。
def plot_one_box(x, img, color=(0, 255, 0), label=None, line_thickness=3): """绘制图像上的边框和标签注释""" tl = line_thickness or int(round(0.002 * max(img.shape[0:2]))) # 计算线条厚度 c1, c2 = (int(x[0]), int(x[1])), (int(x[2]), int(x[3])) # 获取边框坐标 cv2.rectangle(img, c1, c2, color, thickness=tl, lineType=cv2.LINE_AA) # 绘制边框 if label: tf = max(tl - 1, 1) # 计算字体厚度 t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0] # 计算字体大小 c2 = (c1[0] + t_size[0], c1[1] - t_size[1] - 3) # 调整坐标以容纳标签 cv2.rectangle(img, c1, c2, color, -1, cv2.LINE_AA) # 绘制填充的边框 cv2.putText(label, c1[0] + t_size[0], c1[1] - t_size[1] - 2, fontFace=cv2.FONT_HERSHEY_SIMPLEX, fontScale=tl / 3, color=color, thickness=tf) # 添加标签
以下是一个使用该函数的示例代码片段:
import cv2# 加载示例图像img = cv2.imread("example_image.jpg")# 使用函数绘制边框和标签plot_one_box((100, 200, 300, 400), img, label="目标物体")# 显示图像cv2.imshow("结果图像", img)cv2.waitKey(0)cv2.destroyAllWindows()
转载地址:http://pjfbz.baihongyu.com/