转换前txt数据:
from xml.dom.minidom import Document
import os
import os.path
from PIL import Image
#--------目标检测数据txt转xml格式操作说明--------#
# ann_path目录下保存的是待输入的.txt文件
# xml_path目录下保存的是待输出的.xml文件
# .txt文件每行的格式如下(1行代表1个目标):
# 2 -88.3929 -36.5645 -87.8285 -48.0764
# 目标ID 左上角x坐标 左上角y坐标 右上角x坐标 右上角y坐标
#
# 第一步: 在本py程序目录下创建ann_path子目录和xml_path子目录,名字随意
# 第二步: 将待转换的.txt文件放入ann_path目录下
# 第三步: 运行txt_to_xml.py
#--------------------------------------------#
ann_path = '/home/guo/txt_2_xml/txt/'
xml_path = '/home/guo/txt_2_xml/xml/'
def writeXml(temp,objbud, wxml):
doc = Document()
# 目标id代表的数据类型
dict = {'0': "plane",
'1': "Lwing",
'2': "Rwing",
'3': "Ltail",
'4': "Rtail",
'5': "Mfoot"
}
annotation = doc.createElement('annotation')
doc.appendChild(annotation)
#folder = doc.createElement('folder')
for i in range(0, int(len(objbud))):
objbuds = objbud[i].split(' ')
# 获得目标类型ID
ClassType = doc.createElement("class")
annotation.appendChild(ClassType)
class_id = doc.createTextNode(dict[objbuds[0]])
ClassType.appendChild(class_id)
# 左上角x坐标
Lwing_x = doc.createElement("Lwing_x")
ClassType.appendChild(Lwing_x)
Lwing_x_txt = doc.createTextNode(str(objbuds[1]))
Lwing_x.appendChild(Lwing_x_txt)
# 左上角y坐标
Lwing_y = doc.createElement("Lwing_y")
ClassType.appendChild(Lwing_y)
Lwing_y_txt = doc.createTextNode(str(objbuds[2]))
Lwing_y.appendChild(Lwing_y_txt)
# 右下角x坐标
Rwing_x = doc.createElement("Rwing_x")
ClassType.appendChild(Rwing_x)
Rwing_x_txt = doc.createTextNode(str(objbuds[3]))
Rwing_x.appendChild(Rwing_x_txt)
# 右下角y坐标
Rwing_y = doc.createElement("Rwing_y")
ClassType.appendChild(Rwing_y)
Rwing_y_txt = doc.createTextNode(str(objbuds[4]))
Rwing_y.appendChild(Rwing_y_txt)
temfile = temp + "test.xml"
# 将以上创建的doc文件信息写入test.xml文件
with open(temfile, "w") as f :
f.write(doc.toprettyxml(indent='\t'))
# 提取test.xml里面的数据到newlines中
rewrite = open(temfile,'r')
lines = rewrite.read().split('\n')
newlines = lines[1:len(lines) -1]
# 将newlines中的数据转存到wxml路径中
fw = open(wxml, "w")
for i in range(0, len(newlines)):
fw.write(newlines[i] + '\n')
# 关闭并移除相关临时文件
fw.close()
rewrite.close()
os.remove(temfile)
return
for files in os.walk(ann_path):
# 创建临时文件目录temp,作为数据中转使用
temp = '/home/guo/txt_2_xml/temp'
if not os.path.exists(temp):
os.mkdir(temp)
# 遍历temp目录下的所有txt文件
for file in files[2]:
print(file + "-->start ! ! !")
# 获得将要保存的txt文件的所有数据
filelabel = open(ann_path+file, "r")
lines = filelabel.read().split('\n')
obj = lines[:len(lines)-1]
# 获得将要保存的xml文件的绝对路径
filename = xml_path + os.path.splitext(file)[0] + '.xml'
# 将每个txt文件的信息转换为xml格式
writeXml(temp, obj, filename)
# 关闭临时文件
os.rmdir(temp)
转换后xml数据: