一、创建文件夹
创建输入文件夹(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的比例了。
Python自动化脚本多文件夹裁剪图片为1:1

149

被折叠的 条评论
为什么被折叠?



