Table of Contents

There may have been a situation when you wanted to remove background from an image but either you found a bad free online tool or a paid one. Learn how to generate high quality images after removing the background of any image. we will be using rembg tool to power this functionality

Prerequsitive

Create new project

Bash
mkdir remove-bg
cd remove-bg
poetry init

In the remove-bg folder a poetry project will be created. when you will use the poetry init command then it will ask some question. Choose the default options

Install the dependencies

Bash
peotry shell

First activate the virtual environment such that all the files related to this project will be at one place and will not interfere with other projectes.

Bash
poetry add rembg

Rembg is a tool to remove images background.

Bash
poetry add onnxruntime

ONNX Runtime is a cross-platform inference and training machine-learning accelerator. we will be using a machine learning model to remove the background

Bash
poetry add gradio

Gradio is the fastest way to demo your machine learning model with a friendly web interface so that anyone can use it, anywhere!

Code to Remove background from your image

create a new file main.py in the current folder

Bash
touch main.py

We will be using the Gradio module to create the user interface for remove background tool

Python
import gradio as gr
from rembg import remove
from rembg.session_factory import new_session
from PIL import Image
import io

# Create a custom session with a better model
session = new_session(model_name="isnet-general-use")

def remove_bg(image_path):
    with open(image_path, "rb") as f:
        input_bytes = f.read()

    # Use the custom session for background removal
    result_bytes = remove(input_bytes, session=session)

    return Image.open(io.BytesIO(result_bytes))

def main():
    gr.Interface(
        fn=remove_bg,
        inputs=gr.Image(type="filepath", label="Upload Image"),
        outputs=gr.Image(label="Background Removed (ISNet)"),
        title="Background Remover - High Quality (ISNet)",
    ).launch()

if __name__ == "__main__":
    main()
  • we are using isnet-general-use model which is best suited for removing background from human interface

Start the remove background server

Bash
python main.py

When you start the server and the model is not present locally then it will try to download that from the web

The Gradio tool will start a http server on port 7860

Bash
(remove-bg-py3.12) ➜  remove-bg python main.py
* Running on local URL:  http://127.0.0.1:7860
* To create a public link, set `share=True` in `launch()`.

Open the application in browser to remove background

Upload a picture and click on submit to remove the background

remove background from image

References

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *