【问题标题】:Python3: Resize rectangular image to a different kind of rectangle, keeping ratio and fill background with blackPython3:将矩形图像调整为不同类型的矩形,保持比例并用黑色填充背景
【发布时间】:2018-09-25 12:14:11
【问题描述】:

我有一个与此非常相似的问题:Resize rectangular image to square, keeping ratio and fill background with black,但我想调整为非方形图像的大小,并在需要时将图像水平或垂直居中。

以下是一些所需输出的示例。我完全用 Paint 制作了这张图片,所以图片实际上可能不是完全居中的,但居中是我想要实现的:

我尝试了从链接的问题中编辑的以下代码:

def fix_size(fn, desired_w=256, desired_h=256, fill_color=(0, 0, 0, 255)):
    """Edited from https://stackoverflow.com/questions/44231209/resize-rectangular-image-to-square-keeping-ratio-and-fill-background-with-black"""
    im = Image.open(fn)
    x, y = im.size
    #size = max(min_size, x, y)
    w = max(desired_w, x)
    h = max(desired_h, y)
    new_im = Image.new('RGBA', (w, h), fill_color)
    new_im.paste(im, ((w - x) // 2, (h - y) // 2))
    return new_im.resize((desired_w, desired_h))

但这不起作用,因为它仍然会将一些图像拉伸成方形(至少是示例中的图像 b。对于大图像,它似乎会旋转它们!

【问题讨论】:

    标签: python python-3.x image


    【解决方案1】:

    问题在于你对图片尺寸的计算不正确:

    w = max(desired_w, x)
    h = max(desired_h, y)
    

    您只是独立地获取最大尺寸 - 没有考虑图像的纵横比。想象一下,如果您的输入是一个 1000x1000 的正方形图像。您最终会创建一个黑色的 1000x1000 图像,将原始图像粘贴在上面,然后将其调整为 244x138。要获得正确的结果,您必须创建 1768x1000 的图像,而不是 1000x1000 的图像。


    以下是考虑纵横比的更新代码:

    def fix_size(fn, desired_w=256, desired_h=256, fill_color=(0, 0, 0, 255)):
        """Edited from https://stackoverflow.com/questions/44231209/resize-rectangular-image-to-square-keeping-ratio-and-fill-background-with-black"""
        im = Image.open(fn)
        x, y = im.size
    
        ratio = x / y
        desired_ratio = desired_w / desired_h
    
        w = max(desired_w, x)
        h = int(w / desired_ratio)
        if h < y:
            h = y
            w = int(h * desired_ratio)
    
        new_im = Image.new('RGBA', (w, h), fill_color)
        new_im.paste(im, ((w - x) // 2, (h - y) // 2))
        return new_im.resize((desired_w, desired_h))
    

    【讨论】:

    • 不幸的是,这对我不起作用。对于 b) 中的图像,它与命令 Image.open('image.png').resize((244, 138)).save('image2.png') 完全相同。对于更大的 JPG 图像(3456x5184,desired_w 5184 和desired_h 3456,类似于示例 b,但 JPG 格式的图片更大),它会拉伸和旋转,而我的原始代码只是旋转。也不是我想要的,我不想拉伸或旋转,但代码无论如何都会这样做:( - (通过“拉伸”我的意思是改变图像原始非必要黑色部分的纵横比)
    • @hilssu 哎呀。我想我应该在更多图像上测试它。我的错。我认为/希望它现在已修复 :)
    • 是的,谢谢,成功了!好吧,它实际上确实旋转了一张用我朋友的相机拍摄的 JPG 图像,但是当我用 Paint 打开它并将其另存为另一个 JPG 文件时,它工作正常。这证明了 JPG 图像至少可以用两种不同的方式进行编码,其中至少一种是 PIL 无法正确处理的。
    • @hilssu 是的,有办法将旋转信息存储在图像元数据中;我怀疑 PIL 忽略了这一点。
    猜你喜欢
    • 2017-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-07
    • 2017-11-21
    • 2012-02-02
    • 1970-01-01
    相关资源
    最近更新 更多