YOLOv5 数据集划分及生成labels

0.本人文件夹存放格式

(因为要测试多个数据集和不同的yolov5版本和其他算法,所以数据集整体放到外面)

 YOLOv5 数据集划分及生成labels_第1张图片                                                    YOLOv5 数据集划分及生成labels_第2张图片

 1.划分数据集 验证集 测试集

# -*- coding:utf-8 -*
import os
import random

val_percent = 0.2
test_percent = 0.2
train_percent = 0.8
xmlfilepath = 'Annotations'
txtsavepath = 'Images'
total_xml = os.listdir(xmlfilepath)

num = len(total_xml)  #统计所有的标注文件
list = range(num)
tr = int(num * train_percent )  # 设置训练和验证集的数目
tv = int(num * train_percent * val_percent)      # 设置训练集的数目
te = int(num * test_percent)
trainval = random.sample(list, tr)
val = random.sample(trainval, tv)

# txt 文件写入的只是xml 文件的文件名(数字),没有后缀,如下图。
ftrainval = open('ImageSets\\trainval.txt', 'w')
ftest = open('ImageSets\\test.txt', 'w')
ftrain = open('ImageSets\\train.txt', 'w')
fval = open('ImageSets\\val.txt', 'w')

for i in list:
    print(i)
    name = total_xml[i][:-4] + '\n'
    if i in trainval:
        print(i)
        ftrainval.write(name)
        if i in val:
            fval.write(name)
        else:
            ftrain.write(name)
    else:
        ftest.write(name)

ftrainval.close()
ftrain.close()
fval.close()
ftest.close()

2.生成labels标签 同时也把图片归一化 

# -*- coding:utf-8 -*
import xml.etree.ElementTree as ET
import pickle
import os
from os import listdir, getcwd
from os.path import join

sets = ['train', 'test', 'val']
classes = ['person', 'bicycle', 'car', 'motorbike', 'bus']


def convert(size, box):
    dw = 1. / size[0]
    dh = 1. / size[1]
    x = (box[0] + box[1]) / 2.0
    y = (box[2] + box[3]) / 2.0
    w = box[1] - box[0]
    h = box[3] - box[2]
    x = x * dw
    w = w * dw
    y = y * dh
    h = h * dh
    return (x, y, w, h)


def convert_annotation(image_id):
    in_file = open('Annotations/%s.xml' % (image_id))
    out_file = open('labels/%s.txt' % (image_id), 'w')
    tree = ET.parse(in_file)
    root = tree.getroot()
    size = root.find('size')
    w = int(size.find('width').text)
    h = int(size.find('height').text)

    for obj in root.iter('object'):
        difficult = obj.find('difficult').text
        cls = obj.find('name').text
        cls = cls.lower();
        if cls == "people":
            cls ="person"
        elif cls == "table":
            cls = "diningtable"
        if cls not in classes or int(difficult) == 1:
            continue
        cls_id = classes.index(cls)
        xmlbox = obj.find('bndbox')
        b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text),
             float(xmlbox.find('ymax').text))
        bb = convert((w, h), b)
        out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')


wd = getcwd()
print(wd)
for image_set in sets:
    if not os.path.exists('labels/'):
        os.makedirs('labels/')
    image_ids = open(
        'ImageSets/%s.txt' % (image_set)).read().strip().split()
    list_file = open('%s.txt' % (image_set), 'w')
    for image_id in image_ids:
        list_file.write('F:\\xiaolunwen2\\datasets\\dataset_vosunny\\images\\%s.jpg\n' % (image_id))
        convert_annotation(image_id)
        print(image_id)
    list_file.close()

你可能感兴趣的:(python,开发语言)