Effortless Image Background Removal App with Less Than 20 Lines of Python

0𝕏koji
2 min readJan 1, 2024

In this post, I will introduce you to an application that can remove background from an image. The application is on Huggingface space.

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

https://huggingface.co/

  1. create a space
  2. select Gradio
  3. push app.py and requirements.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 Gradiospace 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.

--

--

0𝕏koji

software engineer works for a Biotechnology Research startup in Brooklyn. #CreativeCoding #Art #IoT #MachineLearning #python #typescript #javascript #reactjs