数据标注:YOLO模式到PascalVOC模式的一键转换

import os, sys
import glob
from PIL import Image

def txtLabel_to_xmlLabel(source_pth,save_xml_pth):
    if not os.path.exists(save_xml_pth):
        os.makedirs(save_xml_pth)
    classes = open(classes_file).read().splitlines()
    print(classes)
    for file in os.listdir(source_pth):
        if not file.endswith('.jpg'):
            continue
        img_file = Image.open(os.path.join(source_pth,file))
        txt_file = open(os.path.join(source_pth,file.replace('.jpg','.txt'))).read().splitlines()
        print(txt_file)
        xml_file = open(os.path.join(save_xml_pth,file.replace('.jpg','.xml')), 'w')
        width, height = img_file.size
        xml_file.write('\n')
        xml_file.write('\tsimple\n')
        xml_file.write('\t' + str(file) + '\n')
        xml_file.write('\t\n')
        xml_file.write('\t\t' + str(width) + ' \n')
        xml_file.write('\t\t' + str(height) + '\n')
        xml_file.write('\t\t' + str(3) + '\n')
        xml_file.write('\t\n')

        for line in txt_file:
            print(line)
            line_split = line.split(' ')
            x_center = float(line_split[1])
            y_center = float(line_split[2])
            w = float(line_split[3])
            h = float(line_split[4])
            xmax = int((2*x_center*width + w*width)/2)
            xmin = int((2*x_center*width - w*width)/2)
            ymax = int((2*y_center*height + h*height)/2)
            ymin = int((2*y_center*height - h*height)/2)

            xml_file.write('\t\n')
            xml_file.write('\t\t'+ str(classes[int(line_split[0])]) +'\n')
            xml_file.write('\t\tUnspecified\n')
            xml_file.write('\t\t0\n')
            xml_file.write('\t\t0\n')
            xml_file.write('\t\t\n')
            xml_file.write('\t\t\t' + str(xmin) + '\n')
            xml_file.write('\t\t\t' + str(ymin) + '\n')
            xml_file.write('\t\t\t' + str(xmax) + '\n')
            xml_file.write('\t\t\t' + str(ymax) + '\n')
            xml_file.write('\t\t\n')
            xml_file.write('\t\n')
        xml_file.write('')

if __name__ == '__main__':
    classes_file = r"D:\CV_Data\Region\GZ5Region\classes.txt"
    txtLabel_to_xmlLabel(r'D:\CV_Data\Region\GZ5Region\SZ_GZ_CV_region',r'D:\CV_Data\Region\GZ5Region\SZ_GZ_CV_region_xml')





 

你可能感兴趣的:(PyTorch,图像处理,python)