我正在开发一个项目,其中我对某些叶子的图像进行了注释,并将它们保存为 xml 格式,以便使用对象检测来识别叶子上的害虫。 但是,由于我在某些对象中面临一些模糊性,因为某些害虫看起来很相似,但实际上它们是不同的,所以我考虑删除一个类。由于我已经注释了所有图像,手动删除标签是一项繁琐的任务,因此我想到编写一个脚本来删除 xml 文件中的这些对象。 文件的结构是:
<annotation>
<folder>Set 3 A</folder>
<filename>IMG-20200904-WA0105.jpg</filename>
<path>C:\Users\Admin\Desktop\Set 3 A\Set 3 A\IMG-20200904-WA0105.jpg</path>
<source>
<database>Unknown</database>
</source>
<size>
<width>960</width>
<height>1280</height>
<depth>3</depth>
</size>
<segmented>0</segmented>
<object>
<name>Whiteflies</name>
<pose>Unspecified</pose>
<truncated>0</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>232</xmin>
<ymin>83</ymin>
<xmax>286</xmax>
<ymax>173</ymax>
</bndbox>
</object>
<object>
<name>Jassid Attack Effect</name>
<pose>Unspecified</pose>
<truncated>0</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>356</xmin>
<ymin>7</ymin>
<xmax>563</xmax>
<ymax>359</ymax>
</bndbox>
</object>
<object>
<name>Jassid Attack Effect</name>
<pose>Unspecified</pose>
<truncated>0</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>356</xmin>
<ymin>7</ymin>
<xmax>563</xmax>
<ymax>359</ymax>
</bndbox>
</object>
<object>
<name>Whiteflies</name>
<pose>Unspecified</pose>
<truncated>0</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>232</xmin>
<ymin>83</ymin>
<xmax>286</xmax>
<ymax>173</ymax>
</bndbox>
</object>
因此,如果我想删除对象名称“Jassid Attack Effect”(它可能在文档中多次出现,并且必须将其全部删除,如上面的 xml 代码所示)及其内容,我该怎么做?例如:在解析时,对象名称是“Jassid Attack Effect”,然后我想从 xml 文件中完全删除它:
<object>
<name>Jassid Attack Effect</name>
<pose>Unspecified</pose>
<truncated>0</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>356</xmin>
<ymin>7</ymin>
<xmax>563</xmax>
<ymax>359</ymax>
</bndbox>
</object>
尝试这样的事情:
stuff = r"""your xml above""" #you need the "r" because you have unescaped backslashes; also note that the xml is not well-formed; you left out the closing <annotation> tag
from lxml import etree
doc = etree.XML(stuff)
target = doc.xpath('//object[name["Jassid Attack Effect"]]')[0]
target.getparent().remove(target)
print(etree.tostring(doc).decode())
输出:
<annotation>
<folder>Set 3 A</folder>
<filename>IMG-20200904-WA0105.jpg</filename>
<path>C:\Users\Admin\Desktop\Set 3 A\Set 3 A\IMG-20200904-WA0105.jpg</path>
<source><database>Unknown</database></source>
<size>
<width>960</width>
<height>1280</height>
<depth>3</depth>
</size>
<segmented>0</segmented>
<object>
<name>Whiteflies</name>
<pose>Unspecified</pose>
<truncated>0</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>232</xmin>
<ymin>83</ymin>
<xmax>286</xmax>
<ymax>173</ymax>
</bndbox>
</object>
</annotation>
pip install pascal-voc
from pascal import annotation_from_xml
from pascal.utils import save_xml
if __name__ == "__main__":
ann = annotation_from_xml("ann.xml")
ann.filter_objects(["Jassid Attack Effect"])
xml = ann.to_xml()
save_xml("new_ann.xml", xml)