In this article, I will explain to you how to easily install and configure the Rembg library for Python to remove the background from an image.
1. Install PyTorch
If you are using anaconda, you can install Pytorch with the following command
conda install pytorch torchvision torchaudio cpuonly -c pytorch
Alternatively, you may install Pytorch using pip with the following command:
pip install torch==1.7.1+cpu torchvision==0.8.2+cpu -f https://download.pytorch.org/whl/torch_stable.html
Note: for this tutorial and explained as well in the github repository, we are using Pytorch for CPU. If you have a graphic card available in the server, you may install Pytorch with support for CUDA. For more information about Pytorch,
2. Install RemBG
RemBG is a tool to remove the background of any image. This library uses the U2-Net under the hood for pattern recognition (“U^2-Net: Going Deeper with Nested U-Structure for Salient Object Detection.”). To install this package in your system, use pip:
pip install rembg
3. Using the library
After installing the Rembg library, you will be able to choose either directly from the command line or inside a simple python script. Note that when running for first time, the model will be downloaded so it will take a while, once it finishes, the background removal doesn’t take that much for every image. Rembg will be available globally in your environment.
Background removal through the CLI
The fastest way to test if the library is working is to simply use a remote image, the following command will use a Wikipedia image of Julian Casablancas:
curl -s https://upload.wikimedia.org/wikipedia/commons/thumb/e/ec/Julian_Casablancas_%40_Lollapalooz