需求:将一个文件夹里的所有图片分到多个文件夹中,假设要求每个文件夹里分到100张图片,当分到最后不足100张图时,也正常进行
代码如下(示例):
import os
import shutil
def split_images(source_folder, destination_folder, images_per_folder):
# 确保目标文件夹存在
os.makedirs(destination_folder, exist_ok=True)
# 获取源文件夹中的所有图片文件
image_files = [f for f in os.listdir(source_folder) if os.path.isfile(os.path.join(source_folder, f))]
# 计算需要创建的目标文件夹数量
num_folders = len(image_files) // images_per_folder
if len(image_files) % images_per_folder > 0:
num_folders += 1
# 将图片分配到目标文件夹中
for i in range(num_folders):
folder_name = f"folder_{i+1}"
folder_path = os.path.join(destination_folder, folder_name)
os.makedirs(folder_path, exist_ok=True)
# 计算当前目标文件夹应包含的图片范围
start_index = i * images_per_folder
end_index = (i + 1) * images_per_folder
# 处理最后一个文件夹,如果图像数量不足images_per_folder
if i == num_folders - 1 and len(image_files) % images_per_folder > 0:
end_index = len(image_files)
# 将图片复制到目标文件夹
for j in range(start_index, end_index):
image_file = image_files[j]
source_file_path = os.path.join(source_folder, image_file)
destination_file_path = os.path.join(folder_path, image_file)
shutil.copyfile(source_file_path, destination_file_path)
print(f"Created folder {folder_name} and copied {end_index - start_index} images.")
# 示例用法
source_folder = "C:/Users/jutze/Desktop/353S02073"
destination_folder = "C:/Users/jutze/Desktop/IC_contours"
images_per_folder = 100
split_images(source_folder, destination_folder, images_per_folder)