yolov5 批量修改labelimg标注xml文件内容(python版本)

yolov5训练自定义数据集时,需要对半自动打标签的xml文件中的类别进行批量修改。
半自动打标签只能将所有图片都归为一个类别,后期如果想要修改类别可以一键修改,避免从labelimg中逐一修改。
半自动打标签方法:
https://blog.csdn.net/qq_42754919/article/details/130385696

<annotation>
	<folder>imgfolder>
	<filename>20230426094013112_0.bmpfilename>
	<path>D:\test\anchor_xml\img\20230426094013112_0.bmppath>
	<source>
		<database>Unknowndatabase>
	source>
	<size>
		<width>1024width>
		<height>512height>
		<depth>3depth>
	size>
	<segmented>0segmented>
	<object>
		<name>breakname>
		<pose>Unspecifiedpose>
		<truncated>0truncated>
		<difficult>0difficult>
		<bndbox>
			<xmin>533xmin>
			<ymin>233ymin>
			<xmax>571xmax>
			<ymax>256ymax>
		bndbox>
	object>
	<object>
		<name>breakname>
		<pose>Unspecifiedpose>
		<truncated>0truncated>
		<difficult>0difficult>
		<bndbox>
			<xmin>540xmin>
			<ymin>106ymin>
			<xmax>578xmax>
			<ymax>128ymax>
		bndbox>
	object>
annotation>

只需要在代码中修改xml_path和update_class,其中update_class 为希望修改成的类别名称。

import xml.dom.minidom
import os


def change_xml(xml_path, update_content):
    xml_files = os.listdir(xml_path)

    for xml_file in xml_files:
        dom = xml.dom.minidom.parse(os.path.join(xml_path, xml_file))  
        root = dom.documentElement  
        names = root.getElementsByTagName('name')

        for name in names:
            name.firstChild.data = update_content
        with open(os.path.join(xml_path, xml_file), 'w', encoding='utf-8') as fh:
            dom.writexml(fh)


if __name__ == '__main__':
    # 欲修改文件
    xml_path = "D:/test/anchor_xml/xml/"
    # 修改的class类别
    update_class = 'normal'
    change_xml(xml_path, update_class)

运行结果如下:

<annotation>
	<folder>imgfolder>
	<filename>20230426094013112_0.bmpfilename>
	<path>D:\test\anchor_xml\img\20230426094013112_0.bmppath>
	<source>
		<database>Unknowndatabase>
	source>
	<size>
		<width>1024width>
		<height>512height>
		<depth>3depth>
	size>
	<segmented>0segmented>
	<object>
		<name>normalname>
		<pose>Unspecifiedpose>
		<truncated>0truncated>
		<difficult>0difficult>
		<bndbox>
			<xmin>533xmin>
			<ymin>233ymin>
			<xmax>571xmax>
			<ymax>256ymax>
		bndbox>
	object>
	<object>
		<name>normalname>
		<pose>Unspecifiedpose>
		<truncated>0truncated>
		<difficult>0difficult>
		<bndbox>
			<xmin>540xmin>
			<ymin>106ymin>
			<xmax>578xmax>
			<ymax>128ymax>
		bndbox>
	object>
annotation>

你可能感兴趣的:(深度学习,YOLO,xml,python)