ElementTree 元素的一致性
Consistency of ElementTree elements
我正在使用 xml 来描述边界框,并打算过滤掉 xml 文件中的一些元素。典型的 xml 可能看起来像:
<annotation>
<folder>original2</folder>
<filename>beach146.jpg</filename>
<path>/home/train/original/beach146.jpg</path>
<source>
<database>Unknown</database>
</source>
<size>
<width>800</width>
<height>533</height>
<depth>3</depth>
</size>
<segmented>0</segmented>
<object>
<name>person</name>
<pose>Unspecified</pose>
<truncated>0</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>314</xmin>
<ymin>315</ymin>
<xmax>559</xmax>
<ymax>400</ymax>
</bndbox>
</object>
<object>
<name>boat</name>
<pose>Unspecified</pose>
<truncated>0</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>580</xmin>
<ymin>193</ymin>
<xmax>602</xmax>
<ymax>205</ymax>
</bndbox>
</object>
</annotation>
我正在对 bbox 坐标进行一些检查,如有必要,请删除包含相应 bbox 的 object
。
我正在使用类似以下内容访问坐标:
xmin = int(obj.find('bndbox').find('xmax').text)
但它看起来很尴尬和丑陋所以我切换到:
xmin = int(obj[4][0].text)
这似乎好一点。 obj
来自 objs = tree.findall('object')
因此甚至可以通过将相同的索引应用于根来优化它,例如:
print(root[7][4][0].tag, root[7][4][0].text)
xmin 580
我的问题是索引系统是否一致并且在每个 xml 文件中都能按预期工作。这意味着它将 return 元素按照它们在文件中的写入顺序排列。我的 xml 文件应具有相同的元素顺序。在其他情况下,应检查 obj[4][0].tag
以验证我正在处理预期的元素。
我认为索引系统是一致的。但是通过索引访问元素可能会造成混淆并且容易出错。
我的建议是使用findtext()
。
from xml.etree import ElementTree as ET
tree = ET.parse("annotation.xml")
for obj in tree.findall("object"):
xmin = obj.findtext('bndbox/xmin')
...
我正在使用 xml 来描述边界框,并打算过滤掉 xml 文件中的一些元素。典型的 xml 可能看起来像:
<annotation>
<folder>original2</folder>
<filename>beach146.jpg</filename>
<path>/home/train/original/beach146.jpg</path>
<source>
<database>Unknown</database>
</source>
<size>
<width>800</width>
<height>533</height>
<depth>3</depth>
</size>
<segmented>0</segmented>
<object>
<name>person</name>
<pose>Unspecified</pose>
<truncated>0</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>314</xmin>
<ymin>315</ymin>
<xmax>559</xmax>
<ymax>400</ymax>
</bndbox>
</object>
<object>
<name>boat</name>
<pose>Unspecified</pose>
<truncated>0</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>580</xmin>
<ymin>193</ymin>
<xmax>602</xmax>
<ymax>205</ymax>
</bndbox>
</object>
</annotation>
我正在对 bbox 坐标进行一些检查,如有必要,请删除包含相应 bbox 的 object
。
我正在使用类似以下内容访问坐标:
xmin = int(obj.find('bndbox').find('xmax').text)
但它看起来很尴尬和丑陋所以我切换到:
xmin = int(obj[4][0].text)
这似乎好一点。 obj
来自 objs = tree.findall('object')
因此甚至可以通过将相同的索引应用于根来优化它,例如:
print(root[7][4][0].tag, root[7][4][0].text)
xmin 580
我的问题是索引系统是否一致并且在每个 xml 文件中都能按预期工作。这意味着它将 return 元素按照它们在文件中的写入顺序排列。我的 xml 文件应具有相同的元素顺序。在其他情况下,应检查 obj[4][0].tag
以验证我正在处理预期的元素。
我认为索引系统是一致的。但是通过索引访问元素可能会造成混淆并且容易出错。
我的建议是使用findtext()
。
from xml.etree import ElementTree as ET
tree = ET.parse("annotation.xml")
for obj in tree.findall("object"):
xmin = obj.findtext('bndbox/xmin')
...