1.voc模板标签
<annotation>
<folder>123456</folder>
<filename>00000.jpg</filename>
<path>11223344.jpg</path>
<source>
<database>Unknown</database>
</source>
<size>
<width>2560</width>
<height>1440</height>
<depth>3</depth>
</size>
<segmented>0</segmented>
</annotation>
2.python代码
# -*- coding: utf-8 -*-
import os
import xml.etree.ElementTree as ET
def create_box(root, label, box):
x1,y1,x2,y2 = box
# object
object = ET.SubElement(root, "object")
name = ET.SubElement(object, "name")
name.text = label
pose = ET.SubElement(object, "pose")
pose.text = "Unspecified"
truncated = ET.SubElement(object, "truncated")
truncated.text = "0"
difficult = ET.SubElement(object, "difficult")
difficult.text = "0"
# bndbox
bndbox = ET.SubElement(object, "bndbox")
xmin = ET.SubElement(bndbox, "xmin")
xmin.text = str(x1)
ymin = ET.SubElement(bndbox, "ymin")
ymin.text = str(y1)
xmax = ET.SubElement(bndbox, "xmax")
xmax.text = str(x2)
ymax = ET.SubElement(bndbox, "ymax")
ymax.text = str(y2)
return tree
if __name__ == '__main__':
src_xml = "example2.xml"
dst_xml = "dst.xml"
tree = ET.parse(src_xml)
root = tree.getroot()
filename = root.find("filename").text
width = root.find("size/width").text
height = root.find("size/height").text
print(filename)
print(width)
print(height)
create_box(root, "abc", [0,0,100,100])
create_box(root, "bcd", [100, 100, 300, 300])
tree.write(dst_xml)