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

Detectron2加载自定义COCO数据集时遇FileNotFoundError求助

解决方案

1. 清理重复注册的代码

你的代码存在重复导入和注册数据集的情况,可能引发冲突。先简化代码,只保留正确的注册逻辑:

from detectron2.data.datasets import register_coco_instances
from detectron2.data import DatasetCatalog

# 分别注册训练集和验证集,确保路径准确
register_coco_instances("resectionline_train", {}, "./content/resectionline/train/instances.json", "./content/resectionline/train/")
register_coco_instances("resectionline_val", {}, "./content/resectionline/val/instances.json", "./content/resectionline/val/")

# 先测试训练集加载
dataset_dicts = DatasetCatalog.get("resectionline_train")

2. 规避相对路径陷阱

在Google Colab中,相对路径容易因当前工作目录变化出错。直接使用绝对路径注册,避免路径歧义:

# 用绝对路径指定JSON和图片目录
register_coco_instances("resectionline_train", {}, "/content/resectionline/train/instances.json", "/content/resectionline/train/")

你可以先运行!pwd查看当前工作目录,确认路径是否匹配。

3. 修正CVAT导出JSON的格式问题

虽然你确认是COCO格式,但CVAT导出的JSON常存在细节问题:

  • 图片路径不匹配:打开instances.json,检查images字段里的file_name——CVAT可能导出带本地路径的文件名(比如/xxx/xxx/abc.jpg),需要批量替换为仅文件名:
    import json
    
    with open("/content/resectionline/train/instances.json", "r") as f:
        data = json.load(f)
    
    # 剥离file_name中的路径,只保留纯文件名
    for img in data["images"]:
        img["file_name"] = img["file_name"].split("/")[-1]
    
    with open("/content/resectionline/train/instances.json", "w") as f:
        json.dump(data, f)
    
  • 编码或格式错误:CVAT导出的JSON可能存在编码异常,重新保存为标准UTF-8格式:
    import json
    
    with open("/content/resectionline/train/instances.json", "r", encoding="utf-8") as f:
        data = json.load(f)
    
    with open("/content/resectionline/train/instances.json", "w", encoding="utf-8") as f:
        json.dump(data, f, indent=2)
    
  • 核心字段缺失:确认JSON包含images、annotations、categories三个顶级字段,且annotations中的category_id与categories里的id完全对应。

4. 验证文件权限

运行以下命令确认文件存在且有读取权限:

!ls -l /content/resectionline/train/instances.json

如果权限不足,执行命令赋予读取权限:

!chmod +r /content/resectionline/train/instances.json

内容的提问来源于stack exchange,提问作者Laura Rabadan Camacho

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 18:34:58