import os from PIL import Image # 把下面的root_dir路径改成数据集的路径即可 root_dir = "VisDrone2019-DET-val/" annotations_dir = root_dir + "annotations/" image_dir = root_dir + "images/" xml_dir = root_dir + "Annotations_XML/" # 在工作目录下创建Annotations_XML文件夹保存xml文件 # 0-11 共12类 # 下面的类别换成数据类别,也可适用于其他的数据集转换 # 适用于coco128 class_name = ['ignored regions', 'pedestrian', 'people', 'bicycle', 'car', 'van', 'truck', 'tricycle', 'awning-tricycle', 'bus', 'motor', 'others'] for filename in os.listdir(annotations_dir): fin = open(annotations_dir + filename, 'r') image_name = filename.split('.')[0] img = Image.open(image_dir + image_name + ".jpg") # 若图像数据是“png”转换成“.png”即可 xml_name = xml_dir + image_name + '.xml' with open(xml_name, 'w') as fout: fout.write('' + '\n') fout.write('\t' + 'VOC2007' + '\n') fout.write('\t' + '' + image_name + '.jpg' + '' + '\n') fout.write('\t' + '' + '\n') fout.write('\t\t' + '' + 'VisDrone2019-DET' + '' + '\n') fout.write('\t\t' + '' + 'VisDrone2019-DET' + '' + '\n') fout.write('\t\t' + '' + 'flickr' + '' + '\n') fout.write('\t\t' + '' + 'Unspecified' + '' + '\n') fout.write('\t' + '' + '\n') fout.write('\t' + '' + '\n') fout.write('\t\t' + '' + 'LJ' + '' + '\n') fout.write('\t\t' + '' + 'LJ' + '' + '\n') fout.write('\t' + '' + '\n') fout.write('\t' + '' + '\n') fout.write('\t\t' + '' + str(img.size[0]) + '' + '\n') fout.write('\t\t' + '' + str(img.size[1]) + '' + '\n') fout.write('\t\t' + '' + '3' + '' + '\n') fout.write('\t' + '' + '\n') fout.write('\t' + '' + '0' + '' + '\n') for line in fin.readlines(): line = line.split(',') fout.write('\t' + '' + '\n') fout.write('\t\t' + '' + class_name[int(line[5])] + '' + '\n') fout.write('\t\t' + '' + 'Unspecified' + '' + '\n') fout.write('\t\t' + '' + line[6] + '' + '\n') fout.write('\t\t' + '' + str(int(line[7])) + '' + '\n') fout.write('\t\t' + '' + '\n') fout.write('\t\t\t' + '' + line[0] + '' + '\n') fout.write('\t\t\t' + '' + line[1] + '' + '\n') # pay attention to this point!(0-based) fout.write('\t\t\t' + '' + str(int(line[0]) + int(line[2]) - 1) + '' + '\n') fout.write('\t\t\t' + '' + str(int(line[1]) + int(line[3]) - 1) + '' + '\n') fout.write('\t\t' + '' + '\n') fout.write('\t' + '' + '\n') fin.close() fout.write('')