Coding-重新设置图像尺寸-裁剪

摘要

将图片裁剪成预定尺寸,如果图片小于预定尺寸则会用黑底填充

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))

# 调整图片大小以便裁剪(这步可选,取决于是否需要先按调整大小后的图片中心进行裁剪)
# img = img.resize(cropped_size, resample=Image.LANCZOS)

# 计算裁剪的起始坐标以中心对齐
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)