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? I have two images, the top image with alpha channels and the bottom one without. 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. Any suggestion would be appreciable, thanks!
Asked
Active
Viewed 518 times
0
-
Have you tried Kris Kowal's [answer](https://stackoverflow.com/a/3376602/355230) to the linked question? – martineau Jan 18 '19 at 08:41
2 Answers
1
Simply extend your RGB image to RGBA with A set to "1":
rgba = np.dstack((rgb, np.ones(rgb.shape[:-1])))
and then use the compose method you mentioned.
If you use Pillow instead you can simply use:
imRGB.putalpha(alpha)
composite = PIL.Image.alpha_composite(imRGB, im2RGBA)

Mailerdaimon
- 6,003
- 3
- 35
- 46
0
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. 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")

salmon
- 1
- 1