如何使用Python修改JSON,将COCO标注格式转为按图片关联标注格式
错误原因
你的代码存在几个核心逻辑问题:
- 遍历标注时没有匹配
image_id,导致所有标注都被分配给每一张图片 - 重复复用全局的
element、annotation字典,遍历过程中值被反复覆盖,没有为每一张图片/标注创建独立的新字典 - 缺少将
bbox元素转为float、category_id转为字符串的逻辑,不符合目标格式要求 - 存在大量冗余的未使用变量,嵌套逻辑错误
修正后代码
import json json_file = "C:/Temp/python/current_json.json" output = [] with open(json_file, 'r', encoding='utf-8') as f: dataset_dicts = json.load(f) # 遍历所有图片 for img in dataset_dicts["images"]: # 为当前图片创建独立的信息字典 current_img = { "image_id": int(img["id"]), "file_name": img["file_name"], "height": int(img["height"]), "width": int(img["width"]), "annotations": [] } # 筛选属于当前图片的标注 for ann in dataset_dicts["annotations"]: if ann["image_id"] == img["id"]: # 构造符合要求的标注对象 current_ann = { # 将bbox每个元素转为float "bbox": [float(x) for x in ann["bbox"]], "bbox_mode": 1, # 将category_id转为字符串 "category_id": str(ann["category_id"]) } current_img["annotations"].append(current_ann) output.append(current_img) # 写入结果 with open("python/new_json.json", "w", encoding='utf-8') as f: json.dump(output, f, indent=2)
运行上述代码即可生成完全符合要求的目标格式JSON。
内容的提问来源于stack exchange,提问作者linasster
相关产品推荐
相关产品推荐

