将YOLO数据集按比例划分为测试集、训练集

# 将图片和标注数据按比例切分为 训练集和测试集
import shutil
import random
import os

# 原始路径
image_original_path = "E:/A/yolov8-tree/dataset/massif/PNG/"  #放置全部图像
label_original_path = "E:/A/yolov8-tree/dataset/massif/TXT/"   #放置全部标签

cur_path = os.getcwd()

# 训练集路径
train_image_path = os.path.join(cur_path, "E:/A/yolov8-tree/dataset/massif/images/train/")
train_label_path = os.path.join(cur_path, "E:/A/yolov8-tree/dataset/massif/labels/train/")

# 验证集路径
val_image_path = os.path.join(cur_path, "E:/A/yolov8-tree/dataset/massif/images/val/")
val_label_path = os.path.join(cur_path, "E:/A/yolov8-tree/dataset/massif/labels/val/")

# 测试集路径
test_image_path = os.path.join(cur_path, "E:/A/yolov8-tree/dataset/massif/images/test/")
test_label_path = os.path.join(cur_path, "E:/A/yolov8-tree/dataset/massif/labels/test/")

# 训练集目录
list_train = os.path.join(cur_path, "E:/A/yolov8-tree/dataset/massif/train.txt")
list_val = os.path.join(cur_path, "E:/A/yolov8-tree/dataset/massif/val.txt")
list_test = os.path.join(cur_path, "E:/A/yolov8-tree/dataset/massif/test.txt")

# 三种训练集的比例
train_percent = 0.7
val_percent = 0.1
test_percent = 0.2


def del_file(path):
    for i in os.listdir(path):
        file_data = path + "\\" + i
        os.remove(file_data)


def mkdir():
    if not os.path.exists(train_image_path):
        os.makedirs(train_image_path)
    else:
        del_file(train_image_path)
    if not os.path.exists(train_label_path):
        os.makedirs(train_label_path)
    else:
        del_file(train_label_path)

    if not os.path.exists(val_image_path):
        os.makedirs(val_image_path)
    else:
        del_file(val_image_path)
    if not os.path.exists(val_label_path):
        os.makedirs(val_label_path)
    else:
        del_file(val_label_path)

    if not os.path.exists(test_image_path):
        os.makedirs(test_image_path)
    else:
        del_file(test_image_path)
    if not os.path.exists(test_label_path):
        os.makedirs(test_label_path)
    else:
        del_file(test_label_path)


def clearfile():
    if os.path.exists(list_train):
        os.remove(list_train)
    if os.path.exists(list_val):
        os.remove(list_val)
    if os.path.exists(list_test):
        os.remove(list_test)


def main():
    mkdir()
    clearfile()

    file_train = open(list_train, 'w')
    file_val = open(list_val, 'w')
    file_test = open(list_test, 'w')

    total_txt = os.listdir(label_original_path)
    num_txt = len(total_txt)
    list_all_txt = range(num_txt)

    num_train = int(num_txt * train_percent)
    num_val = int(num_txt * val_percent)
    num_test = num_txt - num_train - num_val

    train = random.sample(list_all_txt, num_train)
    # train从list_all_txt取出num_train个元素
    # 所以list_all_txt列表只剩下了这些元素
    val_test = [i for i in list_all_txt if not i in train]
    # 再从val_test取出num_val个元素,val_test剩下的元素就是test
    val = random.sample(val_test, num_val)

    print("训练集数目:{}, 验证集数目:{}, 测试集数目:{}".format(len(train), len(val), len(val_test) - len(val)))
    for i in list_all_txt:
        name = total_txt[i][:-4]

        srcImage = image_original_path + name + '.png'# 依据实际图片格式将其更改为对应格式,如.jpg .bmp 等
        srcLabel = label_original_path + name + ".txt"

        if i in train:
            dst_train_Image = train_image_path + name + '.png'# 依据实际图片格式将其更改为对应格式,如.jpg .bmp 等
            dst_train_Label = train_label_path + name + '.txt'
            shutil.copyfile(srcImage, dst_train_Image)
            shutil.copyfile(srcLabel, dst_train_Label)
            file_train.write(dst_train_Image + '\n')
        elif i in val:
            dst_val_Image = val_image_path + name + '.png'# 依据实际图片格式将其更改为对应格式,如.jpg .bmp 等
            dst_val_Label = val_label_path + name + '.txt'
            shutil.copyfile(srcImage, dst_val_Image)
            shutil.copyfile(srcLabel, dst_val_Label)
            file_val.write(dst_val_Image + '\n')
        else:
            dst_test_Image = test_image_path + name + '.png'# 依据实际图片格式将其更改为对应格式,如.jpg .bmp 等
            dst_test_Label = test_label_path + name + '.txt'
            shutil.copyfile(srcImage, dst_test_Image)
            shutil.copyfile(srcLabel, dst_test_Label)
            file_test.write(dst_test_Image + '\n')

    file_train.close()
    file_val.close()
    file_test.close()


if __name__ == "__main__":
    main()

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
rsod数据集XML转换为yolo格式的过程主要是为了适应YOLO(You Only Look Once)对象检测模型的训练格式。YOLO模型通常需要输入数据的标注格式为文本文件,每行包含信息:类索引、中心点坐标、宽和高。而rsod数据集中的标注文件可能是XML格式,这种格式通常包含图像信息和每个目标的详细标注信息,包括边界框的位置、大小以及类别等。 转换过程大体可以分为以下步骤: 1. 读取XML文件:遍历数据集中的每个图像文件对应的XML标注文件,解析其中的信息。 2. 提取标注信息:从XML文件中提取出每个目标的类别、边界框的位置和尺寸。 3. 转换为YOLO格式:将提取的边界框信息转换为YOLO格式,即将边框坐标转换为相对于图像尺寸的比例值(中心点坐标以及宽高),并且计算每个目标的类别索引。 4. 写入到TXT文件:将转换后的信息写入到以图像名称命名的文本文件中,格式通常为:`<class> <x_center> <y_center> <width> <height>`,每个对象占一行。 5. 划分训练和测试集:根据需求将数据集随机分配为训练集测试集。这可以通过编写脚本实现,随机选择一定比例的图像分配到测试集中,剩余的图像则作为训练集。 以下是一个简单的Python代码示例来展示上述步骤: ```python import os import glob import xml.etree.ElementTree as ET from sklearn.model_selection import train_test_split # 假设data_path是XML文件所在的文件夹路径 data_path = '/path/to/rsod/xml/files' txt_save_path = '/path/to/save/yolo/files' # 获取所有的.xml文件 xml_files = glob.glob(os.path.join(data_path, '*.xml')) # 用于存储图像名称和对应标注信息 images = [] annotations = [] for xml_file in xml_files: tree = ET.parse(xml_file) root = tree.getroot() image_name = os.path.basename(root.find('filename').text) image_width = int(root.find('size/width').text) image_height = int(root.find('size/height').text) for member in root.findall('object'): class_id = member[0].text xmin = member[4][0].text ymin = member[4][1].text xmax = member[4][2].text ymax = member[4][3].text # 转换边界框坐标到YOLO格式 x_center = ((float(xmin) + float(xmax)) / 2) / image_width y_center = ((float(ymin) + float(ymax)) / 2) / image_height width = (float(xmax) - float(xmin)) / image_width height = (float(ymax) - float(ymin)) / image_height # 添加到标注信息列表中 annotations.append(f"{class_id} {x_center} {y_center} {width} {height}") # 记录图像名称 images.append(image_name) # 分割训练集测试集 train_images, test_images, train_annotations, test_annotations = train_test_split(images, annotations, test_size=0.2) # 保存YOLO格式的训练集测试集标注文件 for image, annotation in zip(train_images, train_annotations): with open(os.path.join(txt_save_path, f"{image.split('.')[0]}.txt"), 'w') as file: file.write(annotation) for image, annotation in zip(test_images, test_annotations): with open(os.path.join(txt_save_path, f"{image.split('.')[0]}_test.txt"), 'w') as file: file.write(annotation) ``` 请根据实际情况调整上述代码中的路径和其他参数。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值