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

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))
相关推荐
余俊晖9 分钟前
再看多模态OCR视觉token裁剪思路-LayoutLite基于token的隐式布局分析
人工智能·ocr·多模态
二狗PPT14 分钟前
AI做PPT提示词怎么写,换个写法效果差很多
人工智能·powerpoint
段一凡-华北理工大学19 分钟前
AI推动工业智能化转型~系列文章07:分类与诊断算法体系:故障识别的完整工具箱
数据库·人工智能·算法·机器学习·分类·数据挖掘·高炉炼铁智能化
cxr82820 分钟前
第 7 章 . 设计哲学回顾与最终说明
人工智能
skywalk816342 分钟前
经过多次尝试,在kaggle 双T4训练Qwen2.5-0.5B的正确打开方式是:
人工智能·深度学习·机器学习·qwen2.5·段言
孪生质数-1 小时前
AI Agent 工程实践(一):大模型 API 接入示范
网络·人工智能·ai·chatgpt·github·claude·claudecode
qq_419563091 小时前
机器能思考吗?“——图灵测试、达特茅斯会议与 AI 的诞生
人工智能
维核科技1 小时前
世界模型落地:物理 AI 方案走向商用,机器人“理解“物理世界
人工智能
神神道呵he1 小时前
[深度学习] 大模型学习-RAG技术全景解析
人工智能·深度学习·学习
deepseek231 小时前
750 亿参数只激活 37 亿:LG 开源 K-EXAONE 2.0,与 DeepSeek 的路线之争迎来新玩家
人工智能·ai agent·mcp