yolov9中绘制检测框的代码是什么
时间: 2025-06-23 15:29:25 浏览: 7
### YOLOv9 中绘制检测框的代码实现
在 `utils/plots.py` 文件中实现了绘图的相关代码,在这个文件的 `box_label` 函数下实现了检测框绘制的相关内容。为了更好地理解如何在 YOLOv9 中绘制检测框,下面展示一段简化版的代码示例:
```python
import cv2
import numpy as np
def box_label(image, box, label='', color=(128, 128, 128), txt_color=(255, 255, 255)):
"""
在图像上绘制边界框并添加标签。
参数:
image (numpy.ndarray): 输入图像。
box (list or tuple): 边界框坐标[x_min, y_min, x_max, y_max]。
label (str): 显示的文字标签,默认为空字符串。
color (tuple): 边界框的颜色,默认为灰色(128, 128, 128)。
txt_color (tuple): 文字颜色,默认为白色(255, 255, 255)。
返回值:
None: 图像被原地修改。
"""
p1, p2 = (int(box[0]), int(box[1])), (int(box[2]), int(box[3]))
cv2.rectangle(image, p1, p2, color=color, thickness=2)
if label:
font_thickness = max(round(sum(image.shape) / 2 * 0.003), 2)
w, h = cv2.getTextSize(label, 0, fontScale=font_thickness / 3, thickness=font_thickness)[0]
outside = p1[1] - h >= 3
p2 = p1[0] + w, p1[1] - h - 3 if outside else p1[1] + h + 3
cv2.rectangle(image, p1, p2, color, -1, cv2.LINE_AA)
cv2.putText(
image,
label,
(p1[0], p1[1] - 2 if outside else p1[1] + h + 2),
0,
font_thickness / 3,
txt_color,
thickness=font_thickness,
lineType=cv2.LINE_AA,
)
```
此函数接受一张图片和一个表示矩形区域坐标的列表作为输入参数,并根据给定的颜色、字体大小和其他样式选项来绘制边框及其对应的类别名[^2]。
阅读全文
相关推荐


















