python应用(9)——将一个文件夹里的图片分配到多个文件夹内


需求:将一个文件夹里的所有图片分到多个文件夹中,假设要求每个文件夹里分到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)
### 使用Python读取文件夹中的图像 为了实现从指定文件夹中加载并处理图像数据,在Python中有多种库可以完成这项工作,其中最常用的是`PIL`(现在通常通过其维护版本`Pillow`访问)以及`OpenCV`。下面展示两种方法来遍历给定路径下的所有图片文件,并将其载入内存。 #### 方法一:使用 Pillow 库 Pillow 是基于 Python Imaging Library (PIL) 构建的一个非常流行的图像处理库。它支持广泛的图像格式并且易于安装和使用。 ```python from PIL import Image import os def load_images_from_folder(folder): images = [] for filename in os.listdir(folder): img_path = os.path.join(folder, filename) if img_path.endswith(("jpeg", "jpg", "png")): # 只考虑这些扩展名的文件 try: with Image.open(img_path) as img: images.append(img.copy()) # 防止原始文件被修改 except Exception as e: print(f"Failed to load image {img_path}: ", str(e)) return images ``` 此函数会返回一个包含所有成功打开的图像对象列表[^1]。 #### 方法二:使用 OpenCV 库 对于计算机视觉任务来说,OpenCV 提供了一个强大的工具集用于图像操作。它可以轻松地读取不同类型的图像文件,并提供额外的功能来进行预处理或其他形式的数据增强。 ```python import cv2 import os def load_images_from_folder_cv2(folder): images = [] for filename in os.listdir(folder): img_path = os.path.join(folder, filename) if img_path.endswith(('jpeg', 'jpg', 'png')): img = cv2.imread(img_path) if img is not None: images.append(img) else: print(f'Error loading image at path {img_path}') return images ``` 这段代码同样实现了相同的目标——收集来自特定目录下所有的兼容图像到一个列表;不过这采用了 `cv2.imread()` 函数代替了之前的方式。 无论选择哪种方式取决于具体应用场景和个人偏好。如果只需要基本功能的话推荐使用更轻量级且容易上手的 Pillow;而对于涉及更多高级图像分析的任务,则可能更适合采用功能更为全面丰富的 OpenCV 来解决问题。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

想要躺平的一枚

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值