如何将MS COCO数据集的单份JSON标注文件拆分为单图像对应JSON文件
拆分MS COCO单份JSON标注为单图像独立JSON文件
核心思路
COCO的标注JSON包含images(图像元信息)、annotations(标注数据)、categories(类别定义)三个核心字段。我们需要:
- 建立图像ID与图像信息的映射
- 按图像ID对所有标注进行分组
- 为每个图像生成包含其自身信息、对应标注(以及可选的类别定义)的独立JSON文件,保存到指定目录
操作步骤
确认目录结构
确保你的数据集目录符合要求:- 根目录:
datasets/ms_coco - 原始标注存放于:
datasets/ms_coco/annotations - 目标输出目录:
datasets/ms_coco/train2017_annotations、datasets/ms_coco/val2017_annotations等(脚本会自动创建不存在的目录)
- 根目录:
运行拆分脚本
以下是可直接使用的Python脚本,适配你的数据集结构:
import json import os from collections import defaultdict def split_coco_annotations(coco_json_path, output_dir): # 自动创建输出目录(如果不存在) os.makedirs(output_dir, exist_ok=True) # 读取原始COCO标注文件 with open(coco_json_path, 'r') as f: coco_data = json.load(f) # 构建图像ID到图像元信息的映射字典 img_id_map = {img['id']: img for img in coco_data['images']} # 按图像ID分组所有标注数据 img_annotations = defaultdict(list) for ann in coco_data['annotations']: img_annotations[ann['image_id']].append(ann) # 遍历每个图像,生成独立标注文件 for img_id, img_info in img_id_map.items(): # 组装单图像的标注数据 single_img_data = { 'image': img_info, 'annotations': img_annotations.get(img_id, []), 'categories': coco_data['categories'] # 可选:如果不需要类别定义可删除此行 } # 用图像文件名(不含后缀)作为输出JSON文件名,也可替换为图像ID img_base_name = os.path.splitext(img_info['file_name'])[0] output_path = os.path.join(output_dir, f'{img_base_name}.json') # 保存JSON文件,缩进4格保证可读性 with open(output_path, 'w') as f: json.dump(single_img_data, f, indent=4) print(f"拆分完成:共生成 {len(img_id_map)} 份标注文件,保存至 {output_dir}") # 批量处理不同子集的标注文件 if __name__ == '__main__': dataset_root = 'datasets/ms_coco' # 处理train2017关键点标注 split_coco_annotations( os.path.join(dataset_root, 'annotations', 'person_keypoints_train2017.json'), os.path.join(dataset_root, 'train2017_annotations') ) # 处理val2017关键点标注 split_coco_annotations( os.path.join(dataset_root, 'annotations', 'person_keypoints_val2017.json'), os.path.join(dataset_root, 'val2017_annotations') ) # 如需处理train2014/val2014,取消下方注释并修改路径 # split_coco_annotations( # os.path.join(dataset_root, 'annotations', 'person_keypoints_train2014.json'), # os.path.join(dataset_root, 'train2014_annotations') # )
自定义调整说明
- 文件名规则:如果想用图像ID而非文件名命名输出JSON,将
img_base_name = os.path.splitext(img_info['file_name'])[0]替换为img_base_name = str(img_id)即可。 - 精简文件体积:如果不需要保留
categories字段,直接删除single_img_data中的对应键即可。 - 依赖说明:脚本仅使用Python标准库,无需额外安装第三方包。
内容的提问来源于stack exchange,提问作者Tewodros Legesse Munea
相关产品推荐
相关产品推荐

