【小脚本】批量xml标签名称一键修改

357 阅读1分钟

1、功能简介

当我们用labelimg标注完数据后,发现一些标签需要修改,应该怎么办,直接脚本一键批量修改,红色框为错误标签,绿色框为修正后的标签,注意修改需要一一对应; file

2、代码实现

废话不多说,直接上代码:

'''修改xml文件中错误的标签'''

import os 
import xml.etree.ElementTree as ET
from tqdm import tqdm


def modify_xml(input_path:str, src_name:list, out_name:list) -> None:
    '''修改xml文件中错误的标签'''
    xml_files = [file for file in os.listdir(input_path) if file.endswith('.xml')]
    for xml_file in tqdm(xml_files, desc='modify xml files'):
        xml_path  = os.path.join(input_path, xml_file)
        with open(xml_path, encoding='utf-8') as f:
            tree = ET.parse(f)
        root = tree.getroot()
        for object in root.findall('.//object'):
            if object.find('name').text in src_name:
                error_class = object.find('name').text
                object.find('name').text = out_name[src_name.index(error_class)]
                print(xml_file)
                tree.write(file_or_filename=xml_path, encoding = 'utf-8')
            else:
                continue


if __name__=='__main__':
    input_path = r'D:\data_set\helmet\Annotations'
    error_name= ['hat','person']
    correct_name = ['helmet','head']
    
    modify_xml(input_path, error_name, correct_name)

一键修改完标签,这样就能愉快的训练了!!!

本文由博客一文多发平台 OpenWrite 发布!