json批量转化为xml文件
import os
from json import loads
from dicttoxml import dicttoxml
from xml.dom.minidom import parseString
def jsonToXml(json_path, xml_path):
with open(json_path, 'r', encoding='UTF-8')as json_file:
load_dict = loads(json_file.read())
my_item_func = lambda x: 'Annotation'
xml = dicttoxml(load_dict, custom_root='Annotations', item_func=my_item_func, attr_type=False)
dom = parseString(xml)
with open(xml_path, 'w', encoding='UTF-8')as xml_file:
xml_file.write(dom.toprettyxml())
def json_to_xml(json_dir, xml_dir):
if (os.path.exists(xml_dir) == False):
os.makedirs(xml_dir)
dir = os.listdir(json_dir)
for file in dir:
file_list = file.split(".")
if (file_list[-1] == 'json'):
jsonToXml(os.path.join(json_dir, file), os.path.join(xml_dir, file_list[0] + '.xml'))
print('==============')
print('文件转换已完成')
print('==============')
if __name__ == '__main__':
json_path = r"F:\Desktop\myfile1"
xml_path = "F:\Desktop\myfile2"
json_to_xml(json_path, xml_path)
json批量转化为txt文件
import os
import json
from tqdm import tqdm
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--json_path',
default=r'D:\Dataset\UG2_train\annotations/rtts.json', type=str,
help="input: coco format(json)")
parser.add_argument('--save_path', default=r'D:\Dataset\UG2_train\RTTS_txt', type=str,
help="specify where to save the output dir of labels")
arg = parser.parse_args()
def convert(size, box):
dw = 1. / (size[0])
dh = 1. / (size[1])
x = box[0] + box[2] / 2.0
y = box[1] + box[3] / 2.0
w = box[2]
h = box[3]
x = round(x * dw, 6)
w = round(w * dw, 6)
y = round(y * dh, 6)
h = round(h * dh, 6)
return (x, y, w, h)
if __name__ == '__main__':
json_file = arg.json_path
ana_txt_save_path = arg.save_path
data = json.load(open(json_file, 'r'))
if not os.path.exists(ana_txt_save_path):
os.makedirs(ana_txt_save_path)
id_map = {}
with open(os.path.join(ana_txt_save_path, 'classes.txt'), 'w') as f:
for i, category in enumerate(data['categories']):
f.write(f"{category['name']}\n")
id_map[category['id']] = i
print(id_map)
list_file = open(os.path.join(ana_txt_save_path, 'train2017.txt'), 'w')
for img in tqdm(data['images']):
filename = img["file_name"]
img_width = img["width"]
img_height = img["height"]
img_id = img["id"]
head, tail = os.path.splitext(filename)
ana_txt_name = head + ".txt"
f_txt = open(os.path.join(ana_txt_save_path, ana_txt_name), 'w')
for ann in data['annotations']:
if ann['image_id'] == img_id:
box = convert((img_width, img_height), ann["bbox"])
f_txt.write("%s %s %s %s %s\n" % (id_map[ann["category_id"]], box[0], box[1], box[2], box[3]))
f_txt.close()
list_file.write('D:/Dataset/UG2_train/RTTS/%s.png\n' % (head))
list_file.close()