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

多边形区域目标检测代码报错:AttributeError问题排查与修复

问题:Supervision库Detections.from_yolov8属性错误及修复方案

错误原因

你遇到的AttributeError: type object 'Detections' has no attribute 'from_yolov8'是因为Supervision库版本更新后,专门针对YOLOv8的from_yolov8方法被移除,替换为通用的from_ultralytics方法(YOLOv8属于Ultralytics生态,新版本统一了所有Ultralytics模型的检测结果转换接口)。

修复及功能完善步骤

  • 替换检测结果转换方法:将sv.Detections.from_yolov8(results)改为sv.Detections.from_ultralytics(results)
  • 移除冗余代码:原代码在process_frame内重复初始化box_annotator,删除该行即可
  • 添加每帧目标数量统计:通过len(detections)获取当前帧目标数,可选择打印或标注到画面上

修改后的完整代码

import numpy as np
import supervision as sv
from ultralytics import YOLO  # 显式导入YOLO类

video_path = "/content/drive/MyDrive/CVcoursework/toycars.mp4"
model = YOLO("runs/detect/train/weights/best.pt")

# 初始化多边形区域
polygon = np.array([
    [0, 480],[640, 480], [640, 0], [0, 0]
])

video_info = sv.VideoInfo.from_video_path(video_path)
zone = sv.PolygonZone(polygon=polygon, frame_resolution_wh=video_info.resolution_wh)

# 初始化标注器(仅需初始化一次)
box_annotator = sv.BoxAnnotator(thickness=4, text_thickness=4, text_scale=2)
zone_annotator = sv.PolygonZoneAnnotator(zone=zone, color=sv.Color.white(), thickness=6, text_thickness=6, text_scale=4)

def process_frame(frame: np.ndarray, frame_idx: int) -> np.ndarray:
    # 目标检测
    results = model(frame, imgsz=640)[0]
    detections = sv.Detections.from_ultralytics(results)
    detections = detections[detections.class_id == 0]  # 过滤仅保留类别ID为0的目标
    zone.trigger(detections=detections)

    # 统计当前帧目标数量
    current_count = len(detections)
    print(f"第{frame_idx}帧检测到目标数量:{current_count}")

    # 画面标注
    labels = [f"{model.names[class_id]} {confidence:0.2f}" for _, confidence, class_id, _ in detections]
    frame = box_annotator.annotate(scene=frame, detections=detections, labels=labels)
    frame = zone_annotator.annotate(scene=frame)

    # 可选:将数量标注到画面左上角
    sv.draw_text(
        scene=frame,
        text=f"Count: {current_count}",
        text_anchor=sv.Point(x=20, y=50),
        text_color=sv.Color.white(),
        background_color=sv.Color.black(),
        text_scale=2,
        text_thickness=3
    )

    return frame

sv.process_video(source_path=video_path, target_path=f"/content/drive/MyDrive/CVcoursework/result.mp4", callback=process_frame)

from IPython import display
display.clear_output()

补充说明

  • 若Supervision版本过旧,执行pip install --upgrade supervision更新到最新版
  • 代码中新增frame_idx参数,可用于区分不同帧,方便后续统计分析
  • 画面上的数量标注为可选功能,不需要可直接删除sv.draw_text代码块

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 11:57:30