深度学习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
            }
        }
    ]
}
相关推荐
好奇龙猫13 分钟前
【AI学习-comfyUI学习-第三十节-第三十一节-FLUX-SD放大工作流+FLUX图生图工作流-各个部分学习】
人工智能·学习
沈浩(种子思维作者)20 分钟前
真的能精准医疗吗?癌症能提前发现吗?
人工智能·python·网络安全·健康医疗·量子计算
minhuan22 分钟前
大模型应用:大模型越大越好?模型参数量与效果的边际效益分析.51
人工智能·大模型参数评估·边际效益分析·大模型参数选择
Cherry的跨界思维28 分钟前
28、AI测试环境搭建与全栈工具实战:从本地到云平台的完整指南
java·人工智能·vue3·ai测试·ai全栈·测试全栈·ai测试全栈
MM_MS31 分钟前
Halcon变量控制类型、数据类型转换、字符串格式化、元组操作
开发语言·人工智能·深度学习·算法·目标检测·计算机视觉·视觉检测
ASF1231415sd43 分钟前
【基于YOLOv10n-CSP-PTB的大豆花朵检测与识别系统详解】
人工智能·yolo·目标跟踪
水如烟1 小时前
孤能子视角:“意识“的阶段性回顾,“感质“假说
人工智能
Carl_奕然2 小时前
【数据挖掘】数据挖掘必会技能之:A/B测试
人工智能·python·数据挖掘·数据分析
旅途中的宽~2 小时前
《European Radiology》:2024血管瘤分割—基于MRI T1序列的分割算法
人工智能·计算机视觉·mri·sci一区top·血管瘤·t1
岁月宁静2 小时前
当 AI 越来越“聪明”,人类真正的护城河是什么:智商、意识与认知主权
人工智能