英文:
Resize any image to 512 x 512
问题
我正在尝试训练一个稳定的扩散模型,它以 512 x 512
的图像作为输入。
我从网络上下载了大量的图像,它们具有多种大小和形状,因此我需要对它们进行预处理并转换为 512 x 512
。
如果我拿这张 2000 × 1434
的图像为例:
然后尝试使用以下代码进行调整大小:
from PIL import Image
# 打开图像文件
with Image.open("path/to/Image.jpg") as im:
# 创建图像的缩略图
im.thumbnail((512, 512))
# 保存缩略图
im.save("path/to/Image_resized.jpg")
我会得到这张 512 × 367
的图像:
但我需要宽度和高度都为512,而不扭曲图像,就像您可以在这个网站上实现的那样:
有关如何使用Python实现这种转换的想法吗?
英文:
I am trying to train a stable diffusion model, which receives 512 x 512
images as inputs.
I am downloading the bulk of images from the web, and they have multiple sizes and shapes, and so I need to preprocess them and convert to 512 x 512
.
If I take this 2000 × 1434
image:
And I try to resize it, with:
from PIL import Image
# Open an image file
with Image.open("path/to/Image.jpg") as im:
# Create a thumbnail of the image
im.thumbnail((512, 512))
# Save the thumbnail
im.save("path/to/Image_resized.jpg")
I get this 512 × 367
image:
But I need 512 for both width and height, without distorting the image, like you can achieve on this website:
Any ideas on how I can achieve this conversion using python?
答案1
得分: 2
我认为不可能将一个宽高比不为1:1的图像(512:512)进行调整大小而不失真。您可以将图像的较短维度调整为512像素,然后将较大维度裁剪为512像素。
from PIL import Image
# 打开图像文件
with Image.open("image.jpg") as im:
width, height = im.size
if width < height:
newWidth = 512
newHeight = int(height / (width / 512))
cropTop = (newHeight - 512) // 2
cropBottom = cropTop + 512
crop = (0, cropTop, 512, cropBottom)
else:
newHeight = 512
newWidth = int(width / (height / 512))
cropLeft = (newWidth - 512) // 2
cropRight = cropLeft + 512
crop = (cropLeft, 0, cropRight, 512)
imResize = im.resize((newWidth, newHeight))
imCrop = imResize.crop(crop)
imCrop.save("image_resized_cropped.jpg")
英文:
I dont think a resize of an image with another aspect ratio of 1:1 (512:512) is possible without distorting the image. You can resize the shorter dimension of the image to 512px and crop the large dimension to 512px.
from PIL import Image
# Open an image file
with Image.open("image.jpg") as im:
width, height = im.size
if width < height:
newWidth = 512
newHeight = int(height / (width / 512))
cropTop = (newHeight - 512) // 2
cropBottom = cropTop + 512
crop = (0, cropTop, 512, cropBottom)
else:
newHeight = 512
newWidth = int(width / (height / 512))
cropLeft = (newWidth - 512) // 2
cropRight = cropLeft + 512
crop = (cropLeft, 0, cropRight, 512)
imResize = im.resize((newWidth, newHeight))
imCrop = imResize.crop(crop)
imCrop.save("image_resized_cropped.jpg")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论