简体   繁体   English

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

[英]How to compose an image with an alpha channel over another image(RGB, without alpha channel)? Using python PIL

My question is similar as this one: With the Python Imaging Library (PIL), how does one compose an image with an alpha channel over another image? 我的问题与此相似: 使用Python Imaging Library(PIL),一个人如何在另一个图像上组成一个带有alpha通道的图像? I have two images, the top image with alpha channels and the bottom one without. 我有两张图片,最上面的图片带有Alpha通道,最下面的一张没有。 I want to put top image over the bottom one, resulting in a new image , just as would occur if they were rendered in layers. 我想将顶部图像放在底部图像上,以生成新图像,就像将它们分层渲染一样。 I would like to do this with the Python PIL. 我想用Python PIL做到这一点。 Any suggestion would be appreciable, thanks! 任何建议都是可取的,谢谢!

Simply extend your RGB image to RGBA with A set to "1": 只需将A设置为“ 1”即可将RGB图像扩展为RGBA:

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

and then use the compose method you mentioned. 然后使用您提到的compose方法。

If you use Pillow instead you can simply use: 如果您使用枕头,则可以简单地使用:

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

I have solved my issue by myself, the problem is that the value of alpha channel in RGBA image is either 0 or 255, I just change the 255 to 220, so that the top image won't cover the bottom image. 我已经解决了我的问题,问题是RGBA图像中的alpha通道的值是0或255,我只是将255更改为220,所以顶部图像不会覆盖底部图像。 My code is as follow: 我的代码如下:

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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM