In this tutorial, you will learn how to remove background from an image using Python. We will use the rembg library to remove the background from an image and make a PNG image with a transparent background.
We will use the rembg and Pillow libraries to remove the background from an image.
Install rembg library
pip install rembg
The rembg library uses the u2net model to remove the background from an image. The u2net model is a deep learning model that is trained to remove the background from an image.
This library directly depends on the onnxruntime library. Therefore, we can only update the Python version when onnxruntime provides support for that specific version.
Install Pillow library
pip install pillow
Remove Background from Image using Python
from rembg import remove
from PIL import Image
image_path = 'cat.jpg'
input = Image.open(image_path)
output = remove(input)
output.save('cat_transparent.png', 'PNG')
After removing the background from the image, the output image will be saved with a transparent background.

Before Removing Background

After Removing Background
In the above code, we first import the remove function from the rembg library and the Image class from the Pillow library.
We then open the image using the Image.open method and pass the image path to it.
We then call the remove function and pass the input image to it. This function will remove the background from the image and return the image with a transparent background.
We then save the output image using the save method and pass the output image path and the image format to it.
Now, you can run the above code and it will remove the background from the image and save the output image with a transparent background.
That’s it. You have successfully removed the background from an image using Python.
I hope this tutorial helps you to remove the background from an image using Python. If you have any questions, please feel free to ask in the comments section below.
Happy Coding! 🚀




