python将json转xml

python将json转xml

1、代码

# coding=utf-8
import os
import xml.dom

import numpy as np
import codecs
import json
import glob
import cv2
import shutil

# 1.标签路径
labelme_path = r"D:\1\2"  # 原始json、jpg标注数据路径,需要更换成自己的数据集名称
saved_path = r"D:\1\3"  # 保存路径

# 2.获取待处理文件
files = glob.glob("%s/*.json" % (labelme_path))

# 3.读取标注信息并写入 xml
for json_filename in files:
     json_file = json.load(open(json_filename, "r", encoding="utf-8"))

     # 图像名字
     img_name = json_filename.replace(".json", ".jpg")
     height, width, channels = cv2.imread(img_name).shape
     # xml名字
     xmlName = os.path.join(saved_path, json_filename.split("\\")[-1].replace(".json", ".xml"))

     with codecs.open(xmlName, "w", "utf-8") as xml:
        print(2)
        xml.write('\n')
        xml.write('\t' + 'jpg' + '\n')
        xml.write('\t' + img_name + '\n')
        # -------------------------------------------------
        xml.write('\t\n')
        xml.write('\t\thulan\n')

        # --------------------------------------------------
        xml.write('\t\n')
        # -----------------------------------------------------------
        xml.write('\t\n')
        xml.write('\t\t' + str(width) + '\n')
        xml.write('\t\t' + str(height) + '\n')
        xml.write('\t\t' + str(channels) + '\n')
        # ------------------------------------------------
        xml.write('\t\n')
        xml.write('\t\t0\n')

        # 节点判断
        for multi in json_file["shapes"]:
            points = np.array(multi["points"])
            xmin = min(points[:, 0])
            xmax = max(points[:, 0])
            ymin = min(points[:, 1])
            ymax = max(points[:, 1])
            label = multi["label"]
            if xmax <= xmin:
                pass
            elif ymax <= ymin:
                pass
            else:
                xml.write('\t\n')
                xml.write('\t\t' + json_file["shapes"][0]["label"] + '\n')
                xml.write('\t\tUnspecified\n')
                xml.write('\t\t0\n')
                xml.write('\t\t0\n')
                xml.write('\t\t\n')
                xml.write('\t\t\t' + str(xmin) + '\n')
                xml.write('\t\t\t' + str(ymin) + '\n')
                xml.write('\t\t\t' + str(xmax) + '\n')
                xml.write('\t\t\t' + str(ymax) + '\n')
                xml.write('\t\t\n')
                xml.write('\t\n')
                print(json_filename, xmin, ymin, xmax, ymax, label)
        xml.write('')

        # 复制图片
        newImgName = os.path.join(saved_path, img_name.split("\\")[-1])
        shutil.copy(img_name, newImgName)

2、效果

python将json转xml_第1张图片

python将json转xml_第2张图片

你可能感兴趣的:(python,python,json,xml)