In this article, we will learn how to make an image background transparent by processing and modifying its pixel values using Python's Pillow library (Python Imaging Library).
Pillow supports RGBA images, where the extra Alpha channel controls pixel transparency. You can install Pillow using the following pip command:
pip install pillow
Approach
- Read the image using Pillow.
- Convert the image to RGBA format (Red, Green, Blue, Alpha).
- Read pixel data.
- Detect background-colored pixels (for example, white).
- Set their alpha value to 0.
- Save the result as a PNG file (PNG supports transparency).
Python Implementation
Input:
👁 ImageOutput:
Explanation:
- convert("RGBA"): adds an alpha channel so transparency can be stored.
- getdata(): returns all pixel values.
- Loop reads each pixel as (r, g, b, a).
- White pixels are detected using RGB values (255,255,255).
- (255,255,255,0): sets alpha to 0 → fully transparent.
- Other pixels are kept unchanged.
- putdata(): writes modified pixels back.
Related Articles: