我怎么做ImageOps.fit不是庄稼吗?

2024-09-30 14:34:56 发布

您现在位置:Python中文网/ 问答频道 /正文

如何使ImageOps.fit(source28x32, (128, 128))适合而不修剪顶部/底部/侧面?我真的必须找到方面,相应地调整大小,使放大后的版本不超过128x128,然后添加边框像素(或在128x128画布中使图像居中)?请注意,源可以是任何比率,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


Tags: 图像版本newsize画布像素floatfit
1条回答
网友
1楼 · 发布于 2024-09-30 14:34:56

这是在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中

^{pr2}$

所需宽度为128:

enter image description hereenter image description here

enter image description hereenter image description here

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

相关问题 更多 >