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

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))
相关推荐
大千AI助手1 小时前
SWE-bench:真实世界软件工程任务的“试金石”
人工智能·深度学习·大模型·llm·软件工程·代码生成·swe-bench
天上的光2 小时前
17.迁移学习
人工智能·机器学习·迁移学习
后台开发者Ethan2 小时前
Python需要了解的一些知识
开发语言·人工智能·python
猫头虎3 小时前
猫头虎AI分享|一款Coze、Dify类开源AI应用超级智能体快速构建工具:FastbuildAI
人工智能·开源·prompt·github·aigc·ai编程·ai-native
重启的码农3 小时前
ggml 介绍 (6) 后端 (ggml_backend)
c++·人工智能·神经网络
重启的码农3 小时前
ggml介绍 (7)后端缓冲区 (ggml_backend_buffer)
c++·人工智能·神经网络
数据智能老司机3 小时前
面向企业的图学习扩展——图简介
人工智能·机器学习·ai编程
盼小辉丶3 小时前
PyTorch生成式人工智能——使用MusicGen生成音乐
pytorch·python·深度学习·生成模型
mit6.8244 小时前
[AI React Web] 包与依赖管理 | `axios`库 | `framer-motion`库
前端·人工智能·react.js