import os
import json
from xml.etree.ElementTree import Element, SubElement, tostring
from xml.dom.minidom import parseString
# JSON标注文件路径和保存生成的XML标签的文件夹路径
json_file_path = r'./train_annos.json' # 替换为你的JSON文件路径
xml_folder_path = r'./Annotations/' # 替换为你想要保存XML文件的文件夹路径
# 创建保存XML文件的文件夹
os.makedirs(xml_folder_path, exist_ok=True)
def json_to_xml(json_data):
root = Element('annotation')
# 创建子元素并添加到根元素
filename = SubElement(root, 'filename')
filename.text = json_data['name']
size = SubElement(root, 'size')
width = SubElement(size, 'width')
width.text = str(json_data['image_width'])
height = SubElement(size, 'height')
height.text = str(json_data['image_height'])
# 创建object元素
obj = SubElement(root, 'object')
name = SubElement(obj, 'name')
name.text = str(json_data['category'])
# 创建bndbox元素
bndbox = SubElement(obj, 'bndbox')
xmin = SubElement(bndbox, 'xmin')
xmin.text = str(json_data['bbox'][0])
ymin = SubElement(bndbox, 'ymin')
ymin.text = str(json_data['bbox'][1])
xmax = SubElement(bndbox, 'xmax')
xmax.text = str(json_data['bbox'][2])
ymax = SubElement(bndbox, 'ymax')
ymax.text = str(json_data['bbox'][3])
# 返回XML字符串
return root
def json_file_to_xml(json_file_path, xml_folder_path):
total_files = 0
with open(json_file_path, 'r', encoding='utf-8') as f:
json_data = json.load(f)
for data in json_data:
xml_str = tostring(json_to_xml(data), 'utf-8')
xml_str = parseString(xml_str).toprettyxml(indent=" ")
xml_file_name = os.path.splitext(data['name'])[0] + '.xml'
xml_file_path = os.path.join(xml_folder_path, xml_file_name)
with open(xml_file_path, 'w') as xml_file:
xml_file.write(xml_str)
total_files += 1
print(f"Total files converted: {total_files}")
json_file_to_xml(json_file_path, xml_folder_path)
数据集格式转换:json_to_xml
最新推荐文章于 2024-07-10 17:12:51 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)