摘要
将图片裁剪成预定尺寸,如果图片小于预定尺寸则会用黑底填充
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| from PIL import Image import os
source_folder = 'data' output_folder = 'output1024' target_resolution = (1024, 1024)
if not os.path.exists(output_folder): os.makedirs(output_folder)
for filename in os.listdir(source_folder): if filename.endswith('.jpg') or filename.endswith('.jpeg'): img_path = os.path.join(source_folder, filename) try: with Image.open(img_path) as img: current_size = img.size width_ratio = current_size[0] / target_resolution[0] height_ratio = current_size[1] / target_resolution[1] crop_ratio = max(width_ratio, height_ratio) cropped_size = (int(current_size[0] / crop_ratio), int(current_size[1] / crop_ratio)) left = (current_size[0] - cropped_size[0]) // 2 top = (current_size[1] - cropped_size[1]) // 2 img = img.crop((left, top, left + target_resolution[0], top + target_resolution[1])) output_path = os.path.join(output_folder, filename) img.save(output_path, quality=95) except IOError as e: print(f"Error processing {img_path}: {e}")
print("Images have been processed and saved to", output_folder)
|