Modify the name of the object in the marked xml file

The name was typed incorrectly when labeling with labelImg. The code is written here and collectively modified. The
original xml file is as follows

<annotation>
	<folder>JPEGImages</folder>   从这里开始数为0
	<filename>20200507201335.jpg</filename>  从这里开始数为1
	<path>K:\JPEGImages\20200507201335.jpg</path> 从这里开始数为2
	<source>    从这里开始数为3
		<database>Unknown</database>
	</source>
	<size>   从这里开始数为4
		<width>640</width>
		<height>360</height>
		<depth>3</depth>
	</size>
	<segmented>0</segmented>  从这里开始数为5
	<object>  从这里开始数为6
		<name>qingliangyou</name>
		<pose>Unspecified</pose>
		<truncated>0</truncated>
		<difficult>0</difficult>
		<bndbox>
			<xmin>283</xmin>
			<ymin>147</ymin>
			<xmax>306</xmax>
			<ymax>170</ymax>
		</bndbox>
	</object>
	<object>   从这里开始数为7
		<name>three</name>
		<pose>Unspecified</pose>
		<truncated>0</truncated>
		<difficult>0</difficult>
		<bndbox>
			<xmin>459</xmin>
			<ymin>68</ymin>
			<xmax>522</xmax>
			<ymax>152</ymax>
		</bndbox>
	</object>
	<object>  从这里开始数为8
		<name>olderchuia</name>
		<pose>Unspecified</pose>
		<truncated>0</truncated>
		<difficult>0</difficult>
		<bndbox>
			<xmin>408</xmin>
			<ymin>270</ymin>
			<xmax>506</xmax>
			<ymax>350</ymax>
		</bndbox>
	</object>
</annotation>

The problem now is that I typed olderchuia a more, and
modified the code as follows. By the way, some xml files do not have root[8][0], so I used a try

import xml.etree.ElementTree as ET
import os
import os.path as osp

def get_dir(devkit_dir,  type):
    return osp.join(devkit_dir, type)

def change_xml(xml_path):
    filelist = os.listdir(xml_path)
    #print(filelist)
    # 打开xml文档
    for xmlfile in filelist:

        try:
            doc = ET.parse(get_dir(xml_path, xmlfile))
            root = doc.getroot()
            root[8][0].text = "olderchui"
            doc.write(get_dir(xml_path, xmlfile))  # 保存修改
            print(root[8][0].text)
        except IndexError:
            pass
        continue
       


change_xml('K:/z_paddle detection5.27/dataset/fruit/Annotations')

Guess you like

Origin blog.csdn.net/weixin_43134049/article/details/106462218