目标检测数据集转换--labelme格式转coco格式通用代码

import os
import json
import xml.etree.ElementTree as ET

def xml_to_coco(xml_folder, output_json):
    coco_data = {
        "images": [],
        "annotations": [],
        "categories": [],
    }

    # Mapping between class names and category ids
    class_to_category_id = {}

    image_id = 1
    annotation_id = 1

    for xml_file in os.listdir(xml_folder):
        if xml_file.endswith(".xml"):
            xml_path = os.path.join(xml_folder, xml_file)

            tree = ET.parse(xml_path)
            root = tree.getroot()

            # Extract image information
            image_info = {
                "id": image_id,
                "file_name": root.find("filename").text,
                "width": int(root.find("size/width").text),
                "height": int(root.find("size/height").text),
            }

            coco_data["images"].append(image_info)

            # Extract annotations
            for obj in root.findall("object"):
                category_name = obj.find("name").text
                if category_name not in class_to_category_id:
                    class_to_category_id[category_name] = len(class_to_category_id)

                    category_info = {
                        "id": class_to_category_id[category_name],
                        "name": category_name,
                        "supercategory": "object",
                    }
                    coco_data["categories"].append(category_info)

                category_id = class_to_category_id[category_name]

                bbox = [
                    float(obj.find("bndbox/xmin").text),
                    float(obj.find("bndbox/ymin").text),
                    float(obj.find("bndbox/xmax").text) - float(obj.find("bndbox/xmin").text),
                    float(obj.find("bndbox/ymax").text) - float(obj.find("bndbox/ymin").text),
                ]

                area = bbox[2] * bbox[3]

                annotation_info = {
                    "id": annotation_id,
                    "image_id": image_id,
                    "category_id": category_id,
                    "bbox": bbox,
                    "area": area,
                    "iscrowd": 0,
                }

                coco_data["annotations"].append(annotation_info)
                annotation_id += 1

            image_id += 1
print('coco_data')
    # with open(output_json, "w") as json_file:
    #     json.dump(coco_data, json_file)


# Example usage
xml_folder_path =  ###your xml folder
output_json_path = ##your destination file to save json

xml_to_coco(xml_folder_path, output_json_path)

  • 7
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值