文件夹中有很多张图片,随机取出80%张图片放在train文件中,抽取10%放在val文件中,剩下10%放到test文件中,要完成这一步python程序怎么写
时间: 2024-09-13 13:18:19 浏览: 38
在Python中,你可以使用`random`模块和一些基本的文件操作来实现这个任务。这里是一个简单的示例:
```python
import os
import random
# 假设图片目录是images_folder
image_folder = 'images_folder'
train_ratio = 0.8
val_ratio = 0.1
test_ratio = 0.1
# 检查图像文件夹是否存在
if not os.path.exists(image_folder):
print(f"Folder {image_folder} does not exist.")
else:
# 获取所有图片文件列表
all_images = [f for f in os.listdir(image_folder) if os.path.isfile(os.path.join(image_folder, f)) and f.endswith(('.jpg', '.png', '.jpeg'))]
# 计算划分比例
total_files = len(all_images)
train_count = int(train_ratio * total_files)
val_count = int(val_ratio * total_files)
# 验证总和是否合理
assert train_count + val_count + test_ratio * total_files == total_files, "Sum of ratios exceeds 1"
# 打乱图片顺序
random.shuffle(all_images)
# 分割并保存到对应的文件夹
train_path = 'train'
val_path = 'val'
test_path = 'test'
os.makedirs(train_path, exist_ok=True)
os.makedirs(val_path, exist_ok=True)
os.makedirs(test_path, exist_ok=True)
for i, img_name in enumerate(all_images[:train_count]):
src = os.path.join(image_folder, img_name)
dst = os.path.join(train_path, img_name)
shutil.move(src, dst)
for i, img_name in enumerate(all_images[train_count : train_count + val_count]):
src = os.path.join(image_folder, img_name)
dst = os.path.join(val_path, img_name)
shutil.move(src, dst)
for i, img_name in enumerate(all_images[train_count + val_count :]):
src = os.path.join(image_folder, img_name)
dst = os.path.join(test_path, img_name)
shutil.move(src, dst)
print("Images have been randomly split into train, val, and test folders.")
阅读全文