python - 在 python 中读取 PASCAL VOC 注释

标签 python xml python-3.x

我在 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>

在 Python 中检索字段 filenamebndbox 的最简洁方法是什么?

我正在尝试 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

最佳答案

对于您的问题,这是一个非常简单的解决方案:

这将在嵌套列表 [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")

关于python - 在 python 中读取 PASCAL VOC 注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53317592/

相关文章:

Java+DOM : How do I set the base namespace of an (already created) Document?

python - 我们如何从被调用者修改调用者中的值?

python :TypeError: this constructor takes no arguments

python - AIOHTTP meme 命令discord.py

python - Pandas .describe() 仅返回 4 个关于 int 数据帧的统计信息(计数、唯一、顶部、频率)...没有最小值、最大值等

python - Numpy:搜索第一个匹配行

java - 了解简单 XML 中的构造函数注入(inject)

java - 匹配具有不同顺序和数字格式的嵌套元素

python - 获取字典的最小值的键,该键又在数组中

python - 我应该使用属性还是 getter 和 setter?