如何用Python将图片无损调整为512×512适配Stable Diffusion训练
实现无扭曲转换为512×512图片的两种方案
要实现需求中的效果,核心是先保持图片原有比例缩放,再通过居中裁剪或背景填充得到正方形尺寸,以下是具体实现:
方案1:居中裁剪(保留核心区域)
这种方法会先将图片按比例缩放到最短边为512,然后裁剪中间的512×512区域,适合希望保留图片核心内容的场景。
from PIL import Image def crop_to_square(image_path, output_path, size=512): with Image.open(image_path) as img: # 计算缩放比例,确保最短边缩放到目标尺寸 width, height = img.size scale = size / min(width, height) new_width = int(width * scale) new_height = int(height * scale) # 按比例缩放图片,使用LANCZOS算法保证画质 img = img.resize((new_width, new_height), Image.Resampling.LANCZOS) # 计算居中裁剪的坐标 left = (new_width - size) // 2 top = (new_height - size) // 2 right = left + size bottom = top + size # 裁剪并保存结果 cropped_img = img.crop((left, top, right, bottom)) cropped_img.save(output_path) # 调用示例 crop_to_square("path/to/Image.jpg", "path/to/Image_cropped.jpg")
方案2:背景填充(保留完整图片)
这种方法会先将图片按比例缩放到最长边不超过512,然后在空白区域填充背景色(默认白色),适合需要保留图片全部内容的场景。
from PIL import Image def pad_to_square(image_path, output_path, size=512, bg_color=(255, 255, 255)): with Image.open(image_path) as img: # 计算缩放比例,确保最长边不超过目标尺寸 width, height = img.size scale = size / max(width, height) new_width = int(width * scale) new_height = int(height * scale) # 按比例缩放图片 img = img.resize((new_width, new_height), Image.Resampling.LANCZOS) # 创建指定尺寸的正方形画布 square_img = Image.new("RGB", (size, size), bg_color) # 计算居中粘贴的位置 paste_x = (size - new_width) // 2 paste_y = (size - new_height) // 2 # 粘贴缩放后的图片并保存 square_img.paste(img, (paste_x, paste_y)) square_img.save(output_path) # 调用示例 pad_to_square("path/to/Image.jpg", "path/to/Image_padded.jpg")
注意事项
- 若使用PIL旧版本(低于9.1.0),将
Image.Resampling.LANCZOS替换为Image.LANCZOS即可。 - 批量处理时,只需遍历本地图片路径列表,循环调用上述函数即可完成批量转换。
内容的提问来源于stack exchange,提问作者8-Bit Borges
相关产品推荐
相关产品推荐

