Python YOLO目标检测划分数据集(训练集、验证集、测试集)

划分模版

百度网盘链接:https://pan.baidu.com/s/11hop3cJhdri_QSQJc19ReQ 
提取码:cnif

代码如下

import xml.etree.ElementTree as ET
import pickle
import os
from os import listdir, getcwd
from os.path import join
import random
from shutil import copyfile

classes = ["one_day"]
# classes=["ball",“people”]

TRAIN_RATIO = 80  # 训练集占 10分之8
VALID_RATIO = 10  # 验证集占 10分之1
TEST_RATIO = 10  # 测试集占 10分之1


def clear_hidden_files(path):  # 清理隐藏的文件
    dir_list = os.listdir(path)  # 以列表的形式获取目录中的文件
    for i in dir_list:
        abspath = os.path.join(os.path.abspath(path), i)  # 获取当前文件的绝对位置并与文件拼接
        if os.path.isfile(abspath):  # 判断是否为一个文件
            if i.startswith("._"):  # 判断字符串是否以指定字符串开始
                os.remove(abspath)  # 删除文件
        else:
            clear_hidden_files(abspath)  # 闭环执行,直到目录中所有的指定文件删除


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):  # 转换xml文件
    in_file = open('datasets/Sum/Annotations/%s.xml' % image_id)  # 打开xml文件的目录
    out_file = open('datasets/Sum/YOLOLabels/%s.txt' % image_id, 'w')  # 创建一个存放txt文件的目录
    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
        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')
    in_file.close()
    out_file.close()


wd = os.getcwd()  # 获取当前python文件的目录
print(wd)
data_base_dir = os.path.join(wd, "datasets/")  # 拼接文件目录
if not os.path.isdir(data_base_dir):  # 判断是否为一个文件目录
    os.mkdir(data_base_dir)  # 否则就创建一个目录

work_sapce_dir = os.path.join(data_base_dir, "Sum/")  # 拼接文件目录
if not os.path.isdir(work_sapce_dir):
    os.mkdir(work_sapce_dir)

annotation_dir = os.path.join(work_sapce_dir, "Annotations/")  # 拼接文件目录
if not os.path.isdir(annotation_dir):
    os.mkdir(annotation_dir)
clear_hidden_files(annotation_dir)  # 清理隐藏的文件

image_dir = os.path.join(work_sapce_dir, "JPGImages/")  # 拼接文件目录
if not os.path.isdir(image_dir):
    os.mkdir(image_dir)
clear_hidden_files(image_dir)  # 清理隐藏的文件

yolo_labels_dir = os.path.join(work_sapce_dir, "YOLOLabels/")  # 拼接文件目录
if not os.path.isdir(yolo_labels_dir):
    os.mkdir(yolo_labels_dir)
clear_hidden_files(yolo_labels_dir)  # 清理隐藏的文件

yolov8_train_dir = os.path.join(data_base_dir, "train/")  # 训练集文件夹 1
if not os.path.isdir(yolov8_train_dir):
    os.mkdir(yolov8_train_dir)
clear_hidden_files(yolov8_train_dir)

yolov8_valid_dir = os.path.join(data_base_dir, "valid/")  # 拼接文件目录 -1
if not os.path.isdir(yolov8_valid_dir):
    os.mkdir(yolov8_valid_dir)
clear_hidden_files(yolov8_valid_dir)

yolov8_test_dir = os.path.join(data_base_dir, "test/")
if not os.path.isdir(yolov8_test_dir):
    os.mkdir(yolov8_test_dir)
clear_hidden_files(yolov8_test_dir)


yolov8_train_images_dir = os.path.join(yolov8_train_dir, "images/")  # 训练集 2
if not os.path.isdir(yolov8_train_images_dir):
    os.mkdir(yolov8_train_images_dir)
for filename in os.listdir(yolov8_train_images_dir):
    file_path = os.path.join(yolov8_train_images_dir, filename)
    if os.path.isfile(file_path):
        os.remove(file_path)
clear_hidden_files(yolov8_train_images_dir)

yolov8_train_labels_dir = os.path.join(yolov8_train_dir, "labels/")  # 训练集 3
if not os.path.isdir(yolov8_train_labels_dir):
    os.mkdir(yolov8_train_labels_dir)
for filename in os.listdir(yolov8_train_labels_dir):
    file_path = os.path.join(yolov8_train_labels_dir, filename)
    if os.path.isfile(file_path):
        os.remove(file_path)
clear_hidden_files(yolov8_train_labels_dir)

yolov8_valid_images_dir = os.path.join(yolov8_valid_dir, "images/")  # 验证集 -2
if not os.path.isdir(yolov8_valid_images_dir):
    os.mkdir(yolov8_valid_images_dir)
for filename in os.listdir(yolov8_valid_images_dir):
    file_path = os.path.join(yolov8_valid_images_dir, filename)
    if os.path.isfile(file_path):
        os.remove(file_path)
clear_hidden_files(yolov8_valid_images_dir)

yolov8_valid_labels_dir = os.path.join(yolov8_valid_dir, "labels/")  # 验证集 -3
if not os.path.isdir(yolov8_valid_labels_dir):
    os.mkdir(yolov8_valid_labels_dir)
for filename in os.listdir(yolov8_valid_labels_dir):
    file_path = os.path.join(yolov8_valid_labels_dir, filename)
    if os.path.isfile(file_path):
        os.remove(file_path)
clear_hidden_files(yolov8_valid_labels_dir)

yolov8_test_images_dir = os.path.join(yolov8_test_dir, "images/")
if not os.path.isdir(yolov8_test_images_dir):
    os.mkdir(yolov8_test_images_dir)
for filename in os.listdir(yolov8_test_images_dir):
    file_path = os.path.join(yolov8_test_images_dir, filename)
    if os.path.isfile(file_path):
        os.remove(file_path)
clear_hidden_files(yolov8_test_images_dir)

yolov8_test_labels_dir = os.path.join(yolov8_test_dir, "labels/")
if not os.path.isdir(yolov8_test_labels_dir):
    os.mkdir(yolov8_test_labels_dir)
for filename in os.listdir(yolov8_test_labels_dir):
    file_path = os.path.join(yolov8_test_labels_dir, filename)
    if os.path.isfile(file_path):
        os.remove(file_path)
clear_hidden_files(yolov8_test_labels_dir)

train_file = open(os.path.join(wd, "yolov8_train.txt"), 'w')  # 创建一个拼接好的训练集路径日记
val_file = open(os.path.join(wd, "yolov8_valid.txt"), 'w')  # 创建一个拼接好的验证集路径日记
test_file = open(os.path.join(wd, "yolov8_test.txt"), 'w')
train_file.close()
val_file.close()
test_file.close()
train_file = open(os.path.join(wd, "yolov8_train.txt"), 'a')  # 使文件可追加
val_file = open(os.path.join(wd, "yolov8_valid.txt"), 'a')  # 使文件可追加
test_file = open(os.path.join(wd, "yolov8_test.txt"), 'a')

list_imgs = os.listdir(image_dir)  # 以列表的形式获取目录中的文件
prob = random.randint(1, 100)
print("Probability: %d" % prob)
for i in range(0, len(list_imgs)):
    path = os.path.join(image_dir, list_imgs[i])  # 指定每一个图片的路径
    if os.path.isfile(path):  # 判断是否为一个文件
        image_path = image_dir + list_imgs[i]  # 每一个图片的绝对路径名
        voc_path = list_imgs[i]  # 每一个图片路径名
        (nameWithoutExtention, extention) = os.path.splitext(os.path.basename(image_path))  # 返回每一个图片路径最后一级的文件名与后缀组成的元组
        (voc_nameWithoutExtention, voc_extention) = os.path.splitext(os.path.basename(voc_path))
        annotation_name = nameWithoutExtention + '.xml'  # 每一个xml文件的绝对路径名
        annotation_path = os.path.join(annotation_dir, annotation_name)  # 指定Annotations中每一个xml文件
        label_name = nameWithoutExtention + '.txt'
        label_path = os.path.join(yolo_labels_dir, label_name)  # 指定YOLOLabels中的每一个txt文件
    prob = random.randint(1, 100)
    print("Probability: %d" % prob)

    if (prob < TRAIN_RATIO):  # 训练集
        if os.path.exists(annotation_path):  # 判断一个路径是否存在
            train_file.write(image_path + '\n')  # 把图片路径写进日记中
            convert_annotation(nameWithoutExtention)  # 转换数据
            copyfile(image_path, yolov8_train_images_dir + voc_path)  # 把JPGImages中对应的图片复制到images_train文件夹中
            copyfile(label_path, yolov8_train_labels_dir + label_name)  # 把YOLOLabels中对应的txt文件复制到labels_train文件夹中
    elif (prob > TRAIN_RATIO and prob < TRAIN_RATIO+VALID_RATIO):  # 验证集
        if os.path.exists(annotation_path):
            val_file.write(image_path + '\n')
            convert_annotation(nameWithoutExtention)  # 转换数据
            copyfile(image_path, yolov8_valid_images_dir + voc_path)
            copyfile(label_path, yolov8_valid_labels_dir + label_name)
    else:
        if os.path.exists(annotation_path):
            test_file.write(image_path + '\n')
            convert_annotation(nameWithoutExtention)
            copyfile(image_path, yolov8_test_images_dir + voc_path)
            copyfile(label_path, yolov8_test_labels_dir + label_name)

train_file.close()
val_file.close()
test_file.close()

  • 8
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值