Python自动化脚本裁剪图片为1:1比例(多文件夹版)

Python自动化脚本多文件夹裁剪图片为1:1

一、创建文件夹

创建输入文件夹(in1、in2、in3)和输出文件夹(out),将原始图片放在输入文件夹(in1、in2、in3)里。我这里创建了三个要处理的图片文件夹,里面各有一张图片,还有输出的文件夹out。

二、下载安装需要的Python库

pip install Pillow

三、Python脚本源码 

import os
from PIL import Image

def crop_images_to_square(input_folders, base_output_folder):
    """
    Crop all images in multiple input folders to square shape and save them in corresponding output folders.

    Args:
        input_folders (list): List of paths to input folders containing images.
        base_output_folder (str): Base path for output folders.
    """
    for input_folder in input_folders:
        # Create corresponding output folder structure
        relative_folder = os.path.relpath(input_folder, start=os.path.commonpath(input_folders))
        output_folder = os.path.join(base_output_folder, relative_folder)
        os.makedirs(output_folder, exist_ok=True)

        # Process each file in the current input folder
        for filename in os.listdir(input_folder):
            if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp')):
                img_path = os.path.join(input_folder, filename)
                try:
                    with Image.open(img_path) as img:
                        # Get image dimensions
                        width, height = img.size
                        new_size = min(width, height)

                        # Calculate cropping box
                        left = (width - new_size) / 2
                        top = (height - new_size) / 2
                        right = (width + new_size) / 2
                        bottom = (height + new_size) / 2

                        # Crop and save the image
                        img_cropped = img.crop((left, top, right, bottom))
                        img_cropped.save(os.path.join(output_folder, filename))
                        print(f'Cropped and saved: {os.path.join(output_folder, filename)}')
                except Exception as e:
                    print(f"Error processing file {img_path}: {e}")

if __name__ == '__main__':
    # Define the list of input folders
    input_folders = [
        r'C:\Users\Administrator\Desktop\r\in1',
        r'C:\Users\Administrator\Desktop\r\in2',
        r'C:\Users\Administrator\Desktop\r\in3',
    ]

    # Define the base output folder
    base_output_folder = r'C:\Users\Administrator\Desktop\r\out'

    # Crop images in all input folders
    crop_images_to_square(input_folders, base_output_folder)

ps:input_folder为输入文件夹,base_output_folder为根输出文件夹,需要注意的是如果是绝对路径,前面需要添加原始字符串r。脚本运行后输出的对应文件夹会创建在out文件夹下。

四、运行脚本

可以看到脚本运行后已经裁剪并保存了。

五、查看裁剪结果

在out文件夹中已经创建了裁剪后对应的图片所在文件夹,并可以看到图片已经是1:1的比例了。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值