批量修改LabelImg生成的xml文件

批量修改LabelImg生成的xml文件

xml文件是由LabelImg标注生成的文件,但有时需要对xml文件内容进行修改,本文提供以下思路:

xml格式

下面是由LabelImg标注生成文件的具体内容,这里对filename和path进行修改


	Defect
	Image_0000.bmp
	C:\Users\13357\Desktop\Pictures\Pictures\Defect\Image_0000.bmp
	
		Unknown
	
	
		2592
		1944
		3
	
	0
	
		defect
		Unspecified
		0
		0
		
			2086
			300
			2166
			376
		
	
	
		defect
		Unspecified
		0
		0
		
			1997
			690
			2043
			1015
		
	
	
		defect
		Unspecified
		0
		0
		
			2051
			729
			2096
			1039
		
	
	
		case
		Unspecified
		0
		0
		
			1897
			188
			2317
			1619
		
	


实现代码

import os
import xml.dom.minidom

path = 'Datasets/Test_of_xml_rectify/xmls'
files = os.listdir(path)

s = []
num = 0
i = 0
j = 0

for xmlFile in files:
    if not os.path.isdir(xmlFile):
        print(xmlFile)
    if xmlFile.endswith('.xml'):
        dom = xml.dom.minidom.parse(os.path.join(path, xmlFile))
        root = dom.documentElement
        xml_name = root.getElementsByTagName('filename')
        xml_path = root.getElementsByTagName('path')

        for i in range(len(xml_name)):
            print(xml_name[i].firstChild.data)
            if num < 10:
                xml_name[i].firstChild.data = '00000000000' + str(num) + '.bmp'
            elif 10 <= num < 100:
                xml_name[i].firstChild.data = '0000000000' + str(num) + '.bmp'
            else:
                xml_name[i].firstChild.data = '000000000' + str(num) + '.bmp'
            print(xml_name[i].firstChild.data)

        for j in range(len(xml_path)):
            print(xml_name[j].firstChild.data)
            if num < 10:
                xml_path[j].firstChild.data = './coco/2017/annotations/xml/' + '00000000000' + str(num) + '.bmp'
            elif 10 <= num < 100:
                xml_path[j].firstChild.data = './coco/2017/annotations/xml/' + '0000000000' + str(num) + '.bmp'
            else:
                xml_path[j].firstChild.data = './coco/2017/annotations/xml/' + '0000000000' + str(num) + '.bmp'
            print(xml_path[j].firstChild.data)
            num += 1

        with open(os.path.join(path, xmlFile), 'w') as fh:
            dom.writexml(fh)
            print('写入filename/path OK!')

你可能感兴趣的:(python,xml)