Created
February 21, 2023 08:15
-
-
Save ShadowPower/bb27897b2b91575d2e84608f7fdb2aa0 to your computer and use it in GitHub Desktop.
用新版bing生成的调整图片尺寸&加上白色边框
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
from PIL import Image | |
# 定义源目录和目标目录 | |
source_dir = r"D:\dataset\before" | |
target_dir = r"D:\dataset\after" | |
# 遍历源目录下的所有图片文件 | |
for filename in os.listdir(source_dir): | |
# 打开图片文件 | |
image = Image.open(os.path.join(source_dir, filename)) | |
# 获取图片的宽度和高度 | |
width, height = image.size | |
# 计算缩放比例,保持图像比例不变 | |
ratio = min(512 / width, 512 / height) | |
# 计算缩放后的宽度和高度 | |
new_width = int(width * ratio) | |
new_height = int(height * ratio) | |
# 缩放图片 | |
image = image.resize((new_width, new_height), Image.ANTIALIAS) | |
# 创建一个新的白色背景图片,大小为512x512 | |
background = Image.new("RGB", (512, 512), (255, 255, 255)) | |
# 将缩放后的图片粘贴到背景图片上,居中对齐 | |
offset_x = (512 - new_width) // 2 | |
offset_y = (512 - new_height) // 2 | |
background.paste(image, (offset_x, offset_y)) | |
# 将背景图片保存到目标目录下,格式为png | |
background.save(os.path.join(target_dir, filename + ".png")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment