5

我正在尝试在 Python 中裁剪和调整图像大小,然后我希望它们采用固定格式(47x62 像素)。但是,如果原始图像是横向的,我的算法不起作用,会有空白区域。

import Image, sys

MAXSIZEX = 47
MAXSIZEY = 62

im = Image.open(sys.argv[1])
(width, height) = im.size

ratio = 1. * MAXSIZEX / MAXSIZEY

im = im.crop((0, 0, int(width*ratio), int(height*ratio)))
im = im.resize((MAXSIZEX, MAXSIZEY), Image.ANTIALIAS)

im.save(sys.argv[2])

我希望调整后的图像完全是 47x62 - 应该没有可见的空白区域。

4

2 回答 2

1

您应该首先检查是否MAXSIZEX大于宽度或MAXSIZEY大于高度。如果他们首先重新缩放图像然后进行裁剪:

MAXSIZEX = 64
MAXSIZEY = 42
width, height = im.size

xrat = width / float(MAXSIZEX)
yrat = height / float(MAXSIZEY)

if xrat < 1 or yrat < 1:
    rat = min(xrat, yrat)
    im = im.resize((int(width / rat), int(height / rat)))
res = im.crop((0, 0, MAXSIZEX, MAXSIZEY))
res.show()
于 2013-09-20T14:54:13.050 回答
0

选择 x/y 作为缩放比例是一个隐含的假设,即相对于目标分辨率而言,源的 y 维度始终小于源的 x 维度。首先,确定要缩放的维度,然后裁剪:

width_count = float(width) / MAXSIZEX
height_count = float(height) / MAXSIZEY
if width_count == height_count:
    pass
elif width_count < height_count:
    im = im.crop(0, 0, width, int(width_count * height / height_count))
else:
    im = im.crop(0, 0, int(height_count * width / width_count), height)

现在您知道您拥有与目标纵横比相匹配的原始子图像的最大子图像,因此您可以在不扭曲图像的情况下调整大小。

于 2013-09-20T14:55:53.103 回答