如何在另一个图像上合成一个带有alpha通道的图像(RGB,没有alpha通道)?使用python PIL

时间:2019-01-18 07:09:41

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

我的问题与此类似: With the Python Imaging Library (PIL), how does one compose an image with an alpha channel over another image? 我有两张图片,最上面的图片带有Alpha通道,最下面的一张没有。我想将顶部图像放在底部图像上,以生成新图像,就像将它们分层渲染一样。我想用Python PIL做到这一点。任何建议都是可取的,谢谢!

2 个答案:

答案 0 :(得分:1)

只需将A设置为“ 1”,即可将RGB图像扩展为RGBA:

rgba = np.dstack((rgb, np.ones(rgb.shape[:-1])))

,然后使用您提到的compose方法。

如果您使用Pillow,则可以简单地使用:

imRGB.putalpha(alpha)
composite = PIL.Image.alpha_composite(imRGB, im2RGBA)

答案 1 :(得分:0)

我自己解决了问题,问题是RGBA图像中的alpha通道值为0或255,我只是将255更改为220,所以顶部图像不会覆盖底部图像。我的代码如下:

def transPNG(srcImageName, dstImageName):
img = Image.open(srcImageName)
img = img.convert("RGBA")
datas = img.getdata()
newData = list()
for item in datas:
    if item[0] > 200 and item[1] > 200 and item[2] > 200:
        newData.append(( 255, 255, 255, 0))
    else:
        newData.append((item[0], item[1], item[2], randint(220, 220)))
img.putdata(newData)
img.save(dstImageName,"PNG")
相关问题