替换VOC数据集格式中的标签信息
说明:在用yolo训练自己的数据集时候,标注的voc格式的数据集中有中文,导致转化成的yolo格式的txt文件有中文,训练起来一直报错的,针对这个问题,想着直接修改已经标注好的voc中的数据集标签信息,可以根据下述脚本直接修改
import os
import xml.etree.ElementTree as ET
def replace_labels(xml_file, old_labels, new_labels):
tree = ET.parse(xml_file)
root = tree.getroot()
for obj in root.findall('object'):
for label in obj.findall('name'):
if label.text in old_labels:
label.text = new_labels[old_labels.index(label.text)]
tree.write(xml_file)
def batch_replace_labels(folder_path, old_labels, new_labels):
for filename in os.listdir(folder_path):
if filename.endswith('.xml'):
xml_file = os.path.join(folder_path, filename)
replace_labels(xml_file, old_labels, new_labels)
# 使用示例
folder_path = 'D:\\data_\\xml\\xml'
# 原标签信息
old_labels = ['hat\t\t\t\u5b89\u5168\u5e3d','workclothes\t\t\u5de5\u4f5c\u670d',
'work_person\t\t\u5de5\u4f5c\u4eba\u5458','no_coal_flow\t\t\u7164\u6d41\u91cf\u65e0\u7164','cross_safe\t\t\u4eba\u5458\u7ffb\u9605',
'low_coal_flow\t\t\u7164\u6d41\u91cf\u5c11\u7164','check_person\t\t\u5de1\u68c0\u4eba\u5458',
'right_cutting\t\t\u53f3\u6eda\u7b52','bracket\t\t\t\u62a4\u5e2e\u677f','normal_coal_flow\t\u7164\u6d41\u91cf\u6b63\u5e38\u7164',]
# 替换后的标签信息
new_labels = ['hat', 'workclothes','work_person','no_coal_flow','cross_safe','low_coal_flow','check_person','right_cutting','bracket','normal_coal_flow',]
batch_replace_labels(folder_path, old_labels, new_labels)