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

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))
相关推荐
池央36 分钟前
AI性能极致体验:通过阿里云平台高效调用满血版DeepSeek-R1模型
人工智能·阿里云·云计算
我们的五年37 分钟前
DeepSeek 和 ChatGPT 在特定任务中的表现:逻辑推理与创意生成
人工智能·chatgpt·ai作画·deepseek
Yan-英杰38 分钟前
百度搜索和文心智能体接入DeepSeek满血版——AI搜索的新纪元
图像处理·人工智能·python·深度学习·deepseek
Fuweizn40 分钟前
富唯智能可重构柔性装配产线:以智能协同赋能制造业升级
人工智能·智能机器人·复合机器人
taoqick3 小时前
对PosWiseFFN的改进: MoE、PKM、UltraMem
人工智能·pytorch·深度学习
suibian52353 小时前
AI时代:前端开发的职业发展路径拓宽
前端·人工智能
预测模型的开发与应用研究4 小时前
数据分析的AI+流程(个人经验)
人工智能·数据挖掘·数据分析
源大模型4 小时前
OS-Genesis:基于逆向任务合成的 GUI 代理轨迹自动化生成
人工智能·gpt·智能体
PowerBI学谦5 小时前
Python in Excel高级分析:一键RFM分析
大数据·人工智能·pandas
运维开发王义杰6 小时前
AI: Unsloth + Llama 3 微调实践,基于Colab
人工智能·llama