Effortless Image Background Removal App with Less Than 20 Lines of Python
In this post, I will introduce you to an application that can remove background from an image. The application is on Huggingface space.
RemoveBG - a Hugging Face Space by baxin
Discover amazing ML apps made by the community
huggingface.co
Requirements
- python ( Gradio requires python 3.8 or higher, I used 3.10.6)
- Gradio
- rembg
- Huggingface account (if you want to host the app on Huggingface space)
Install Packages
First, we will need to install packages.
pip install gradio rembg
Write a python script
As you can see (embedded tweet), the application is very simple. It has two big boxes to display images, one is for our original image and the other is for the image without its background. As title says, the code is very short 😁
First two lines are importing packages.
remove_bg is a function to remove background from an image. It just calls remove function from rembg.
demo(you can change the name whatever you like) is the interface part.
from rembg import remove
import gradio as gr
def remove_bg(input_image):
output = remove(input_image)
return output
demo = gr.Interface(
remove_bg,
gr.Image(type="pil"),
"image",
title="Remove Image BG",
)
if __name__ == "__main__":
demo.launch()
Now we can run the application.
python app.py
You will see the following when clicking the url that Gradio displays in your Terminal.
Push The Application to Huggingface space
- create a space
- select Gradio
- push
app.py
andrequirements.txt
Huggingface will show you how to push the code to your repository.
The difference between your local and Huggingface space
is missingrequirements.txt.
When you select Gradio
space on Huggingface
, the package will be installed automatically, but the space is missing rembg.
requirements.txt
needs only 1 line like below.
rembg
Here is my repository for this application.