Python Pillow - Working with Alpha Channels



An alpha channel in an image is a component that represents the level of transparency or opacity for each pixel. It is commonly used in RGBA images, where each pixel is defined by its Red, Green, Blue, and Alpha values. This channel determines how much of the background shows through an image. In simple terms we can say a pixel with an alpha value of 0 is fully transparent and while a pixel with an alpha value of 255 is fully opaque.

Here are visual representations of an image with different transparency levels −

working_with_alpha_channels_intro

The following are the breakdown of key concepts related to alpha channels in Pillow −

RGBA Mode

  • Images with an alpha channel are often represented in the RGBA mode.

  • Each pixel in an RGBA image has four components i.e. Red, Green, Blue and Alpha.

Transparency Levels

  • The alpha channel values typically range from 0 to 255.

  • 0 indicates complete transparency i.e. fully see-through or invisible.

  • 255 indicate complete opacity i.e. fully opaque or not see-through.

Accessing Alpha Channel

We can access the alpha channel using the split() function of the Pillow Image module. This function is used to separate the individual color channels of an image. It breaks down an image into its constituent channels by allowing us to access and manipulate each channel separately.

Splitting channels with split() function provides the flexibility to work with and manipulate individual color or alpha channels separately by enabling precise image adjustments and processing.

When the split() function is called on an image object, it returns a tuple of individual channel images. For an RGBA image, the tuple includes the Red, Green, Blue, and Alpha channels. For grayscale or single-channel images split() function still returns four identical copies of the same channel. By accessing the alpha channel specifically, you can manipulate the transparency of an image directly.

The following is the syntax and parameters of the of the split() function −

r,g,b,a = image.split()

Where,

  • image − This is the image object opened using Image.open() function.

  • r, g, b, a − These variables receive the separate bands representing Red, Green, Blue and Alpha i.e. transparency of channels respectively.

Example

In this example we are using the split() function to split and access the alpha channel.

from PIL import Image

# Open an image
img_obj = Image.open('Images/colordots.png')

#Split the image into RGBA channels
red, green, blue, alpha = img_obj.split()

# Alpha (transparency) channel
alpha.show()

Input RGBA Image to be used

colordots.jpg

Output alpha channel

splited_image_a

Creating an Image with Alpha Channel

To create an image with an alpha channel, we can use the new() function. This function provides options like mode, width, height and the RGBA values for customizing the image. The last argument's last value defines the transparency i.e. alpha of the image.

Example

In this example we will create an image with alpha channel using the new() funtion.

from PIL import Image

# Create an RGBA image with Semi-transparent green
image = Image.new('RGBA', (700, 300), (10, 91, 51, 100))  

# Display the resultant image with alpha channel
image.show()

On executing the above program you will get output RGBA like below −

image_with_alpha

Modifying Alpha Channels

The individual alpha values for pixels can be set using the putpixel() function to apply modifications to the alpha channel of an image.

The putpixel() function of the Python Pillow is used to change the color of a single pixel at a specified position within an image. This function allows us to directly modify the color of a specific pixel by providing its coordinates and the desired color.

The below is the syntax and parameters of the putpixel() function.

image.putpixel((x, y), color)
  • image − This is the image object opened using Image.open() function.

  • (x, y) − These are the coordinates of the pixel where we want to set the color. x represents the horizontal position and y represents the vertical position.

  • color − The color value that we want to assign to the specified pixel. The format of the color value depends on the image mode.

Example

In this example we are using the putpixel() function of the pillow library for modifying the alpha values for pixels of the given input image.

from PIL import Image

# Open an image
image = Image.open("Images/colordots.png")
width, height = image.size

# Modify alpha values of pixels
for y in range(height):
    for x in range(width):
        r, g, b, a = image.getpixel((x, y))
        image.putpixel((x, y), (r, g, b, int(a * 0.5)))  # Reduce alpha by 50%

# Display the modified image
image.show()

Input Image

colordots jpg

Output modified image

modified_alpha jpg

Note

  • The putpixel() function directly modifies the image in memory. It is useful for making small modifications to individual pixels.

  • For large-scale pixel operations or more complex manipulations we have to consider using other Pillow functions that operate on larger regions or entire images for better performance.

Composite Images with Alpha Channel

The Image.alpha_composite() function is used to composite two images with alpha channels. This function blends the images based on their alpha channels.

Example

In this example we are using the Image.alpha_composite() function for blending two images based on their alpha channels.

from PIL import Image

# Open two images
img1 = Image.open('Images/tp_logo.png')
img2 = Image.open('Images/colordots_2.png')

# Composite the images
composite = Image.alpha_composite(img1, img2)

# Display the result
composite.show()

Input Images −

colordots_2 jpg tp_logo jpg

Output alpha composited image −

composite_image jpg

Saving Images with Alpha Channel

To preserve transparency, save the image in a format that supports alpha channels such as PNG. Formats like JPEG do not support alpha channels and will discard transparency information. We can use the save() function available in pillow.

Example

In this example we are using the Image.save() function for saving an image with alpha channel.

from PIL import Image

# Create a new image with alpha channel
new_img = Image.new('RGBA', (700, 300), (255, 0, 0, 128)) 

# Save the image with alpha channel
new_img.save("output Image/new_img.png", "PNG")
print("The image with alpha channel is saved.")

After executing the above code, you will find the resulting PNG file 'new_img.png' saved in the current working directory −

The image with alpha channel is saved.
Advertisements