Alpha Channel / Opacity / Masks

You can blend images in interesting ways using opacity values.

Here’s an example of what you can do from sbnation.com:

Here’s what you do to make an image like that:

  1. Make a grayscale version of your picture
  2. Make a blue version of your picture
  3. Create a mask file shaped like a large “25”
  4. Paste or blend the images onto each other through the mask.

Alpha Channel

“RGBA” mode images have “A” (alpha) as their fourth channel. Alpha is theĀ opacity of each pixel. A value of 255 is completely opaque, and a value of 0 is completely transparent.

Creating a Simple Mask

This example creates a square shaped mask with low opacity on the outside and high opacity on the inside.

from PIL import Image
#create a single channel dark gray image
mask = Image.new("L", (300,300), 80)

#draw a light gray rectangle in the middle
mask.paste(200, (50,50,250,250))

The mask looks like this:

If you paste an image through this mask, the middle of the image will show up as mostly opaque, and the outside of the image will be mostly transparent.

Now we’ll paste an image onto a background through the mask.

The background:

Seamless marine wave patterns

The image we’re pasting on top of the background:

Here’s what we get when we paste the cat through the mask:

Here’s the code:

#create a single channel dark gray image
mask = Image.new("L", (300,256), 80)

#draw a light gray rectangle in the middle
mask.paste(200, (50,50,250,206))

#resize the background to the size I want
blue = PIL.Image.open('bluepattern.jpg').resize((400,356))
cat = Image.open('graycat.jpg')

#paste the cat starting at coords (50,50)
blue.paste(cat, (50,50), mask)

blue.show()

If an image doesn’t have an alpha channel and you want to add one, you need to add that somehow. If you want to make a transparent background, you can use AI to figure out which parts are background and remove them.

Remove an Image Background

You can also convert your image to RGBA mode as follows and then iterate through pixels to change some alpha values yourself.

img = img.convert('RGBA')

From there, you can add a loop to make some of the pixels transparent. For example, if you used a Paint program to color in a bunch of your picture with a certain shade of bright yellow, such as RGB (255,255,0), you could search for that color in every pixel, and give all of those pixels an alpha value of zero. That would make all of the yellow parts transparent.

Example of looping through a picture to change alpha values:

#add alpha channel
img = img.convert('RGBA')

#load pixel data
pixels = img.load()

#loop through every pixel
for x in range(img.size[0]):
    for y in range(img.size[1]):
        #only modify yellow pixels
        if pixels[x,y] = [255,255,0,255]:
            #change alpha (last value) to zero:
            pixels[x,y] = [255,255,0,0]

Now you can use this modified image file as a mask.