Python Convert Image Background to Transparent: A Step Guide – Python Pillow Tutorial

By | August 30, 2020

Sometimes, we need make the backgroud of an image transparent, how to implement it in python? In this tutorial, we will implement this function using python pillow library.

This tutorial refers:

Python Pillow Change a Specific Color of an Image: A Step Guide

Load an image using python pillow

We can open an image to process first.

from PIL import Image
im = Image.open("file.png")

file.png is:

png rgb mode image

The image mode is RGB.

In order to know how to get the mode of an image, you can check this tutorial.

Python Pillow Get and Convert Image Mode: A Beginner Guide

Convert image mode to RGBA

In order to make the backgroud of an image transparent, we must make its image mode be RGBA, which contains an alpha channel.

img = im.convert("RGBA")

Then we can process this image pixel by pixel.

Convert the backgroud of an image transparent

The backgroud color of file.png is white(255, 255, 255). We should make all pixels with white color transparent.

width = img.size[0] 
height = img.size[1] 
for x in range(0,width):# process all pixels
    for y in range(0,height):
        data = img.getpixel((x, y))
        if (data[0] == 255 and data[1] == 255 and data[2] == 255 ):
            img.putpixel((x, y), (255, 255, 255, 0))

img.putpixel((x, y), (255, 255, 255, 0)) can make a pixel transparent.

Then we can display the processed image.

python convert the backgroud of an image to be transparent

Leave a Reply

Your email address will not be published. Required fields are marked *