基本结构:
<annotation>
<folder>文件夹</folder>
<filename>文件名</filename>
<path>路径</path>
<source>
<database>Unknown</database>
</source>
<size>
<width>100</width> #宽
<height>100</height> #高
<depth>3</depth> #深度
</size>
<segmented>0</segmented>
<object>
<name>people</name> #label名
<pose>Unspecified</pose>
<truncated>0</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>1</xmin>
<ymin>2</ymin>
<xmax>3</xmax>
<ymax>4</ymax>
</bndbox>
</object>
</annotation>
用到的库
try:
import xml.etree.cElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET
读取xml内容:
tree = ET.parse(path) # 打开xml文档
root = tree.getroot() # 获得root节点
之后就可以根据节点的名字,获取节点信息
1、获取图片大小
for node in root:
if node.tag == 'size':
width = node[0].text
height = node[1].text
2、获取label名
for node in root:
if node.tag == 'object':
label = node[0].text # peple
3、获取对象坐标
for node in root:
if node.tag == 'object':
for i in range(len(node)):
if node[i].tag == 'bndbox':
xmin = int(node[i][0].text)
ymin = int(node[i][1].text)
xmax = int(node[i][2].text)
ymax = int(node[i][3].text)
4、修改文件内容
tree = ET.parse(path) # 打开xml文档
root = tree.getroot() # 获得root节点
for node in root:
if node.tag == 'size':
node[0].text = str(200)
node[1].text = str(200)
if node.tag == 'object':
node[0].text = 'peple'
for i in range(len(node)):
if node[i].tag == 'bndbox':
int(node[i][0].text) = str(5)
int(node[i][1].text) = str(6)
int(node[i][2].text) = str(7)
int(node[i][3].text) = str(8)
tree.write(f)#修改完后保存