深度学习02-数据集格式转换

背景:

通常搜集完数据图片后,我们会用labelimg进行图片标注,比较高版本的labelimg支持的标注格式有三种,PascalVOC、YOLO、CreateML,标注的时候可以根据自己的算法模型数据集需求选择相应的格式,当然,也可以三种方式同时标注,不过会耗时间一些。有时候我们仅仅标注了一种格式转,而实际算法建模的时候可能需要对相应的格式进行转换。

xml转json:

默认选用PascalVOC方式的话,标注的数据集格式为XML,实例如下(2.xml):

复制代码
<annotation>
	<folder>Desktop</folder>
	<filename>ng2.png</filename>
	<path>C:\Users\Xiao\Desktop\ng2.png</path>
	<source>
		<database>Unknown</database>
	</source>
	<size>
		<width>1892</width>
		<height>851</height>
		<depth>3</depth>
	</size>
	<segmented>0</segmented>
	<object>
		<name>1</name>
		<pose>Unspecified</pose>
		<truncated>0</truncated>
		<difficult>0</difficult>
		<bndbox>
			<xmin>60</xmin>
			<ymin>381</ymin>
			<xmax>354</xmax>
			<ymax>583</ymax>
		</bndbox>
	</object>
</annotation>

将该文档转换为json格式并保存的代码如下:

复制代码
import xml.etree.ElementTree as ET
import json

def xml_to_json(xml_file, json_file):
    tree = ET.parse(xml_file)
    root = tree.getroot()

    data = []
    for obj in root.findall('object'):
        obj_data = {}
        obj_data['name'] = obj.find('name').text
        obj_data['bbox'] = {
            'xmin': int(obj.find('bndbox/xmin').text),
            'ymin': int(obj.find('bndbox/ymin').text),
            'xmax': int(obj.find('bndbox/xmax').text),
            'ymax': int(obj.find('bndbox/ymax').text)
        }
        data.append(obj_data)

    json_data = {
        'filename': root.find('filename').text,
        'size': {
            'width': int(root.find('size/width').text),
            'height': int(root.find('size/height').text),
            'depth': int(root.find('size/depth').text)
        },
        'objects': data
    }

    with open(json_file, 'w') as f:
        json.dump(json_data, f, indent=4)

# Example usage
xml_file = r'C:\Users\Xiao\Desktop\tools\2.xml'
json_file = r'C:\Users\Xiao\Desktop\tools\2.json'
xml_to_json(xml_file, json_file)
print('数据转换完成!')

实际使用的时候需要适当修改一下文档路径才可以。

转换完之后的json内容如下(2.json):

复制代码
{
    "filename": "ng2.png",
    "size": {
        "width": 1892,
        "height": 851,
        "depth": 3
    },
    "objects": [
        {
            "name": "1",
            "bbox": {
                "xmin": 60,
                "ymin": 381,
                "xmax": 354,
                "ymax": 583
            }
        }
    ]
}
相关推荐
私人珍藏库10 分钟前
[Android] 会计快题库 -财会职称考试刷题学习
android·人工智能·学习·app·软件·多功能
Sirius Wu27 分钟前
OpenClaw Skill:Matplotlib 可视化技能 + 沙箱双层隔离完整详解
服务器·网络·人工智能·安全·ai·架构·aigc
闻道且行之33 分钟前
TurboOCR:基于PP-OCRv6的极速Windows离线OCR工具,深度解析3.4GB依赖背后的技术架构
c++·人工智能·python·qt·机器学习·ocr
We0 AI35 分钟前
2026 年的 B2B 官网竞争,已经不只是页面竞争了
人工智能·aigc·#ai建站
橙臣程1 小时前
深度学习2——CNN与RNN概述
rnn·深度学习·cnn
冬奇Lab1 小时前
每日一个开源项目(第160篇):Destructive Command Guard - 在 AI Agent 运行 rm -rf 之前拦截它
人工智能·安全·开源
绝世番茄1 小时前
鸿蒙HarmonyOS ArkTS原生拖拽排序深度解析
深度学习·华为·list·harmonyos·鸿蒙
IvorySQL1 小时前
PG 日报|SQL/PGQ 图查询基于联接重写机制实现
数据库·人工智能·sql·postgresql·区块链·ivorysql
博图光电1 小时前
博图汽车零配件视觉检测与测量解决方案
人工智能·汽车·视觉检测
仿生狮子1 小时前
别再说“全栈”了,AI 时代团队只认这 5 种人
前端·人工智能·后端