如何在不保持纵横比的情况下调整图像大小?

问题描述

我尝试了很多方法来根据宽度和高度值强制调整图像大小,但它总是以我不期望的纵横比返回。

我有几张图片,我想找出平均宽度和高度的像素值,然后根据这些平均像素值,我希望调整整个图像的大小。

这是我尝试计算平均像素的代码

from PIL import Image,ImageOps

listofimages = ['one.jpg','two.jpg','three.jpg','four.jpg','five.jpg','six.jpg']

def get_avg_size(listofimages):
    h,w = 0,0
    for p in listofimages:
        im = Image.open(p)
        width,height = im.size
        h += height
        w += width
        print('Process image {0} and height-weight is {1} '.format(p,im.size))

    print('Calculate average w-h: {0} ~ {1}'.format(w //len(listofimages),h//len(listofimages)))
    return w//len(listofimages),h//len(listofimages)

然后调整所有图像的大小:

def _convert_in_same_size(width,height,listofimages):
    sizes = width,height
    for p in listofimages:
        images = Image.open(p)
        images.thumbnail(sizes,Image.ANTIALIAS)
        images.save(p)
        print('Saved image {0} and size is {1}'.format(p,sizes))

得到结果:

get_width,get_height = get_avg_size(listofimages)
_convert_in_same_size(get_width,get_height,listofimages)

输出

Process image one.jpg and height-weight is (771,480) 
Process image two.jpg and height-weight is (480,270) 
Process image three.jpg and height-weight is (800,484) 
Process image four.jpg and height-weight is (522,340) 
Process image five.jpg and height-weight is (1200,900)
Process image six.jpg and height-weight is (1000,667)

Calculate average w-h: 795 ~ 523

Saved image one.jpg and size is (795,523)
Saved image two.jpg and size is (795,523)
Saved image three.jpg and size is (795,523)
Saved image four.jpg and size is (795,523)
Saved image five.jpg and size is (795,523)
Saved image six.jpg and size is (795,523)

显示结果大小为 (795,523),但实际情况是每张图片都保持纵横比。如果我在调整图像大小后再次检查

Process image one.jpg and height-weight is (771,480)
Process image two.jpg and height-weight is (480,270)
Process image three.jpg and height-weight is (795,481)
Process image four.jpg and height-weight is (522,340)
Process image five.jpg and height-weight is (697,523)
Process image six.jpg and height-weight is (784,523)

我不希望有任何纵横比,并使用 average(795 ~ 523) 像素强制调整所有图像的大小。我该怎么做?

解决方法

来自 Image.thumbnail 的文档:

此方法计算适当的缩略图大小以保留图像的外观,[...]

那么,为什么不将 Image.resize 用于该任务?

from PIL import Image

img = Image.open('path/to/some/image.png')
print(img)
# ... size=400x400

img_thumb = img.copy()
img_thumb.thumbnail(size=(300,200))
print(img_thumb)
# ... size=200x200

img_resize = img.resize((300,200))
print(img_resize)
# ... size=300x200

Image.resize 将(强制)将任何图像调整为给定大小。

----------------------------------------
System information
----------------------------------------
Platform:      Windows-10-10.0.16299-SP0
Python:        3.9.1
PyCharm:       2021.1.1
Pillow:        8.2.0
----------------------------------------