You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在YOLOv5中计算并显示Bounding Box的高度与宽度

在YOLOv5检测画面中显示Bounding Box的宽高信息

要在检测画面中展示目标框的宽高,只需修改代码中生成标注标签的逻辑,计算宽高后追加到原有标签文本中即可,具体步骤如下:

1. 计算Bounding Box的宽和高

在代码的Process predictions部分,遍历检测结果的循环中(for *xyxy, conf, cls in reversed(det):),通过xyxy的坐标值计算宽高:

  • xyxy格式为[x1, y1, x2, y2],其中x1,y1是框的左上角坐标,x2,y2是右下角坐标
  • 宽度 = x2 - x1
  • 高度 = y2 - y1

2. 修改标签生成逻辑

找到原有生成label的代码行,将宽高信息追加到标签中,修改后的代码片段如下:

# Write results
for *xyxy, conf, cls in reversed(det):
    if save_txt:  # Write to file
        xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist()  # normalized xywh
        line = (cls, *xywh, conf) if save_conf else (cls, *xywh)  # label format
        with open(f'{txt_path}.txt', 'a') as f:
            f.write(('%g ' * len(line)).rstrip() % line + '\n')

    if save_img or save_crop or view_img:  # Add bbox to image
        c = int(cls)  # integer class
        # 计算宽高
        x1, y1, x2, y2 = xyxy
        bbox_width = x2 - x1
        bbox_height = y2 - y1
        # 生成包含宽高的标签文本
        if hide_labels:
            label = None
        else:
            if hide_conf:
                label = f'{names[c]} | W:{bbox_width:.0f}, H:{bbox_height:.0f}'
            else:
                label = f'{names[c]} {conf:.2f} | W:{bbox_width:.0f}, H:{bbox_height:.0f}'
        annotator.box_label(xyxy, label, color=colors(c, True))
    if save_crop:
        save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True)

修改说明

  • 新增了bbox_width和bbox_height的计算,用.0f格式化取整,避免小数过多影响显示
  • 根据hide_labels和hide_conf的参数状态,生成对应格式的标签:
    • 如果隐藏标签,保持label=None
    • 如果隐藏置信度,标签仅显示类别+宽高
    • 默认显示类别+置信度+宽高

替换原有代码中的对应部分后,运行检测脚本,就能在画面中看到每个目标框的宽高信息和置信度一起显示了。

内容的提问来源于stack exchange,提问作者Arshan Abbas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 02:20:54