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 Downloads Downloads License Hugging Face Spaces

Rembg is a tool to remove images background. That is it.

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

Installation

CPU support:

pip install rembg
Enter fullscreen mode Exit fullscreen mode

GPU support:

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

Usage as a cli

Remove the background from a remote image

curl -s http://input.png | rembg i > output.png
Enter fullscreen mode Exit fullscreen mode

Remove the background from a local file

rembg i path/to/input.png path/to/output.png
Enter fullscreen mode Exit fullscreen mode

Remove the background from all images in a folder

rembg p path/to/input path/to/output
Enter fullscreen mode Exit fullscreen mode

Usage as a server

Start the server

rembg s
Enter fullscreen mode Exit fullscreen mode

And go to:

http://localhost:5000/docs

Image with background:

https://upload.wikimedia.org/wikipedia/commons/thumb/9/9a/Gull_portrait_ca_usa.jpg/1280px-Gull_portrait_ca_usa.jpg

Image without background:

http://localhost:5000/?url=https://upload.wikimedia.org/wikipedia/commons/thumb/9/9a/Gull_portrait_ca_usa.jpg/1280px-Gull_portrait_ca_usa.jpg

Also you can send the file as a FormData (multipart/form-data):

<form
    action="http://localhost:5000"
    method="post"
    enctype="multipart/form-data"
>
    <input type="file" name="file" />
    <input type="submit" value="upload" />
</form>
Enter fullscreen mode Exit fullscreen mode

Usage

…

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 (0)

Join us at DEV Want to join the conversation?
Β 

It's easy! Become a DEV member to follow this post, comment, and more.