BOBOBK

Use Python to set image background color to transparent

TECHNOLOGY

Since the original logo has a white background, and we need to change the white background to transparent, here we use the versatile Python tool for image conversion, specifically the pillow package’s Image.
The PNG format has a fourth parameter in addition to the RGB colors that indicates the transparency of a pixel. For example, (0,0,0,0) means a transparent black. So during image conversion, we can convert that pixel to (0,0,0,0), and the following Python code achieves that.

Steps:

  1. Install the pillow package
  2. Define a function to convert the image background color to transparent PNG format
  3. Perform the image conversion

Install pillow package

First, install the pillow package using pip by running this command in the terminal:

pip install pillow  

Define the function to convert image background to transparent PNG

The function takes the image file path as input, and outputs a transparent image name (without suffix), saving as a PNG image:

import PIL.Image as Image # Import Image module  
def transparent_png(imgfile, out="out"):  
    img = Image.open(imgfile)  
    img = img.convert('RGBA')  
    W, H = img.size  
    white_pixel = (255, 255, 255, 255)  
    for h in range(W):   ### Loop through each pixel in the image  
        for l in range(H):  
            if img.getpixel((h,l)) == white_pixel:  
                img.putpixel((h,l), (0, 0, 0, 0))  
    img.save(out + ".png")  

Image conversion

Locally we have an image called “学会40周年图标.png” with a white background. We want to convert it to transparent background, so let’s start:

transparent_png("学会40周年图标.png", "40")  

Check the effect before and after conversion:
Before:

After:

Related