import os
import shutil
from random import shuffle
from math import floor
# 创建 dataset 文件夹
dataset_path = 'classify/dataset'
os.makedirs(dataset_path, exist_ok=True)
# 这里填你的图片所在文件夹
main_directory = 'H:\Processor\output_del1'
for dirpath, dirnames, filenames in os.walk(main_directory):
for dirname in dirnames:
# 获取每个子文件夹中的所有 jpg 文件
folder_path = os.path.join(dirpath, dirname)
images = [img for img in os.listdir(folder_path) if img.endswith(".jpg")]
shuffle(images) # 随机打乱图片顺序
# 按8:2的比例分配训练和测试图片
split_index = floor(len(images) * 0.8)
train_images = images[:split_index]
test_images = images[split_index:]
# 在dataset文件夹下创建对应的 train 和 test 子文件夹
os.makedirs(os.path.join(dataset_path, 'train', dirname), exist_ok=True)
os.makedirs(os.path.join(dataset_path, 'test', dirname), exist_ok=True)
# 复制训练和测试图片到相应的文件夹
for img in train_images:
shutil.copy2(os.path.join(folder_path, img), os.path.join(dataset_path, 'train', dirname))
for img in test_images:
shutil.copy2(os.path.join(folder_path, img), os.path.join(dataset_path, 'test', dirname))```
划分后:

用于划分图像分类训练集,验证集的脚本
最新推荐文章于 2025-08-03 11:58:00 发布