Skip to main content
 首页 » 编程设计

python之如何使 ImageOps.fit 不裁剪

2024年12月31日7itcoder

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

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:

→

→

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