批量修改标签
使用labelImg标注数据时,通过python批量修改已经标注的数据标签名字,例如,本程序将标注生成的xml文件中的目标名字“crack”批量修改为“scratch”,示例程序如下:
'''
通过解析xml文件,批量修改xml文件里的标签名称,比如把标签crack改成scratch
'''
import os.path
import glob
import xml.etree.ElementTree as ET
path = 'crop_images/0421label' # 存储标签的路径,修改为自己的Annotations标签路径
for xml_file in glob.glob(path + '/*.xml'):
# 返回解析树
tree = ET.parse(xml_file)
# 获取根节点
root = tree.getroot()
# 对所有目标进行解析
for member in root.findall('object'):
objectname = member.find('name').text
if objectname == 'crack': # 原来的标签名字
print(objectname)
member.find('name').text = str('scratch') # 替换的标签名字
tree.write(xml_file)
批量修改xml文件内容
# -*- coding:utf-8 -*-
# 将a替换成b
import os
xmldir = 'crop_images/0427label'
savedir = 'crop_images/0430_save'
xmllist = os.listdir(xmldir)
i = 100332
for xml in xmllist:
if '.xml' in xml:
fo = open(savedir + '/' + '{}'.format(xml), 'w', encoding='utf-8')
print('{}'.format(xml))
fi = open(xmldir + '/' + '{}'.format(xml), 'r', encoding='utf-8')
content = fi.readlines()
for line in content:
line = line.replace('<filename>{}.jpg</filename>'.format(i), '<filename>{}.jpg</filename>'.format(i-1))
line = line.replace(r'<path>D:\image_preprocessing\crop_images\0427origin_imgs\{}.jpg</path>'.format(i), r'<path>D:\image_preprocessing\crop_images\0427origin_imgs\{}.jpg</path>'.format(i-1))
fo.write(line)
i += 1
fo.close()
print('替换成功')
# 如通b为空字符串,就是删除
参考:
Python批量修改、删除、替换xml文件内容(labelimg标注)
python实现对LabelImg标注的xml文件修改其标签名字
Python批量修改、删除、替换xml文件内容(labelimg标注)