前提条件相关介绍实验环境Json文件内容转为VOC中的XML文件
Json文件内容代码实现输出结果
前提条件相关介绍熟悉Python基本语法熟悉Python OS模块熟悉Python3 JSON 数据解析
实验环境Python是一种跨平台的计算机程序设计语言。是一个高层次的结合了解释性、编译性、互动性和面向对象的脚本语言。最初被设计用于编写自动化脚本(shell),随着版本的不断更新和语言新功能的添加,越多被用于独立的、大型项目的开发。Python OS模块提供了非常丰富的方法用来处理文件和目录。Python JSON (Javascript Object Notation) 是一种轻量级的数据交换格式。实验目标:Python将Json文件内容转为VOC中的XML文件
Json文件内容转为VOC中的XML文件 Json文件内容 代码实现Python 3.x (面向对象的高级语言)
# -*- coding: utf-8 -*-
"""
Created on 2022/02/25 10:00
@author: TFX
"""
import os
import json
path = r"citypersons_all_train.json"
file = open(path, "rb")
data = json.load(file)
img_list = data["images"]
annotations_list = data["annotations"]
new_xml=r"Annotations"
if not os.path.isdir(new_xml):
os.makedirs(new_xml)
for i in img_list:
img_name = i["file_name"].split("/")[1]
width, height = i["width"],i["height"]
xml_name=img_name.split('.')[0]
xml_file = open((new_xml + '\' + xml_name + '.xml'), 'w')
xml_file.write('n')
xml_file.write(' citysperson n')
xml_file.write(' ' + str(img_name)+ ' n')
xml_file.write(' n')
xml_file.write(' ' + str(width) + ' n')
xml_file.write(' ' + str(height) + ' n')
xml_file.write(' 3 n')
xml_file.write(' n')
for j in annotations_list:
if i['id']==j['image_id']:
x,y,w,h=j['bbox']
xml_file.write(' n')
xml_file.write('n')
输出结果
citysperson aachen_000000_000019_leftImg8bit.png 497 249 3



