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
43
44
45
46
47
48
49
50
51
52
from PIL import Image
import os

# 指定源文件夹和目标文件夹
source_folder = 'data'
output_folder = 'output28'
# target_resolution = (1440, 1920)
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:
# 创建一个目标尺寸的黑色背景图像(想要白色就是255,255,255)
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)