python3 txt文件转xml(VOC)格式
from lxml.etree import Element, SubElement, tostringfrom xml.dom.minidom import parseStringimport osdef make_xml(f,save_xml_path):# 第一层循环遍历所有的照片for line in f:lines = str(line)....
·
from lxml.etree import Element, SubElement, tostring
from xml.dom.minidom import parseString
import os
def make_xml(f,save_xml_path):
# 第一层循环遍历所有的照片
for line in f:
lines = str(line).split(' ')
box_num = len(lines)-2
pic_name = str(lines[0])
node_root = Element('annotation')
node_filename = SubElement(node_root, 'filename')
# 图片名字
node_filename.text = pic_name
# 第二层循环遍历有多少个框
for i in range(box_num):
bbox = str(lines[i+2]).split(',')
cls_name = bbox[-2]
node_object = SubElement(node_root, 'object')
node_name = SubElement(node_object, 'name')
# 类别名字
node_name.text = class_name(cls_name)
node_bndbox = SubElement(node_object, 'bndbox')
node_xmin = SubElement(node_bndbox, 'xmin')
node_xmin.text = str(int(bbox[0]))
node_ymin = SubElement(node_bndbox, 'ymin')
node_ymin.text = str(int(bbox[1]))
node_xmax = SubElement(node_bndbox, 'xmax')
node_xmax.text = str(int(bbox[2]))
node_ymax = SubElement(node_bndbox, 'ymax')
node_ymax.text = str(int(bbox[3]))
xml = tostring(node_root, pretty_print = True)
dom = parseString(xml)
#print xml 打印查看结果
xml_name = pic_name.replace(".jpg","")
xml_name = os.path.join(save_xml_path, xml_name + '.xml')
with open(xml_name, 'wb') as f:
f.write(dom.toprettyxml(indent='\t', encoding='utf-8'))
txt_path = '/home/yxq/桌面/xxx/new_train.txt'
save_xml_path = '/home/yxq/桌面/xxx/Annotations'
f = open(txt_path,'r')
f = f.readlines()
make_xml(f,save_xml_path)
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)