摘要
将图片设置成预定尺寸,如果图片尺寸与预期不符则会裁剪,如果图片小于预定尺寸则会用黑底填充
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 43 44 45 46 47 48 49 50 51 52
| from PIL import Image import os
source_folder = 'data' output_folder = 'output28'
target_resolution = (28, 28)
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 if current_size[0] >= target_resolution[0] and current_size[1] >= target_resolution[1]: width_ratio = target_resolution[0] / current_size[0] height_ratio = target_resolution[1] / current_size[1] crop_ratio = min(width_ratio, height_ratio) new_size = (int(current_size[0] * crop_ratio), int(current_size[1] * crop_ratio)) img = img.resize(new_size, resample=Image.LANCZOS) left = (new_size[0] - target_resolution[0]) // 2 top = (new_size[1] - target_resolution[1]) // 2 right = (new_size[0] + target_resolution[0]) // 2 bottom = (new_size[1] + target_resolution[1]) // 2 img = img.crop((left, top, right, bottom)) else: new_img = Image.new('RGB', target_resolution, (0, 0, 0)) paste_position = ((target_resolution[0] - current_size[0]) // 2, (target_resolution[1] - current_size[1]) // 2) new_img.paste(img, paste_position) img = new_img 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)
|