【问题标题】:With the Python Imaging Library (PIL), how does one compose an image with an alpha channel over another image?使用 Python Imaging Library (PIL),如何在另一个图像上合成具有 alpha 通道的图像?
【发布时间】:2018-05-30 16:30:22
【问题描述】:

我有两张图片,都带有 Alpha 通道。我想将一个图像放在另一个图像上,从而生成一个带有 alpha 通道的新图像,就像将它们分层渲染一样。我想用 Python Imaging Library 来做这件事,但是在其他系统中的推荐会很棒,即使是原始数学也会是一个福音;我可以使用 NumPy。

【问题讨论】:

标签: python image-processing python-imaging-library


【解决方案1】:

这似乎可以解决问题:

from PIL import Image
bottom = Image.open("a.png")
top = Image.open("b.png")

r, g, b, a = top.split()
top = Image.merge("RGB", (r, g, b))
mask = Image.merge("L", (a,))
bottom.paste(top, (0, 0), mask)
bottom.save("over.png")

【讨论】:

  • @~unutbu 不,你的效果更好。我已将您的解决方案纳入我的项目中。
  • 刚试过这个,(a)它工作得很好,至少对于我正在做的快速而肮脏的任务,并且(b)不需要安装 numpy。不过请注意上面的评论。
【解决方案2】:

Pillow 2.0 现在包含一个执行此操作的 alpha_composite 函数。

img3 = Image.alpha_composite(img1, img2)

【讨论】:

    【解决方案3】:

    我在 PIL 中找不到 alpha composite 函数,所以这是我用 numpy 实现它的尝试:

    import numpy as np
    from PIL import Image
    
    def alpha_composite(src, dst):
        '''
        Return the alpha composite of src and dst.
    
        Parameters:
        src -- PIL RGBA Image object
        dst -- PIL RGBA Image object
    
        The algorithm comes from http://en.wikipedia.org/wiki/Alpha_compositing
        '''
        # http://stackoverflow.com/a/3375291/190597
        # http://stackoverflow.com/a/9166671/190597
        src = np.asarray(src)
        dst = np.asarray(dst)
        out = np.empty(src.shape, dtype = 'float')
        alpha = np.index_exp[:, :, 3:]
        rgb = np.index_exp[:, :, :3]
        src_a = src[alpha]/255.0
        dst_a = dst[alpha]/255.0
        out[alpha] = src_a+dst_a*(1-src_a)
        old_setting = np.seterr(invalid = 'ignore')
        out[rgb] = (src[rgb]*src_a + dst[rgb]*dst_a*(1-src_a))/out[alpha]
        np.seterr(**old_setting)    
        out[alpha] *= 255
        np.clip(out,0,255)
        # astype('uint8') maps np.nan (and np.inf) to 0
        out = out.astype('uint8')
        out = Image.fromarray(out, 'RGBA')
        return out
    

    例如给定这两张图片,

    img1 = Image.new('RGBA', size = (100, 100), color = (255, 0, 0, 255))
    draw = ImageDraw.Draw(img1)
    draw.rectangle((33, 0, 66, 100), fill = (255, 0, 0, 128))
    draw.rectangle((67, 0, 100, 100), fill = (255, 0, 0, 0))
    img1.save('/tmp/img1.png')
    

    img2 = Image.new('RGBA', size = (100, 100), color = (0, 255, 0, 255))
    draw = ImageDraw.Draw(img2)
    draw.rectangle((0, 33, 100, 66), fill = (0, 255, 0, 128))
    draw.rectangle((0, 67, 100, 100), fill = (0, 255, 0, 0))
    img2.save('/tmp/img2.png')
    

    alpha_composite 产生:

    img3 = alpha_composite(img1, img2)
    img3.save('/tmp/img3.png')
    

    【讨论】:

      猜你喜欢
      • 2019-06-12
      • 2011-02-03
      • 2013-11-02
      • 2016-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-07
      相关资源
      最近更新 更多