【问题标题】:Remove transparency/alpha from any image using PIL使用 PIL 从任何图像中删除透明度/alpha
【发布时间】:2016-03-08 04:44:17
【问题描述】:

如何用指定的背景颜色替换任何图像(png、jpg、rgb、rbga)的 alpha 通道?它还必须适用于没有 Alpha 通道的图像。

【问题讨论】:

    标签: python python-imaging-library pillow alphablending


    【解决方案1】:

    这可以通过检查图像是否透明来完成

    def remove_transparency(im, bg_colour=(255, 255, 255)):
    
        # Only process if image has transparency (http://stackoverflow.com/a/1963146)
        if im.mode in ('RGBA', 'LA') or (im.mode == 'P' and 'transparency' in im.info):
    
            # Need to convert to RGBA if LA format due to a bug in PIL (http://stackoverflow.com/a/1963146)
            alpha = im.convert('RGBA').split()[-1]
    
            # Create a new background image of our matt color.
            # Must be RGBA because paste requires both images have the same format
            # (http://stackoverflow.com/a/8720632  and  http://stackoverflow.com/a/9459208)
            bg = Image.new("RGBA", im.size, bg_colour + (255,))
            bg.paste(im, mask=alpha)
            return bg
    
        else:
            return im
    

    【讨论】:

    • 在现代版本的 Pillow 中,您可能可以使用 .getchannel('A') 而不是 .split()[-1]
    • 将图像粘贴到背景上后,我还必须使用bg.convert('RGB')转换为RGB
    【解决方案2】:

    我建议使用Image.alpha_composite
    如果 png 没有 alpha 通道,此代码可以避免 tuple index out of range 错误。

    from PIL import Image
    
    png = Image.open(img_path).convert('RGBA')
    background = Image.new('RGBA', png.size, (255,255,255))
    
    alpha_composite = Image.alpha_composite(background, png)
    alpha_composite.save('foo.jpg', 'JPEG', quality=80)
    

    我还建议您使用image.show() 检查这两个结果。

    此答案归功于shuuji3 和其他帮助在this other question 中建立大量答案库的人。

    【讨论】:

      【解决方案3】:

      我用用户 tutuDajuju 更新了Vincius M's code,建议制作 [height, width, 3] 矩阵(不是 [height, width, 4]):

      from PIL import Image
      import numpy as np
      
      png = Image.open(img_path).convert('RGBA')
      background = Image.new('RGBA', png.size, (255,255,255))
      
      alpha_composite = Image.alpha_composite(background, png)
      # if you check the matrix dimension, channel, it would be still 4.  
      h, w, channel = np.asarray(alpha_composite)
      
      alpha_composite_3 = alpha_composite.convert('RGB')
      # if you check the matrix dimension, channel, it would be 3.  
      h, w, channel = np.asarray(alpha_composite_3)
      
      

      【讨论】:

        猜你喜欢
        • 2023-04-02
        • 1970-01-01
        • 2019-02-08
        • 2010-10-11
        • 1970-01-01
        • 2023-03-02
        • 1970-01-01
        • 2011-05-10
        • 1970-01-01
        相关资源
        最近更新 更多