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

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))
相关推荐
起个名字都难啊3 分钟前
visual studio配置libtorch
人工智能·visual studio
一点一一4 分钟前
nestjs+langchain:大模型的基本调用、对message的
人工智能·后端
昊星自动化8 分钟前
以房间为单元,筑稳GMP安全屏障-洁净区域风量压差控制技术方案概述
人工智能·国产替代·文丘里阀·实验室通风系统·蝶阀
总写bug的程序员10 分钟前
用 AI 蒸馏球员的思维操作系统:qiuyuan-skill 技术解析
人工智能·unity·游戏引擎
超级AI_mes10 分钟前
化工MES解决方案:从配方管控到安全追溯的智慧转型
大数据·人工智能·5g·能源·制造·业界资讯·设备采集
光影少年16 分钟前
Python+LangGraph学习路线及发展前景
开发语言·人工智能·python·学习
七夜zippoe16 分钟前
OpenClaw Webhook 与 Hooks 机制详解
人工智能·架构·webhook·hooks·openclaw
天天进步201517 分钟前
不止于 UI:OpenWork 的核心哲学与“引擎+外壳”架构全景图
人工智能·ui·架构
刘 大 望21 分钟前
RAG相关技术介绍及Spring AI中使用--第三期
java·人工智能·后端·spring·机器学习·ai·aigc
Mr数据杨23 分钟前
成人收入预测建模与信用评估应用
大数据·人工智能·机器学习·数据分析·kaggle