-1

我正在做一个项目,我对某些叶子的图像进行了注释,并将它们保存为 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>
4

1 回答 1

0

尝试这样的事情:

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>
于 2021-03-07T20:57:46.697 回答