代码之家  ›  专栏  ›  技术社区  ›  Jsevillamol

在python中读取PASCAL VOC注释

  •  2
  • Jsevillamol  · 技术社区  · 6 年前

    <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 bndbox 用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 == []
    

    因此,它成功地提取了 文件名 bndbox “是的。

    2 回复  |  直到 6 年前
        1
  •  26
  •   pix_1    4 年前

    有一次我与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")