Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With the Python Imaging Library (PIL), how does one compose an image with an alpha channel over another image?

I have two images, both with alpha channels. I want to put one image over the other, resulting in a new image with an alpha channel, just as would occur if they were rendered in layers. I would like to do this with the Python Imaging Library, but recommendations in other systems would be fantastic, even the raw math would be a boon; I could use NumPy.

like image 592
Kris Kowal Avatar asked Jul 30 '10 19:07

Kris Kowal


People also ask

How do you display the PIL of an image in Python?

Python – Display Image using PIL To show or display an image in Python Pillow, you can use show() method on an image object. The show() method writes the image to a temporary file and then triggers the default program to display that image. Once the program execution is completed, the temporary file will be deleted.

What is alpha channel in image?

The alpha channel (also called alpha planes) is a color component that represents the degree of transparency (or opacity) of a color (i.e., the red, green and blue channels). It is used to determine how a pixel is rendered when blended with another.


2 Answers

This appears to do the trick:

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")
like image 161
Kris Kowal Avatar answered Sep 21 '22 17:09

Kris Kowal


Pillow 2.0 now contains an alpha_composite function that does this.

img3 = Image.alpha_composite(img1, img2)
like image 45
olt Avatar answered Sep 21 '22 17:09

olt