Background Remover Flask App using Python – 2024

Hey guys, in today’s blog we will see how we can build a background remover flask app using Python. So without any further due, let’s do it…

In today’s digital age, images play a vital role in communication and expression. However, sometimes, the background of an image may not be suitable, and removing it can enhance the image’s overall appeal. To cater to this need, we can build a background remover Flask app that can remove the background of any image using Python.

Flask is a micro-framework that allows us to build web applications using Python. It is lightweight and provides an easy-to-use interface for building web applications. In this article, we will create a Flask app that uses the Python Imaging Library (PIL) and rembg python library to remove the background of an image.

Prerequisites

To build the background remover Flask app, we need to have the following prerequisites installed:

  • Python 3
  • Flask
  • PIL (Python Imaging Library)
  • rembg (Python library that removes background)

Result Samples

Example 1:

Background Remover Flask App

Example 2:

Background Remover Flask App

Working of our Background Remover Flask App

Working Flow of our App…

  • In the first step, the extension of the image is checked, and if it is in the allowed extensions list, it is uploaded to the uploads folder.
  • Then in the next step, the uploaded image is read using the PIL module.
  • In the next step, the background of the image is removed using the rembg python library.
  • Then the image with the removed background is stored in the uploads folder.
  • And finally, both the images are displayed on the results page.

Source Code for Background Remover Flask App

NOTE – Before running the app you need to install a Python module called ‘rembg‘. You can install it by running the following command in the terminal…

pip install rembg

app.py

import cv2
import os
from rembg import remove
from PIL import Image
from werkzeug.utils import secure_filename
from flask import Flask,request,render_template

UPLOAD_FOLDER = 'static/uploads'
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg','webp'])

if 'static' not in os.listdir('.'):
    os.mkdir('static')

if 'uploads' not in os.listdir('static/'):
    os.mkdir('static/uploads')

app = Flask(__name__)
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.secret_key = "secret key"

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

def remove_background(input_path,output_path):
    input = Image.open(input_path)
    output = remove(input)
    output.save(output_path)


@app.route('/')
def home():
    return render_template('home.html')

@app.route('/remback',methods=['POST'])
def remback():
    file = request.files['file']
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        rembg_img_name = filename.split('.')[0]+"_rembg.png"
        remove_background(UPLOAD_FOLDER+'/'+filename,UPLOAD_FOLDER+'/'+rembg_img_name)
        return render_template('home.html',org_img_name=filename,rembg_img_name=rembg_img_name)


if __name__ == '__main__':
    app.run(debug=True)

home.html

<!doctype html>
<html lang="en">

<style type='text/css'>
    body {
        background-color: black !important;
        font-family: sans-serif;
        margin-top: 40px;
        margin: 0; 
    }

    .regform {
        width: 800px;
        background-color: #fb2056;
        margin: auto;
        color: #FFFFFF;
        padding: 10px 0px 10px 0px;
        text-align: center;
        border-radius: 15px 15px 0px 0px;

    }

    .main-form {
        width: 800px;
        margin: auto;
        background-color: #fc86a463;
        padding-left: 50px;
        padding-right: 50px;
        padding-bottom: 20px;
        color: #FFFFFF;
    }

    img {
        max-height: 400px;
        max-width: 500px;
        height: auto;
        width: auto;
    }
</style>


<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">

    <title>Remove Background</title>
</head>

<body>

    <div class='regform mt-3'>
        <h1>Remove Background</h1>
    </div>

    <form action='/remback' class='main-form' method="POST" enctype="multipart/form-data">

        <div class='text-center'>
            <input type="file" id="file" name='file' style="margin-top:10px;margin-bottom:10px;">
            <button type='submit' class='btn btn-success'> Remove Background
            </button>
        </div>

    </form>

    {% if rembg_img_name %}
    <div class="row" style="margin-top:10px;margin-bottom:10px;">
        
        <div class="col text-center" style="background-color: #fb2056ba;margin: 50px;border-radius: 20px;padding: 20px;">
            <h2 style="color: #FFFFFF;">Original Image</h2><img src='../static/uploads/{{ org_img_name }}'
                style="display: block;margin-left: auto;margin-right: auto;">
        </div>

        <div class="col text-center" style="background-color: #fb2056ba;margin: 50px;border-radius: 20px;padding: 20px;">
            <h2 style="color: #FFFFFF;">Image with Background Removed</h2><img src='../static/uploads/{{ rembg_img_name }}'
                style="display: block;margin-left: auto;margin-right: auto;">
        </div>
    
    </div>
    {% endif %}

</body>

</html>

Step by Step coding our Background Remover Flask App

Download Source Code

Conclusion

In this article, we have seen how to create a background remover Flask app using Python. We used the Flask micro-framework, Python Imaging Library (PIL), and rembg to process the images. By following these steps, you can build your own Flask app for removing the background of any image.

So this is all for this blog folks. Thanks for reading it and I hope you are taking something with you after reading this and till the next time …

Read my last blog – Youtube Comments Extraction and Sentiment Analysis Flask App

Check out my other machine learning projectsdeep learning projectscomputer vision projectsNLP projects, and Flask projects at machinelearningprojects.net.

Abhishek Sharma
Abhishek Sharma

Started my Data Science journey in my 2nd year of college and since then continuously into it because of the magical powers of ML and continuously doing projects in almost every domain of AI like ML, DL, CV, NLP.

Articles: 520

Subscribe to our Newsletter

Subscribe to our newsletter and receive all latest projects...

Leave a Reply

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