首页 > 解决方案 > 如何使 ImageOps.fit 不裁剪?

问题描述

如何在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

新的拟合图像

新装

标签: pythonpython-imaging-library

解决方案


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

在 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:

在此处输入图像描述在此处输入图像描述

在此处输入图像描述在此处输入图像描述

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


推荐阅读