YOLO转VOC格式,解决txt多于jpg问题

当数据集中标注的txt少于jpg时,转换代码就会报错,一个一个找出多余图片很麻烦,因此对代码进行修改解决这个问题

 

import os
import glob
from PIL import Image

voc_annotations = 'C:/Users/XX/YOLOtoVOC/dataset/annotations/'
yolo_txt = 'C:/Users/XX/YOLOtoVOC/dataset/YOLO/'
img_path = 'C:/Users/XX/YOLOtoVOC/dataset/JPEGImages/'
labels = ['A', 'B', 'C']  # label for datasets
# 图像存储位置
src_img_dir = img_path  # 添加你的路径
# 图像的txt文件存放位置


src_txt_dir = yolo_txt
src_xml_dir = voc_annotations

img_Lists = glob.glob(src_img_dir + '/*.jpg')

img_basenames = []
for item in img_Lists:
    img_basenames.append(os.path.basename(item))

img_names = []
for item in img_basenames:
    temp1, temp2 = os.path.splitext(item)
    img_names.append(temp1)

for img in img_names:
    im = Image.open((src_img_dir + '/' + img + '.jpg'))
    width, height = im.size

    # 打开txt文件
    try:
        gt = open(src_txt_dir + '/' + img + '.txt').read().splitlines()
        print(gt)
        if gt:
            # 将主干部分写入xml文件中
            xml_file = open((src_xml_dir + '/' + img + '.xml'), 'w')
            xml_file.write('\n')
            xml_file.write('    VOC2007\n')
            xml_file.write('    ' + str(img) + '.jpg' + '\n')
            xml_file.write('    \n')
            xml_file.write('        ' + str(width) + '\n')
            xml_file.write('        ' + str(height) + '\n')
            xml_file.write('        3\n')
            xml_file.write('    \n')

            # write the region of image on xml file
            for img_each_label in gt:
                spt = img_each_label.split(' ')  # 这里如果txt里面是以逗号‘,’隔开的,那么就改为spt = img_each_label.split(',')。
                print(f'spt:{spt}')
                xml_file.write('    \n')
                xml_file.write('        ' + str(labels[int(spt[0])]) + '\n')
                xml_file.write('        Unspecified\n')
                xml_file.write('        0\n')
                xml_file.write('        0\n')
                xml_file.write('        \n')

                center_x = round(float(spt[1].strip()) * width)
                center_y = round(float(spt[2].strip()) * height)
                bbox_width = round(float(spt[3].strip()) * width)
                bbox_height = round(float(spt[4].strip()) * height)
                xmin = str(int(center_x - bbox_width / 2))
                ymin = str(int(center_y - bbox_height / 2))
                xmax = str(int(center_x + bbox_width / 2))
                ymax = str(int(center_y + bbox_height / 2))

                xml_file.write('            ' + xmin + '\n')
                xml_file.write('            ' + ymin + '\n')
                xml_file.write('            ' + xmax + '\n')
                xml_file.write('            ' + ymax + '\n')
                xml_file.write('        \n')
                xml_file.write('    \n')

            xml_file.write('')
    except(FileNotFoundError):
        im.close()
        os.remove(str(src_img_dir + '/' + img + '.jpg'))#删除多余图片

        



你可能感兴趣的:(YOLO,人工智能,计算机视觉)