import os
import random
import shutil
def random_sample_images(source_folder, destination_folder, num_samples=5):
# 遍历源文件夹下的子文件夹
for root, dirs, files in os.walk(source_folder):
# 创建对应的目标文件夹
destination_subfolder = os.path.join(destination_folder, os.path.relpath(root, source_folder))
os.makedirs(destination_subfolder, exist_ok=True)
# 随机抽取 num_samples 张图片
sampled_files = random.sample(files, min(num_samples, len(files)))
# 将抽取的图片复制到目标文件夹
for file in sampled_files:
source_path = os.path.join(root, file)
destination_path = os.path.join(destination_subfolder, file)
shutil.copy(source_path, destination_path)
# 指定源文件夹和目标文件夹路径
source_folder = '/path/to/source/folder'
destination_folder = '/path/to/destination/folder'
# 调用函数进行随机抽取和保存图片
random_sample_images(source_folder, destination_folder, num_samples=5)