Skip to main content

Python Background Remover

·688 words·4 mins· loading · loading ·
Your Name
Author

Deepak

I don't suffer from autism, I enjoy every second of it.

We’ve all been there - you need a clean, professional image without its background, and you’re faced with a maze of disappointing options:

  • Paid Subscriptions: $9.99 to $29.99 per month
  • Free Tools: Watermarked or low-resolution results
  • Online Editors: Slow, clunky, privacy concerns
  • Mobile Apps: Limited functionality, aggressive ads

Our Solution: A Python-Powered Background Remover
#

Using python we can create a simple background with interactive UI in twenty lines of code!

To get started install the following dependencies using pip, pip is a standard installer for python used to manage various python packages and dependencies, it also allows users to easily install, upgrade various packages and libraries.

For this project we’ll be needing the following packages:

  • Rembg, for removing the background of an image
  • Streamlit, for creating the UI
  • Pillow(PIL), for opening the image in python
  • Os, for cleanup
  • Additionally we’ll also use the onnxruntime library as rembg won’t run without this library

To install these packages we’ll first create a virtual environment to create a virtual environment open a powershell window and enter the following in commands:

> mkdir bg-remover #creating a folder
> cd bg-remover #moving into that folder
> python -m venv . #creating a virtual environment inside that folder
> source bin/activate #activating the virtual environment
> pip install rembg streamlit pillow onnxruntime #installing the packages

After installing the required packages create a main.py where the contents of our code will reside, after creating the file open it with your text editor of choice, i’ll be using vscode

> code main.py #this will create and open the file in vscode

Step-by-Step Code Breakdown
#

  1. Setting Up the Basics
import rembg
import streamlit as st
from PIL import Image

These imports bring in all the necessary tools for our project.

  1. Creating the User Interface
st.set_page_config(page_title="BG remover")
st.title("Background remover")

Here we are setting up a title for our page using st.set_page_config and the main title to be displayed on the screen using st.title

  1. Image Upload Magic
image = st.file_uploader("Upload an image")

Using the st.file_uploder we are creating a file upload button. This single line creates an upload button. Magic, right?

  1. Processing the Image
if image:
    # Save uploaded image
    with open(image.name,'wb') as f:
        f.write(image.getbuffer())
        # Show success message
        st.success("File uploaded sucessfully")
        st.write(image.name)
        # Open and process image
        img = Image.open(image.name)
        outImage = rembg.remove(img)

Here, we are checking if an image is uploaded or not, saving the image to local file, displaying a success message if the image is uploaded, if the image is uploaded the program opens the image and removes background using remb

  1. Display
    try:
        st.image(outImage) # Show processed image
    except:
        st.warning("An error occured")

We are almost done with the code, here the program will attempt to display processed image using st.image, and shows warning if any error occurs

Full code
#

import rembg
import streamlit as st
from PIL import Image

st.set_page_config(page_title="BG remover")
st.title("Background remover")

image = st.file_uploader("Upload an image")
if image:
    with open(image.name,'wb') as f:
        f.write(image.getbuffer())
        st.success("File uploaded sucessfully")
        st.write(image.name)
        img = Image.open(image.name)
        outImage = rembg.remove(img)
    try:
        st.image(outImage)
    except:
        st.warning("An error occured")

Save the file and run the code using

> streamlit run main.py

#output
You can now view your Streamlit app in your browser.

  Local URL: http://localhost:8501
  Network URL: http://192.168.1.9:8501 #open the URL in your browser if it           doesn't open automatically

image.png

You should see the following window

Now let’s upload an image and see if our program can remove the background or not, you can save the image by right clicking on it.

image.png

Before VS After
#

Before

image.png

After
image.png

We can see that the background has been removed!!
What we’ve explored today is more than just a script - it’s a gateway into the fascinating world of Python image processing. This simple background removal tool represents something much larger: the power of technology to solve real-world problems with just a few lines of code. Remember, every complex technology starts with a simple idea and curiosity. Today’s experiment could be tomorrow’s groundbreaking application. Don’t just read code - experiment, break things, rebuild, and most importantly, enjoy the process!
Happy Coding!