DEV Community

0xkoji
0xkoji

Posted on

Only 7 lines python code to remove background with rembg

GitHub logo danielgatis / rembg

Rembg is a tool to remove images background

Rembg

Downloads License Hugging Face Spaces Streamlit App

Rembg is a tool to remove images background.

example car-1 example car-1.out example car-2 example car-2.out example car-3 example car-3.out

example animal-1 example animal-1.out example animal-2 example animal-2.out example animal-3 example animal-3.out

example girl-1 example girl-1.out example girl-2 example girl-2.out example girl-3 example girl-3.out

example anime-girl-1 example anime-girl-1.out example anime-girl-2 example anime-girl-2.out example anime-girl-3 example anime-girl-3.out

If this project has helped you, please consider making a donation.

Sponsor










Unsplash


PhotoRoom Remove Background API


https://photoroom.com/api



Fast and accurate background remover API


Requirements

python: >3.7, <3.13

Installation

If you have onnxruntime already installed, just install rembg:

pip install rembg # for library
pip install "rembg[cli]" # for library + cli
Enter fullscreen mode Exit fullscreen mode

Otherwise, install rembg with explicit CPU/GPU support.

CPU support:

pip install rembg[cpu] # for library
pip install "rembg[cpu,cli]" # for library + cli
Enter fullscreen mode Exit fullscreen mode

GPU support:

First of all, you need to check if your system supports the onnxruntime-gpu.

Go to https://onnxruntime.ai and check the installation matrix.

onnxruntime-installation-matrix

If yes, just run:

pip install "rembg[gpu]" # for library
pip install "rembg[gpu,cli]" # for library + cli
Enter fullscreen mode Exit fullscreen mode

Usage as a cli

After the installation step you can use rembg just typing rembg




We can run gpu version on Google colab

!pip install rembg[gpu]
Enter fullscreen mode Exit fullscreen mode

If you want to run the script on your local machine without a gpu, you will need to install 2 packages. If you have OpenCV, you can use it instead of Pillow.

pip install rembg 
pip install -U Pillow
Enter fullscreen mode Exit fullscreen mode
from rembg import remove
from PIL import Image

input_path = 'input.jpg' # input image path
output_path = 'output.png' # output image path

input = Image.open(input_path) # load image
output = remove(input) # remove background
output.save(output_path) # save image
Enter fullscreen mode Exit fullscreen mode

Incredibly easy!!!

Top comments (1)

Collapse
 
samy profile image
Samuel Urah Yahaya

Nice one... Hope to try it out