首页 > 解决方案 > 在 python 中读取 PASCAL VOC 注释

问题描述

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

例如filenamebndbox在 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。

标签: pythonxmlpython-3.x

解决方案


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

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

推荐阅读