【发布时间】:2019-12-02 02:33:46
【问题描述】:
如果 xmin,ymin,xmax,ymax 的值为 None,我想删除整个 <object> 标签。
xml文件为:
<annotation>
<folder>leuko</folder>
<filename>leuko32.jpg</filename>
<path>/Volumes/Windows/tongue-img/leuko/leuko32.jpg</path>
<source>
<database>Unknown</database>
</source>
<size>
<width>3456</width>
<height>2304</height>
<depth>3</depth>
</size>
<segmented>0</segmented>
<object>
<name>leuko</name>
<pose>Unspecified</pose>
<truncated>0</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>1329</xmin>
<ymin>671</ymin>
<xmax>1941</xmax>
<ymax>1252</ymax>
</bndbox>
</object>
<object>
<name>leuko</name>
<pose>Unspecified</pose>
<truncated>0</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>None</xmin>
<ymin>671</ymin>
<xmax>1941</xmax>
<ymax>1252</ymax>
</bndbox>
</object>
</annotation>
在这里,您可以看到 xmin text 的值为 None 然后应该在更新的 xml 文件中删除特定的 <object> 标记。我试过代码:
import xml.etree.ElementTree as ET
tree = ET.parse(original_xml)
root = tree.getroot()
removeList = list()
for child in tree.iter('object'):
if child.tag == 'bndbox':
name = child.find('xmin').text
if (name == None):
removeList.append(child)
for tag in removeList:
parent = tree.find('object')
parent.remove(tag)
tree.write(open(os.path.join(newxml_path , 'stomatitis427-2'), 'wb'))
【问题讨论】:
标签: python python-3.x elementtree