深度学习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
            }
        }
    ]
}
相关推荐
前端开发江鸟27 分钟前
RAG 回答错了,问题到底出在召回、重排,还是生成?
人工智能
美狐美颜SDK开放平台42 分钟前
直播app开发如何实现主播级美颜效果?美颜sdk开发方案详解
人工智能·音视频·美颜sdk·视频美颜sdk·美颜api
东方小月1 小时前
从零开发一个 Coding Agent(四):使用状态机校验大模型事件流
前端·人工智能·后端
大龄码农有梦想1 小时前
使用大模型服务如何保证数据安全?企业 AI 安全、私有化部署与治理实践
人工智能·私有化部署·数据安全·信创·ai agent·智能体·智能体开发平台
冬奇Lab1 小时前
每日一个开源项目(第170篇):CodeWiki - ACL 2026 论文级代码库自动文档生成,递归多 Agent 架构
人工智能·开源·资讯
lxw18449125141 小时前
Claude-Code企业级培训教程
人工智能
冬奇Lab1 小时前
代码库知识库系列(01):技术全景——为什么代码理解比文档检索难十倍
人工智能
MartinYeung51 小时前
[论文学习]迈向自主医疗人工智能智能体:MIRA系统深度分析
人工智能·学习
土星云SaturnCloud2 小时前
边缘侧大模型部署的新利器——国科环宇GK 300I大模型一体机深度评测与架构解析
服务器·人工智能·ai·边缘计算
_Jimmy_2 小时前
Agent 溯源精度提升方案
人工智能·python·langchain