将json文件转换为xml文件,并写入相关属性

目录

一,介绍

1.json文件路径:“F:\code_demo\数据”

 2.json文件内容

        (1)json文件的version写入xml;

        (2)shapes属性中label以及points标注以我们想要的方式写入xml;

         (3)写入label标注

         (4)写入points标注

 3.xml文件路径:“F:\code_demo\data_xml”

二,代码

三,运行结果

xml文件夹路径:

这是xml文件内容: 


一,介绍

1.json文件路径:“F:\code_demo\数据”

 2.json文件内容

        (1)json文件的version写入xml;
        (2)shapes属性中label以及points标注以我们想要的方式写入xml;

         (3)写入label标注

        json文件中可能有json_labelName中六种label标注类型,这里我二分类标注xml_labelName和xml_moreLabelName并写入xml中,方便以后研究,以下是这部分代码:

注释:

        这里xml_labelName中的0为非早癌,1为早癌;在json_labelName中非早癌表示为0/字符串0/字符串0-*,而早癌则表示为1/字符串1/字符串1-*。

        二分类标注xml_labelName和xml_moreLabelName:前一个可以判断是否为癌症,后一个可以知道具体的病名。

#判断label标注类型并以二分类形式写入xml文件中
                if isinstance(labelName, str) and len(labelName) > 1:
                    ascii_values = []  #储存ascll码数组
                    for character in labelName:
                        ascii_values.append(ord(character))   #将labelName字符串转化为ascll码
                    for i in range(0, len(ascii_values)):    
                        if ascii_values[i] == 48:          #判断字符串中第一个数字是否为0(0的ascll码为48)
                            xml.write('\t\t<name>' + "0" + '</name>\n')
                            xml.write('\t\t<moreLabel>' + labelName + '</moreLabel>\n')
                            break
                        elif ascii_values[i] == 49:  #判断字符串中第一个数字是否为1(0的ascll码为49)
                            xml.write('\t\t<name>' + "1" + '</name>\n')
                            xml.write('\t\t<moreLabel>' + labelName + '</moreLabel>\n')
                            break
                        else:
                            i += 1
                else:   #当labelName为0/1时
                    xml.write('\t\t<name>' + labelName + '</name>\n')
                    moreLabelName = "null"
                    xml.write('\t\t<moreLabel>' + moreLabelName + '</moreLabel>\n')
         (4)写入points标注

        points标注中是病变区域的坐标,每一个区域由多个坐标组成,每张图片可能有多个病变区域,所以一个json文件可能有多个points标注。

        我们将points标注的病变区域以一个矩阵坐标的形式写入xml文件,xmin为矩阵最靠近y轴的边,ymin为矩阵最靠近x轴的边,xman为矩阵远离y轴的边,yman为矩阵远离x轴的边。

 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:
                print('wrong1', json_file_)
                pass
            elif ymax <= ymin:
                print('wrong2', json_file_)
                pass
            else:
                xml.write('\t<object>\n')
                xml.write('\t\t<bndbox>\n')
                xml.write('\t\t\t<xmin>' + str(int(xmin)) + '</xmin>\n')
                xml.write('\t\t\t<ymin>' + str(int(ymin)) + '</ymin>\n')
                xml.write('\t\t\t<xmax>' + str(int(xmax)) + '</xmax>\n')
                xml.write('\t\t\t<ymax>' + str(int(ymax)) + '</ymax>\n')
                xml.write('\t\t</bndbox>\n')

                xml.write('\t</object>\n')

 3.xml文件路径:“F:\code_demo\data_xml”

二,代码

import os
from typing import List, Any
import numpy as np
import codecs
import json
from glob import glob
import cv2
import shutil
from sklearn.model_selection import train_test_split
import re
from tqdm import tqdm

# json文件路径
labelme_path = r"F:\code_demo\数据/"
image_path = r"F:\code_demo\数据/"
# 原始labelme标注数据路径
saved_path = r"F:\code_demo\data_xml/"
# 保存路径
isUseTest = True  # 是否创建test集

# 2.创建要求文件夹
if not os.path.exists(saved_path + "Annotations"):
    os.makedirs(saved_path + "Annotations")
if not os.path.exists(saved_path + "BMPImages/"):
    os.makedirs(saved_path + "BMPImages/")
if not os.path.exists(saved_path + "ImageSets/Main/"):
    os.makedirs(saved_path + "ImageSets/Main/")

# 3.获取待处理文件
# glob模块用来查找文件目录和文件
files = glob(labelme_path + "*.json")
# replace(old, new[, max])替换,split('/')[-1]  #以‘/ ’为分割f符,保留最后一段,str.split("[")[1]. split("]")[0]输出的是 [ 后的内容以及 ] 前的内容。
# 相当于循环文件名
files = [i.replace("\\", "/").split("/")[-1].split(".json")[0] for i in files]

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

    height, width, channels = cv2.imdecode(np.fromfile(image_path + json_file_ + ".bmp", dtype=np.uint8), -1).shape

    with codecs.open(saved_path + "Annotations/" + json_file_ + ".xml", "w", "utf-8") as xml:
        xml.write('<annotation>\n')
        xml.write('\t<folder>' + 'GastricCancer' + '</folder>\n')
        xml.write('\t<filename>' + json_file_ + ".bmp" + '</filename>\n')

        #版本号,判断标注名称
        version = json_file["version"]
        #写入版本号
        xml.write('\t<version>' + version + '</version>\n')

        xml.write('\t<source>\n')
        xml.write('\t\t<database>The GastricCancer Database</database>\n')
        xml.write('\t\t<annotation>The GastricCancer Database</annotation>\n')
        xml.write('\t\t<image>flickr</image>\n')
        xml.write('\t</source>\n')
       
        xml.write('\t<size>\n')
        xml.write('\t\t<width>' + str(width) + '</width>\n')
        xml.write('\t\t<height>' + str(height) + '</height>\n')
        xml.write('\t\t<depth>' + str(channels) + '</depth>\n')
        xml.write('\t</size>\n')

        xml.write('\t\t<segmented>1</segmented>\n')

        for multi in json_file["shapes"]:
            points = np.array(multi["points"])
            labelName = multi["label"]

            xmin = min(points[:, 0])
            xmax = max(points[:, 0])
            ymin = min(points[:, 1])
            ymax = max(points[:, 1])
            if xmax <= xmin:
                print('wrong1', json_file_)
                pass
            elif ymax <= ymin:
                print('wrong2', json_file_)
                pass
            else:
                xml.write('\t<object>\n')

                #判断label标注类型并以二分类形式写入xml文件中
                if isinstance(labelName, str) and len(labelName) > 1:
                    ascii_values = []  #储存ascll码数组
                    for character in labelName:
                        ascii_values.append(ord(character))   #将labelName字符串转化为ascll码
                    for i in range(0, len(ascii_values)):
                        if ascii_values[i] == 48:          #判断字符串中第一个数字是否为0(0的ascll码为48)
                            xml.write('\t\t<name>' + "0" + '</name>\n')
                            xml.write('\t\t<moreLabel>' + labelName + '</moreLabel>\n')
                            break
                        elif ascii_values[i] == 49:  #判断字符串中第一个数字是否为1(0的ascll码为49)
                            xml.write('\t\t<name>' + "1" + '</name>\n')
                            xml.write('\t\t<moreLabel>' + labelName + '</moreLabel>\n')
                            break
                        else:
                            i += 1
                else:   #当labelName为0/1时
                    xml.write('\t\t<name>' + labelName + '</name>\n')
                    moreLabelName = "null"
                    xml.write('\t\t<moreLabel>' + moreLabelName + '</moreLabel>\n')

                xml.write('\t\t<pose>Unspecified</pose>\n')
                xml.write('\t\t<truncated>1</truncated>\n')
                xml.write('\t\t<difficult>0</difficult>\n')
                xml.write('\t\t<bndbox>\n')
                xml.write('\t\t\t<xmin>' + str(int(xmin)) + '</xmin>\n')
                xml.write('\t\t\t<ymin>' + str(int(ymin)) + '</ymin>\n')
                xml.write('\t\t\t<xmax>' + str(int(xmax)) + '</xmax>\n')
                xml.write('\t\t\t<ymax>' + str(int(ymax)) + '</ymax>\n')
                xml.write('\t\t</bndbox>\n')

                xml.write('\t</object>\n')
                print(json_filename, xmin, ymin, xmax, ymax, labelName)
        xml.write('</annotation>')

# 5.复制图片到 data_xml/BMPImages/下
image_files = glob(image_path + "*.bmp")
print("copy image files to data_xml/BMPImages/")
for image in image_files:
    shutil.copy(image, saved_path + "BMPImages/")

# 6.拆分训练集、测试集、验证集
txtsavepath = saved_path + "ImageSets/Main/"
ftrainval = open(txtsavepath + '/trainval.txt', 'w')
ftest = open(txtsavepath + '/test.txt', 'w')
ftrain = open(txtsavepath + '/train.txt', 'w')
fval = open(txtsavepath + '/val.txt', 'w')
total_files = glob(saved_path + "Annotations/*.xml")
total_files = [i.replace("\\", "/").split("/")[-1].split(".xml")[0] for i in total_files]
trainval_files = []
test_files = []
if isUseTest:
    trainval_files, test_files = train_test_split(total_files, test_size=0.15, random_state=55)
else:
    trainval_files = total_files
for file in trainval_files:
    ftrainval.write(file + "\n")

# split
train_files, val_files = train_test_split(trainval_files, test_size=0.15, random_state=55)
# train
for file in train_files:
    ftrain.write(file + "\n")
# val
for file in val_files:
    fval.write(file + "\n")
for file in test_files:
    print(file)
    ftest.write(file + "\n")
ftrainval.close()
ftrain.close()
fval.close()
ftest.close()

三,运行结果

xml文件夹路径:

 

这是xml文件内容: 

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
可以使用Java中的org.json库将JSON文件转换XML文件。首先,你需要将JSON文件读取为一个JSONObject对象。然后,使用org.json.XML类的静态方法将JSONObject对象转换XML字符串。最后,将XML字符串写入一个新的XML文件中。 以下是一个示例代码,演示了如何将JSON文件转换XML文件: ```java import org.json.JSONObject; import org.json.XML; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class JsonToXmlConverter { public static void main(String\[\] args) { try { // 读取JSON文件内容 String jsonContent = new String(Files.readAllBytes(Paths.get("input.json"))); // 将JSON字符串转换JSONObject JSONObject jsonObject = new JSONObject(jsonContent); // 将JSONObject转换XML字符串 String xmlString = XML.toString(jsonObject); // 将XML字符串写入XML文件 FileWriter fileWriter = new FileWriter(new File("output.xml")); fileWriter.write(xmlString); fileWriter.close(); System.out.println("JSON文件成功转换XML文件。"); } catch (IOException e) { e.printStackTrace(); } } } ``` 在上面的示例代码中,我们假设JSON文件名为"input.json",将转换后的XML文件写入"output.xml"。你可以根据实际情况修改文件名和路径。 请注意,这个示例代码使用了Java 8的新特性,所以请确保你的Java版本支持这些特性。另外,你需要在项目中引入org.json库的依赖。 希望这个示例能帮到你! #### 引用[.reference_title] - *1* *2* [在Java中将JSON对象转换XML格式?](https://blog.csdn.net/weixin_30830643/article/details/114463948)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值