深度学习标注文件格式转换

json转xml

原始数据集文件夹中图片格式为bmp,标注文件为json,图片和标注文件放在同一个文件夹下面,将json转为xml格式,图片和标注文件分别存放在一个文件夹下面。

python 复制代码
headstr = """\
<annotation>
    <folder>VOC</folder>
    <filename>%s</filename>
    <source>
        <database>My Database</database>
        <annotation>COCO</annotation>
        <image>flickr</image>
        <flickrid>NULL</flickrid>
    </source>
    <owner>
        <flickrid>NULL</flickrid>
        <name>company</name>
    </owner>
    <size>
        <width>%d</width>
        <height>%d</height>
        <depth>%d</depth>
    </size>
    <segmented>0</segmented>
"""
objstr = """\
    <object>
        <name>%s</name>
        <pose>Unspecified</pose>
        <truncated>0</truncated>
        <difficult>0</difficult>
        <bndbox>
            <xmin>%d</xmin>
            <ymin>%d</ymin>
            <xmax>%d</xmax>
            <ymax>%d</ymax>
        </bndbox>
    </object>
"""

tailstr = '''\
</annotation>
'''

def write_xml(xml_path,head,labels,bboxs,tail):
    f = open(xml_path,'w')
    f.write(head)
    for i in range(len(labels)):
        bbox = bboxs[i]
        f.write(objstr % (labels[i],bbox[0],bbox[1],bbox[2],bbox[3]))
    f.write(tail)

def json_to_xml(json_file, xml_file):
    with open(json_file, 'r') as f:
        data = json.load(f)
        
    labels = []
    bboxs = []
    for shape in data['shapes']:
        label = shape['label']
        labels.append(label)
        xmin = int(shape['points'][0][0])
        ymin = int(shape['points'][0][1])
        xmax = int(shape['points'][1][0])
        ymax = int(shape['points'][1][1])
        bboxs.append([xmin, ymin, xmax, ymax])

    image_name = data['imagePath']
    imageWidth = data['imageWidth']
    imageHeight = data['imageHeight']
    head = headstr % (image_name,imageWidth, imageHeight, 3)
    tail = tailstr
    write_xml(xml_file, head, labels, bboxs, tail)

import os, shutil
from tqdm import tqdm
ori_path = "E:/projects/20240702181159-1Fs/"
img_path = "E:/projects/datasets/img/"
xml_path = "E:/projects/datasets/ann/"
for file in tqdm(os.listdir(ori_path)):
    if '.json' in file:
        json_to_xml(os.path.join(ori_path, file), os.path.join(xml_path, file.replace('json', 'xml')))
    else:
        shutil.copy(os.path.join(ori_path, file), os.path.join(img_path, file))
相关推荐
有为少年1 小时前
Welford 算法 | 优雅地计算海量数据的均值与方差
人工智能·深度学习·神经网络·学习·算法·机器学习·均值算法
GISer_Jing1 小时前
跨境营销前端AI应用业务领域
前端·人工智能·aigc
Ven%1 小时前
从单轮问答到连贯对话:RAG多轮对话技术详解
人工智能·python·深度学习·神经网络·算法
OpenCSG1 小时前
OpenCSG社区:激发城市AI主权创新引擎
人工智能·opencsg·agentichub
大厂技术总监下海1 小时前
没有千卡GPU,如何从0到1构建可用LLM?nanoChat 全栈实践首次公开
人工智能·开源
机器之心1 小时前
谁还敢说谷歌掉队?2025年,它打了一场漂亮的翻身仗
人工智能·openai
元智启1 小时前
企业AI智能体加速产业重构:政策红利与场景落地双轮驱动——从技术验证到价值交付的范式跃迁
人工智能·重构
智算菩萨1 小时前
强化学习从单代理到多代理系统的理论与算法架构综述
人工智能·算法·强化学习
San30.1 小时前
从零到一:开启 LangChain 的 AI 工程化之旅
人工智能·langchain·node.js
机器之心1 小时前
字节做了个 AI 手机,钉钉做了台 AI 主机
人工智能·openai