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

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))
相关推荐
love530love14 分钟前
EPGF 新手教程 22教学模板不是压缩包:EPGF 如何设计“可复制、可检查、可回收”的课程模板?
ide·人工智能·windows·python·架构·pycharm·epgf
土豆.exe22 分钟前
IfAI v0.3.0 - 从“文本“到“多模态“的感知升级
人工智能·编辑器
JicasdC123asd24 分钟前
如何使用YOLOv10n进行台风灾害区域识别与分类——基于改进的HAFB-2模型实现
人工智能·yolo·分类
抖知书35 分钟前
喂饭级AI提示词公开!帮短视频创作者写脚本大纲
人工智能
Elastic 中国社区官方博客36 分钟前
JINA AI 与 Elasticsearch 的集成
大数据·人工智能·elasticsearch·搜索引擎·全文检索·jina
高洁0144 分钟前
AI智能体搭建(3)
人工智能·深度学习·算法·数据挖掘·知识图谱
道可云1 小时前
道可云人工智能每日资讯|南宁市公布第二批“人工智能+制造”应用场景“机会清单”和“能力清单”
人工智能·制造
ai_top_trends1 小时前
不同 AI 生成 2026 年工作计划 PPT 的使用门槛对比
人工智能·python·powerpoint
人工智能AI技术1 小时前
开源大模型选型指南:从LLaMA3到文心ERNIE,实战适配不同业务场景
人工智能
TOWE technology1 小时前
聚焦价值 重塑增长
大数据·人工智能·企业