python - 如何使 ImageOps.fit 不裁剪?

标签 python python-imaging-library

如何让 ImageOps.fit(source28x32, (128, 128)) 适合而不裁剪顶部/底部/侧面?我真的必须找到方面,相应地调整大小以使放大版本不超过 128x128,然后添加边框像素(或将图像居中放置在 128x128 Canvas 中)吗?请注意,源可以是任何比例,28x32 只是一个例子。

源图像 (28x32)

source image

拟合图像 (128x128)

fitted image

这是我目前的尝试,不是特别优雅

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

新拟合图像

new fitted

最佳答案

这里是PILcv2中实现的函数。输入可以是任何大小;该函数找到使最大边缘适合所需宽度所需的比例,然后将其放到所需宽度的黑色正方形图像上。

在 PIL 中

def resize_PIL(im, output_edge):
    scale = output_edge / max(im.size)
    new = Image.new(im.mode, (output_edge, output_edge), (0, 0, 0))
    paste = im.resize((int(im.width * scale), int(im.height * scale)), resample=Image.NEAREST)
    new.paste(paste, (0, 0))
    return new

在 cv2

def resize_cv2(im, output_edge):
    scale = output_edge / max(im.shape[:2])
    new = np.zeros((output_edge, output_edge, 3), np.uint8)
    paste = cv2.resize(im, None, fx=scale, fy=scale, interpolation=cv2.INTER_NEAREST)
    new[:paste.shape[0], :paste.shape[1], :] = paste
    return new

所需宽度为 128:

enter image description hereenter image description here

enter image description hereenter image description here

未显示:这些函数适用于大于所需尺寸的图像

关于python - 如何使 ImageOps.fit 不裁剪?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52234971/

相关文章:

python - numpy stride_tricks.as_strided 与滚动窗口的列表理解

python - 确定最小量级数但在 Python 中保留符号的优雅机制

python - 为什么在 Python 中使用 PIL 调整图像大小时会得到负像素值?

python - 在python中正确旋转或翻转图像[发票,表格]到正确的方向

python - 使用numpy为特定值的像素制作掩码数组

python - 我怎样才能用 python 的枕头使我裁剪的 gif 角透明?

python - 两个矩阵之间的余弦距离

python - 类型错误 : get_bind() got an unexpected keyword argument

python - 使用 BeautifulSoup 将 <a> 定位到特定属性

python - 将 2D Numpy 灰度值数组转换为 PIL 图像