如何使ImageOps.fit(source28x32, (128, 128))
适合而不修剪顶部/底部/侧面?我真的必须找到方面,相应地调整大小,使放大后的版本不超过128x128,然后添加边框像素(或在128x128画布中使图像居中)?请注意,源可以是任何比率,28x32只是一个例子。在
源图像(28x32)
适配图像(128x128)
这是我目前为止的尝试,不是特别优雅
def fit(im):
size = 128
x, y = im.size
ratio = float(x) / float(y)
if x > y:
x = size
y = size * 1 / ratio
else:
y = size
x = size * ratio
x, y = int(x), int(y)
im = im.resize((x, y))
new_im = Image.new('L', (size, size), 0)
new_im.paste(im, ((size - x) / 2, (size - y) / 2))
return new_im
新合身图像
这是在
PIL
和cv2
中实现的函数。输入可以是任意大小的;函数会找到将最大边拟合到所需宽度所需的比例,然后将其放在所需宽度的黑色方形图像上。在在PIL中
在cv2中
^{pr2}$所需宽度为128:
→
→
未显示:这些函数适用于大于所需大小的图像
相关问题 更多 >
编程相关推荐