我在 xml 文件中有注释,例如这个,它遵循 PASCAL VOC 约定:
<annotation>
<folder>training</folder>
<filename>chanel1.jpg</filename>
<source>
<database>synthetic initialization</database>
<annotation>PASCAL VOC2007</annotation>
<image>synthetic</image>
<flickrid>none</flickrid>
</source>
<owner>
<flickrid>none</flickrid>
<name>none</name>
</owner>
<size>
<width>640</width>
<height>427</height>
<depth>3</depth>
</size>
<segmented>0</segmented>
<object>
<name>chanel</name>
<pose>Unspecified</pose>
<truncated>0</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>344</xmin>
<ymin>10</ymin>
<xmax>422</xmax>
<ymax>83</ymax>
</bndbox>
</object>
<object>
<name>chanel</name>
<pose>Unspecified</pose>
<truncated>0</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>355</xmin>
<ymin>165</ymin>
<xmax>443</xmax>
<ymax>206</ymax>
</bndbox>
</object>
</annotation>
检索例如字段的最干净的方式是什么filename
and bndbox
在Python中?
我正在尝试 ElementTree,这似乎是官方的 Python 解决方案,但我无法使其工作。
到目前为止我的代码:
from xml.etree import ElementTree as ET
tree = ET.parse("data/all/annotations/" + file)
fn = tree.find('filename').text
boxes = tree.findall('bndbox')
这会产生
fn == 'chanel1.jpg'
boxes == []
这样就成功提取出filename
场,但不是bndbox
'es.
对于您的问题来说,这是一个非常简单的解决方案:
这将返回嵌套列表中的框坐标 [xmin, ymin, xmax, ymax] 和文件名
有一次我遇到了 bndbox 标签的问题,这些标签混合在一起(ymin,xmin,...)或任何其他奇怪的组合,所以这段代码不仅读取位置,还读取标签。
最后我更新了代码。感谢 craq 和 Pritesh Gohil,你们是完全正确的。
希望能帮助到你...
import xml.etree.ElementTree as ET
def read_content(xml_file: str):
tree = ET.parse(xml_file)
root = tree.getroot()
list_with_all_boxes = []
for boxes in root.iter('object'):
filename = root.find('filename').text
ymin, xmin, ymax, xmax = None, None, None, None
ymin = int(boxes.find("bndbox/ymin").text)
xmin = int(boxes.find("bndbox/xmin").text)
ymax = int(boxes.find("bndbox/ymax").text)
xmax = int(boxes.find("bndbox/xmax").text)
list_with_single_boxes = [xmin, ymin, xmax, ymax]
list_with_all_boxes.append(list_with_single_boxes)
return filename, list_with_all_boxes
name, boxes = read_content("file.xml")
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)