使用背景:
使用场景举例:数据集标签处理
有时候我们需要将固定格式的Excel表格文件(csv文件)转换为xml文件使用,例如我们在目标检测实验当中我们需要制作数据集Pascal VOC格式的标签文件,此时如果我们没有现成的xml标签文件,只有csv表格文件如下:
我们需要批量转换为xml特定格式文件:
转换代码:
# Excel表格数据快速批量生成xml格式文件
import csv
#输入csv文件路径
file_path = "train.csv"
with open(file_path) as csvfile:
csv_reader = csv.reader(csvfile) # 使用csv.reader遍历csvfile中的表格数据
birth_header = next(csv_reader) # 读取第一行第一列标签name
count = 0
img_pre = ''
flag = 0
for row in csv_reader: # 将csv 文件中的数据保存到birth_data中
print("正在转换csv表格数据的行数:", row)
if flag == 0:
img_pre = row[0].split('.')[0]
flag = 1
xml_file = open(('./train/' + img_pre + '.xml'), 'w')
xml_file.write('<annotation>\n')
xml_file.write(' <folder>Trash_plus</folder>\n')
xml_file.write(' <filename>' + str(img_pre) + '.jpg' + '</filename>\n')
#输入xml文件存储的目标文件夹路径
xml_file.write(' <path>' + 'D:/workplace/database/' + str(img_pre) + '.jpg' + '</path>\n')
img = row[0].split('.')[0]
if img != img_pre:
# close the file
xml_file.write('</annotation>')
xml_file.close()
# create a new file
xml_file = open(('./test/' + img + '.xml'), 'w')
xml_file.write('<annotation>\n')
xml_file.write(' <folder>Trash_plus</folder>\n')
xml_file.write(' <filename>' + str(img) + '.jpg' + '</filename>\n')
# 输入xml文件存储的目标文件夹路径
xml_file.write(' <path>' + 'D:/workplace/database/' + str(img) + '.jpg' + '</path>\n')
xml_file.write(' <source>\n')
xml_file.write(' <database>' + 'Trash_plus' + '</database>\n')
xml_file.write(' </source>\n')
xml_file.write(' <size>\n')
xml_file.write(' <width>' + str(row[1]) + '</width>\n')
xml_file.write(' <height>' + str(row[2]) + '</height>\n')
xml_file.write(' <depth>3</depth>\n')
xml_file.write(' </size>\n')
xml_file.write(' <object>\n')
xml_file.write(' <name>' + str(row[3]) + '</name>\n')
xml_file.write(' <pose>Unspecified</pose>\n')
xml_file.write(' <truncated>0</truncated>\n')
xml_file.write(' <difficult>0</difficult>\n')
xml_file.write(' <bndbox>\n')
xml_file.write(' <xmin>' + str(row[4]) + '</xmin>\n')
xml_file.write(' <ymin>' + str(row[5]) + '</ymin>\n')
xml_file.write(' <xmax>' + str(row[6]) + '</xmax>\n')
xml_file.write(' <ymax>' + str(row[7]) + '</ymax>\n')
xml_file.write(' </bndbox>\n')
xml_file.write(' </object>\n')
xml_file.write('</annotation>\n')
flag = 0
通过上述步骤就能将Excel表格数据快速批量生成xml格式文件啦
################如果觉得有用的看官麻烦点个赞支持一下哈#####################