批量修改LabelImg生成的xml文件
xml文件是由LabelImg标注生成的文件,但有时需要对xml文件内容进行修改,本文提供以下思路:
xml格式
下面是由LabelImg标注生成文件的具体内容,这里对filename和path进行修改
<annotation>
<folder>Defect</folder>
<filename>Image_0000.bmp</filename>
<path>C:\Users\13357\Desktop\Pictures\Pictures\Defect\Image_0000.bmp</path>
<source>
<database>Unknown</database>
</source>
<size>
<width>2592</width>
<height>1944</height>
<depth>3</depth>
</size>
<segmented>0</segmented>
<object>
<name>defect</name>
<pose>Unspecified</pose>
<truncated>0</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>2086</xmin>
<ymin>300</ymin>
<xmax>2166</xmax>
<ymax>376</ymax>
</bndbox>
</object>
<object>
<name>defect</name>
<pose>Unspecified</pose>
<truncated>0</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>1997</xmin>
<ymin>690</ymin>
<xmax>2043</xmax>
<ymax>1015</ymax>
</bndbox>
</object>
<object>
<name>defect</name>
<pose>Unspecified</pose>
<truncated>0</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>2051</xmin>
<ymin>729</ymin>
<xmax>2096</xmax>
<ymax>1039</ymax>
</bndbox>
</object>
<object>
<name>case</name>
<pose>Unspecified</pose>
<truncated>0</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>1897</xmin>
<ymin>188</ymin>
<xmax>2317</xmax>
<ymax>1619</ymax>
</bndbox>
</object>
</annotation>
实现代码
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!')