You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

54 lines
2.2 KiB
Python

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

from lxml.etree import Element, SubElement, tostring
def create_xml(boxs, img_shape, xml_path):
"""
创建xml文件依次写入xml文件必备关键字
:param boxs: txt文件中的box
:param img_shape: 图片信息xml中需要写入WHC
:return:
"""
node_root = Element('annotation')
node_folder = SubElement(node_root, 'folder')
node_folder.text = 'Images'
node_filename = SubElement(node_root, 'filename')
node_filename.text = str(img_shape[3])
node_size = SubElement(node_root, 'size')
node_width = SubElement(node_size, 'width')
node_width.text = str(img_shape[1])
node_height = SubElement(node_size, 'height')
node_height.text = str(img_shape[0])
node_depth = SubElement(node_size, 'depth')
node_depth.text = str(img_shape[2])
if len(boxs) >= 1: # 循环写入box
for box in boxs:
node_object = SubElement(node_root, 'object')
node_name = SubElement(node_object, 'name')
# if str(list_[4]) == "person": # 根据条件筛选需要标注的标签,例如这里只标记person这类不符合则直接跳过
# node_name.text = str(list_[4])
# else:
# continue
node_name.text = str(list(box.keys())[0])
node_difficult = SubElement(node_object, 'difficult')
node_difficult.text = '0'
node_bndbox = SubElement(node_object, 'bndbox')
node_xmin = SubElement(node_bndbox, 'xmin')
node_xmin.text = str(int(list(box.values())[0][0]))
node_ymin = SubElement(node_bndbox, 'ymin')
node_ymin.text = str(int(list(box.values())[0][1]))
node_xmax = SubElement(node_bndbox, 'xmax')
node_xmax.text = str(int(list(box.values())[0][2]))
node_ymax = SubElement(node_bndbox, 'ymax')
node_ymax.text = str(int(list(box.values())[0][3]))
xml = tostring(node_root, pretty_print=True) # 格式化显示,该换行的换行
# file_name = img_shape[3].split(".")[0]
# filename = xml_path+"/{}.xml".format(file_name)
f = open(xml_path, "wb")
f.write(xml)
f.close()