import os
import xml.etree.ElementTree as ETdef create_xml(xml_filename):# 创建根节点annotation = ET.Element("annotation")# 添加子节点folder = ET.SubElement(annotation, "folder")folder.text = "img"filename = ET.SubElement(annotation, "filename")filename.text = xml_filenamepath = ET.SubElement(annotation, "path")path.text = "/workspace/img/" + xml_filenamesource = ET.SubElement(annotation, "source")database = ET.SubElement(source, "database")database.text = "Unknown"size = ET.SubElement(annotation, "size")width = ET.SubElement(size, "width")width.text = "1920"height = ET.SubElement(size, "height")height.text = "1080"depth = ET.SubElement(size, "depth")depth.text = "3"segmented = ET.SubElement(annotation, "segmented")segmented.text = "0"obj = ET.SubElement(annotation, "object")name = ET.SubElement(obj, "name")name.text = "cover_plate"pose = ET.SubElement(obj, "pose")pose.text = "Unspecified"truncated = ET.SubElement(obj, "truncated")truncated.text = "0"difficult = ET.SubElement(obj, "difficult")difficult.text = "0"bndbox = ET.SubElement(obj, "bndbox")xmin = ET.SubElement(bndbox, "xmin")xmin.text = "0"ymin = ET.SubElement(bndbox, "ymin")ymin.text = "0"xmax = ET.SubElement(bndbox, "xmax")xmax.text = "1920"ymax = ET.SubElement(bndbox, "ymax")ymax.text = "1080"# 创建树结构并写入文件tree = ET.ElementTree(annotation)output_name = os.path.join("/app/xml", xml_filename[:-4] + ".xml")tree.write(output_name, encoding='utf-8', xml_declaration=True)if __name__ == '__main__':img_path = "/app/img"img_path_all = os.listdir(img_path)print(img_path_all)for i in img_path_all:create_xml(i)
结果如下:
<?xml version='1.0' encoding='utf-8'?>
<annotation><folder>img</folder><filename>192.168.60.110_20241230053729_[R][0@0][0].jpg</filename><path>/workspace/img/192.168.60.110_20241230053729_[R][0@0][0].jpg</path><source><database>Unknown</database></source><size><width>1920</width><height>1080</height><depth>3</depth></size><segmented>0</segmented><object><name>cover_plate</name><pose>Unspecified</pose><truncated>0</truncated><difficult>0</difficult><bndbox><xmin>0</xmin><ymin>0</ymin><xmax>1920</xmax><ymax>1080</ymax></bndbox></object>
</annotation>