Last Updated on 2021-10-13 by Clay
If we want to convert a picture background into transparent, we can use the Pillow package in Python to do it.
If you want to know more how to use Pillow module, you can refer to here: https://pillow.readthedocs.io/en/3.0.x/handbook/tutorial.html
Convert the background of the picture to transparent
Assume I have a picture as follows:
It is a picture in .jpg format.
As we can see, most of the background color is white color (rgb(255, 255, 255)). So in below, we use the Pillow package to perform conversion processing.
If it is the first time to use Pillow, use the following command to install it:
pip3 install pillow
After the installation is over, let's look at an example:
# -*- coding: utf-8 -*-
from PIL import Image
image = Image.open('input.jpg')
print(image)
print(image.mode)
Output:
<PIL.Image.Image image mode=RGBA size=626x417 at 0x179240973C8>
RGB
We can see that this is a file of PIL.Image.Image
data type, and the mode of this file is "RGB".
To make the image background transparent, we need to change "RGB" to "RGBA" first. RGBA stands for Red, Green, Blue and Alpha channel.
Alpha channel stands for transparency. This is why we need to convert to this format.
image = image.convert('RGBA')
print(image.mode)
Output:
RGBA
Then we first take out the pixel value of this picture and determine whether the pixel is white (255, 255, 255):
# Transparency
newImage = []
for item in image.getdata():
if item[:3] == (255, 255, 255):
newImage.append((255, 255, 255, 0))
else:
newImage.append(item)
image.putdata(newImage)
As you can see, I replaced all dots with pixel values (255, 255, 255) with transparent. Of course, you can set what color you want to convert here.
image.save('output.png')
Finally, remember to save the picture in PNG format. JPG format does not seem to support transparent backgrounds.
The background of this one is already transparent. Of course, if the background is all white, there is no obvious difference, hahaha.
Complete code
# -*- coding: utf-8 -*-
from PIL import Image
image = Image.open('input.jpg')
image = image.convert('RGBA')
print(image.mode)
# Transparency
newImage = []
for item in image.getdata():
if item[:3] == (255, 255, 255):
newImage.append((255, 255, 255, 0))
else:
newImage.append(item)
image.putdata(newImage)
image.save('output.png')
print(image.mode, image.size)
The above is how to use python package pillow to convert the image background into transparent.
References
- https://stackoverflow.com/questions/8376359/how-to-create-a-transparent-gif-or-png-with-pil-python-imaging
- https://www.geeksforgeeks.org/create-transparent-png-image-with-python-pillow/
Thank you! My high school code club is creating a game and I needed to rotate a sprite so the movement seemed more natural. The rotation left a non-transparent background and your walk through let me progress in the project.
Thank you 🙂
You are welcome =)
this was helpful, thank you!