【目标检测】 Coco格式Json文件转换成xml文件(已验证)

Coco格式Json文件转换成xml文件

修改coco_dir,json_path, save_dir,即图片位置,json位置,xml保存位置(自动创建,无需自建)

import cv2
import numpy as np
import os
import json
from collections import defaultdict
from xml.etree.ElementTree import Element, SubElement, tostring
import xml.dom.minidom as md


def create_xml_annotation(image_name, image_width, image_height, objects):
    annotation = Element("annotation")

    folder = SubElement(annotation, "folder")
    folder.text = "images"

    filename = SubElement(annotation, "filename")
    filename.text = image_name

    size = SubElement(annotation, "size")
    width = SubElement(size, "width")
    width.text = str(image_width)
    height = SubElement(size, "height")
    height.text = str(image_height)
    depth = SubElement(size, "depth")
    depth.text = "3"  # Assuming RGB images

    for obj in objects:
        obj_elem = SubElement(annotation, "object")
        name = SubElement(obj_elem, "name")
        name.text = obj['class']
        bndbox = SubElement(obj_elem, "bndbox")
        xmin = SubElement(bndbox, "xmin")
        xmin.text = str(obj['xmin'])
        ymin = SubElement(bndbox, "ymin")
        ymin.text = str(obj['ymin'])
        xmax = SubElement(bndbox, "xmax")
        xmax.text = str(obj['xmax'])
        ymax = SubElement(bndbox, "ymax")
        ymax.text = str(obj['ymax'])

    xml_str = tostring(annotation, encoding="unicode")
    xml_str = xml_str.replace('><', '>\n<')

    return xml_str


def cocojson2png_rectangles_xml(coco_dir, json_path, save_dir):
    save_path = os.path.join(save_dir)
    if not os.path.exists(save_path):
        os.makedirs(save_path)
    annotation_file = os.path.join(coco_dir, 'annotations', json_path)
    with open(annotation_file, 'r', encoding='utf-8') as annf:
        annotations = json.load(annf)
        images = [i['id'] for i in annotations['images']]

    img_anno = defaultdict(list)
    for anno in annotations['annotations']:
        for img_id in images:
            if anno['image_id'] == img_id:
                img_anno[img_id].append(anno)
    imgid_file = {}
    for im in annotations['images']:
        imgid_file[im['id']] = im['file_name']

    for img_idx in img_anno:
        image = cv2.imread(os.path.join(coco_dir,  imgid_file[img_idx]))
        h, w, _ = image.shape
        instance_rectangles = []  # 存储矩形锚框
        for idx, ann in enumerate(img_anno[img_idx]):
            mask = np.zeros((h, w), dtype=np.uint8)
            for an in ann['segmentation']:
                ct = np.expand_dims(np.array(an), 0).astype(int)
                contour = np.stack((ct[:, ::2], ct[:, 1::2])).T
                cv2.fillPoly(mask, [contour], 1)

            # 找到分割区域的外接矩形
            x, y, width, height = cv2.boundingRect(mask)
            instance_rectangles.append({
                'class': str(ann['category_id']),
                'xmin': str(x),
                'ymin': str(y),
                'xmax': str(x + width),
                'ymax': str(y + height)
            })

        # 生成 XML 内容
        xml_content = create_xml_annotation(
            image_name=imgid_file[img_idx],
            image_width=w,
            image_height=h,
            objects=instance_rectangles
        )

        # 保存 XML 文件
        xml_filename = os.path.join(save_path, imgid_file[img_idx].split('.')[0] + ".xml")
        with open(xml_filename, 'w') as xml_file:
            xml_file.write(xml_content)


if __name__ == '__main__':
    # 修改coco_dir json_path save_dir,图片位置,json位置,xml保存位置(自动创建,无需自建) 
    coco_dir = r"D:\StudyAPP\PyCharm2023\Projects\PreData\train"
    json_path = r"D:\StudyAPP\PyCharm2023\Projects\PreData\instances_train_trashcan.json"
    save_dir = r'D:\StudyAPP\PyCharm2023\Projects\PreData\xml_rectangles'
    cocojson2png_rectangles_xml(coco_dir, json_path, save_dir)


  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要将VOC格式的数据集换为COCO格式,可以按照以下步骤进行操作: 1. 首先,将VOC数据集中的Annotations文件夹里的文件按照训练集和验证集分别放在两个文件夹中。这样可以方便后续的处理。 2. 接下来,将这两个文件夹中的XML文件转换成COCO数据集的JSON格式。你可以使用相应的工具或者脚本来完成这个换过程。这个换过程会将XML文件中的标注信息提取出来,并按照COCO数据集的格式进行组织和保存。 3. 换完成后,你将得到两个JSON文件,分别对应训练集和验证集。这些JSON文件包含了每个图像的信息、标注框的位置和类别等相关信息。 通过以上步骤,你就成功地将VOC数据集换为了COCO格式,方便后续使用effcientdet等网络进行训练和应用。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [将VOC格式的数据集换为COCO格式xml格式转换成json格式](https://download.csdn.net/download/qq_28257631/85131545)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [voc数据集coco数据集](https://blog.csdn.net/jinjieingbiubiu/article/details/125385906)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值