首页 > 解决方案 > 编辑 xml Annotations 数据集的标签

问题描述

我有一个具有以下注释结构的数据集:

`<annotation>
<folder>images</folder>
<filename>maksssksksss0.png</filename>
<size>
    <width>512</width>
    <height>366</height>
    <depth>3</depth>
</size>
<segmented>0</segmented>
<object>
    <name>without_mask</name>
    <pose>Unspecified</pose>
    <truncated>0</truncated>
    <occluded>0</occluded>
    <difficult>0</difficult>
    <bndbox>
        <xmin>79</xmin>
        <ymin>105</ymin>
        <xmax>109</xmax>
        <ymax>142</ymax>
    </bndbox>
</object>
<object>
    <name>with_mask</name>
    <pose>Unspecified</pose>
    <truncated>0</truncated>
    <occluded>0</occluded>
    <difficult>0</difficult>
    <bndbox>
        <xmin>185</xmin>
        <ymin>100</ymin>
        <xmax>226</xmax>
        <ymax>144</ymax>
    </bndbox>
</object>
<object>
    <name>without_mask</name>
    <pose>Unspecified</pose>
    <truncated>0</truncated>
    <occluded>0</occluded>
    <difficult>0</difficult>
    <bndbox>
        <xmin>325</xmin>
        <ymin>90</ymin>
        <xmax>360</xmax>
        <ymax>141</ymax>
    </bndbox>
</object>

`

我想做的是将所有对象标签“with_mask”编辑为“face_mask”,并从所有数据集文件中删除所有对象标签“without_mask”。关于从哪里开始的任何提示?图书馆之类的

标签: pythonxmleditvisioncvat

解决方案


查看 lxml 库并从那里导入 etree。对于搜索,您可以使用 .findall() 和 .find()。您还应该看看基本的 xpath 约束是如何工作的。要从树中删除元素,您可以使用 .remove 函数。如果你把它们放在一起,它可能看起来像这样:

from lxml import etree
#Open you xml 
tree = etree.parse("yourxml.xml")
root = tree.getroot()
#Find all objects in your tree
for obj in root.findall('.//object'):
        # Get the first child of the object which is called name
        name = obj.find("name")
        # Use .txt to access the value
        if name.text == "with_mask":
            # Change the text
            obj.attrib["name"] = "face_mask"
        if name.text == "without_mask":
            #Remove the object from the tree
            root.remove(obj)
# Write the tree
with open('yourxml2.xml', 'wb') as f:
    tree.write(f)

推荐阅读