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

Yolov8在Colab提取预测结果报错:'list'对象无'path'属性

解决YOLOv8提取检测结果并保存到CSV的问题

错误根源

你碰到的AttributeError是因为YOLOv8的model.predict()处理多图时返回的是Results对象的列表,不是单个Results实例。直接对这个列表调用path、boxes这些属性肯定报错——列表本身没这些属性,得先遍历列表里的每个Results对象。

可直接运行的解决方案代码

下面是能正确遍历子文件夹、提取所需信息并导出CSV的完整代码:

from ultralytics import YOLO
import csv
import os

# 加载你的YOLOv8模型(替换成你用的模型,比如yolov8s.pt)
model = YOLO('yolov8n.pt')

# 替换成你的图像文件夹路径(支持子文件夹递归遍历)
image_dir = '/content/your_image_folder'
# 输出CSV的路径
output_csv = '/content/detection_results.csv'

# 初始化CSV,写入表头
with open(output_csv, 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerow(['图像路径', '类别ID', '类别名称', '置信度', '框左上角x', '框左上角y', '框右下角x', '框右下角y'])

# 递归遍历所有子文件夹里的图像
for root, _, files in os.walk(image_dir):
    for file in files:
        # 只处理常见图像格式,可按需添加
        if file.lower().endswith(('.png', '.jpg', '.jpeg')):
            img_path = os.path.join(root, file)
            # 执行预测,注意返回的是列表,取第一个元素才是单图的Results对象
            results = model(img_path)
            single_result = results[0]

            # 提取当前图像的路径
            img_full_path = single_result.path

            # 遍历这张图的所有检测框
            for box in single_result.boxes:
                # 把张量格式的结果转成普通数据类型
                class_id = int(box.cls[0])
                class_name = model.names[class_id]
                confidence = float(box.conf[0])
                x1, y1, x2, y2 = box.xyxy[0].tolist()

                # 追加写入CSV
                with open(output_csv, 'a', newline='') as f:
                    writer = csv.writer(f)
                    writer.writerow([img_full_path, class_id, class_name, confidence, x1, y1, x2, y2])

print(f"结果已保存到 {output_csv}")

核心注意事项

  • 必须先取单个Results对象:不管是单张还是多张图,model()返回的都是列表,一定要用results[0](单图)或者遍历列表(多图)拿到单个Results实例后,才能访问path、boxes属性。
  • boxes对象的属性说明:
    • box.cls:检测到的类别ID(张量类型,要转成int)
    • box.conf:检测置信度(张量类型,要转成float)
    • box.xyxy:边界框的左上角+右下角坐标(张量转成list后直接取数值)
  • 子文件夹遍历:用os.walk()实现递归遍历,确保不会漏掉任何子文件夹里的图像。

常见问题排查

  1. 如果还是报错,先检查YOLOv8版本是否最新,执行pip install --upgrade ultralytics升级试试;
  2. 要是model.names报错,换成single_result.names试试(旧版本YOLOv8的类别名称存在于Results对象里);
  3. 想存相对路径而非绝对路径,把img_full_path = single_result.path改成img_full_path = os.path.relpath(single_result.path, image_dir)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 15:32:19