一、准备工作参考本文:
二、源码:
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__':
# Manually input folder paths
input_folders = []
print("Enter the paths to the input folders (leave empty to stop):")
while True:
folder = input("Input folder path: ")
if folder == '':
break
elif os.path.isdir(folder):
input_folders.append(folder)
else:
print(f"Invalid folder path: {folder}, please try again.")
# Define the base output folder
base_output_folder = input("Enter the base output folder path: ")
# Crop images in all input folders
if input_folders:
crop_images_to_square(input_folders, base_output_folder)
else:
print("No valid input folders provided. Exiting.")
三、运行示例:
运行后输入文件夹路径点回车输入下一个文件夹路径,全输入完后点回车,输入输出文件夹路径,再回车运行,提前建立输出文件夹路径