我有一些图像,我想找出平均宽度和高度像素值,然后根据这些平均像素值,我希望调整整个图像的大小。
下面是我试图计算平均像素的代码:
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
)像素。我该怎么做?