Hello Learners…
Welcome to the blog…
Table Of Contents
- Introduction
- Image Background Removal API With Python And FastAPI
- How to run the FastAPI?
- Call FastAPI Using Postman
- Image Background Removal Streamlit Demo
- Summary
- References
Introduction
In this post, we are going to create an Image Background Removal API With Python And FastAPI.
This is a small project we can say that we created using python libraries and Fast API which removes the background of images using deep learning models.s
Image Background Removal API With Python And FastAPI
Here we create a FastAPI to remove the Background of Images using Python And pre-trained AI/ML models.
which accepts images with .jpg, .jpeg, and .png extensions.
There is one python library or we can say a project or a tool that can help us to remove the background of an image file.
It uses the u2net: salient object detection(SOD) a deep learning model.
How to run the FastAPI?
First, clone the GitHub repository,
Then go to the directory “image_background_removal_python_fastapi“
1. Create a python virtual environment and activate it:
python3 -m venv venv
source venv/bin/activate
2. install all the required libraries using requirements.txt
pip install -r requirements.txt
4. run the API
python3 app.py
5. open the URL in the browser
http://127.0.0.1:8000/docs
6. Click On the POST method with the ‘image_background_remove’ function name.
7. Click on ‘Try it out‘.
Here we can see the input parameter where we have to pass which model we have to select and an image file.
8. Upload an Image and Execute the FastAPI
It will save our uploaded images into ‘./images/uploaded_images’ and after image processing of removing the background it saves the output images into ‘./images/removed_bg’
This is how the Image background removal Python FastAPI works.
Call FastAPI Using Postman
Open Postman, Enter the URL with the function name after that pass the parameters as the below image, and then send the request to the FastAPI and get the response.
Here we get the ‘file_base64’ which is the binary format of the removed background image.
Python Code Of Full API
app.py
from fastapi import FastAPI,UploadFile, File
import uvicorn
import os
from datetime import datetime
from src import with_rembg
import base64
app = FastAPI()
@app.get("/")
def hello():
return {"API":"API is working fine"}
@app.post("/image_backgroung_remove")
async def upload_image(model_type:str ="1",img_file:UploadFile =File(...)):
"""
Model Type: \n
1 - U2net (175 MB) - This model is based on the U2-Net architecture, which is a deep neural network designed for salient object detection \n
2 - U2netp (4.7 MB) - It an improved version of U2-Net, designed to be more efficient and faster while maintaining good performance. \n
\n\n
Args: \n
model_type (str): 1 or 2.\n
img_file (File): uploaded image \n
Returns: \n
dict: A dictionary containing the message and base64 of an image. \n
"""
today_date=str(datetime.now().date())
current_time=str(datetime.now().strftime("%H_%M_%S"))
#image extension validation
if '.jpg' in img_file.filename or '.jpeg' in img_file.filename or '.png' in img_file.filename:
#give input and output file names
file_save_path="./images/uploaded_images/"+today_date+"/"+current_time+"_"+img_file.filename
file_output_path="./images/removed_bg/"+today_date+"/"+current_time+"_removed_bg_"+img_file.filename
#check images directory exists or not, if not then create.
if os.path.exists("./images/uploaded_images/"+today_date+"/") == False:
os.makedirs("./images/uploaded_images/"+today_date+"/")
#check removed_bg directory exists or not, if not then create.
if os.path.exists("./images/removed_bg/"+today_date+"/") == False:
os.makedirs("./images/removed_bg/"+today_date+"/")
#save uploaded file into the directory
with open(file_save_path, "wb") as f:
f.write(img_file.file.read())
#Check File is successfully saved and exists on the given path or not
if os.path.exists(file_save_path):
result=with_rembg.remove_background(file_save_path,file_output_path,model_type)
if result['status'] == "success":
# Open the PNG image file in binary mode
with open(result['file_out_path'], 'rb') as image_file:
# Read the image data
image_data = image_file.read()
# convert the image data in base64 format
base64_encoded = base64.b64encode(image_data)
return {"message": f"Image saved at {result['file_out_path']} successfully","status":"success","file_base64":base64_encoded}
else:
return {"error":result['error'],"status":"fail"}
else:
return {"error":"Image Not saved !!!","status":"fail"}
else:
return {"error": "File Type is not valid please upload only jpg,jpeg and png","status":"fail"}
if __name__=="__main__":
uvicorn.run(app,)
./src/with_rembg.py
import rembg
from PIL import Image
import os
from rembg import new_session
def remove_background(image_path,output_path,model_type):
try:
# Load the image
image = Image.open(image_path)
# Remove the background
if model_type=="1":
model_name="u2net"
elif model_type == "2":
model_name="u2netp"
else:
return {"error":"model type is not specified correctly use 1 - u2net and 2 - u2netp","status":"fail"}
output = rembg.remove(image,session = new_session(model_name))
fname,fextension=os.path.splitext(output_path)
output_path=output_path.replace(fextension,".png")
# Save the output image
output.save(output_path,format="PNG")
return {"status":"success","file_out_path":output_path}
except Exception as e:
return {"error":str(e),"message":"getting error in removing backgroung using rembg","status":"fail"}
Image Background Removal Streamlit Demo:
Now we know how the Image Background Removal API With Python And FastAPI works. So for the demo purpose, we created a Streamlit Web App.
To run the Sreamlit Demo Web App Follow the below commands,
First, check the ‘streamlit_app_demo.py’ file is exists.
Run the streamlit file.
streamlit run streamlit_app_demo.py
Open the below URL in your browser if it does automatically not open.
http://localhost:8501/
We can see this below.
Now click on the ‘Image Background Removal’ radio button
Now upload your image and wait for the output.
So this is how the streamlit web app demo works.
PseudoCode (streamlit_app_demo.py):
import streamlit as st
from src import with_rembg
from datetime import datetime
import os
def main():
st.title("Image Background Removal")
# Sidebar
st.sidebar.header("Navigation")
page = st.sidebar.radio("Go to", ("Home", "Image Background Removal"))
if page == "Home":
st.write("Welcome to the Image Background Removal App.")
st.write("Upload an image, and we'll remove the background for you.")
elif page == "Image Background Removal":
model_type=st.radio("Model name", ("u2net", "u2netp"))
if model_type=="u2net":
model_type="1"
if model_type=="u2netp":
model_type="2"
img_file = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])
if img_file:
today_date = str(datetime.now().date())
current_time = str(datetime.now().strftime("%H_%M_%S"))
print(img_file.type)
# Image extension validation
if img_file.type.startswith('image/'):
# Give input and output file names
#give input and output file names
file_save_path="./images/uploaded_images/"+today_date+"/"+current_time+"_"+img_file.name
file_output_path="./images/removed_bg/"+today_date+"/"+current_time+"_removed_bg_"+img_file.name
filename=current_time+"_removed_bg_"+img_file.name
# Check images directory exists or not, if not then create.
if not os.path.exists(f"./images/uploaded_images/{today_date}/"):
os.makedirs(f"./images/uploaded_images/{today_date}/")
# Check removed_bg directory exists or not, if not then create.
if not os.path.exists(f"./images/removed_bg/{today_date}/"):
os.makedirs(f"./images/removed_bg/{today_date}/")
if '.jpg' or '.jpeg' in filename.lower():
fname,fextension=os.path.splitext(filename)
filename=filename.replace(fextension,".png")
print(filename)
# Save uploaded file into the directory
with open(file_save_path, "wb") as f:
f.write(img_file.read())
# Check if the file is successfully saved and exists on the given path or not
if os.path.exists(file_save_path):
result = with_rembg.remove_background(file_save_path, file_output_path,model_type)
if result['status'] == "success":
st.image(result['file_out_path'], use_column_width=True)
st.success("Image saved successfully.")
with open(result['file_out_path'], "rb") as file:
file_contents = file.read()
st.download_button(label="Download Image",data=file_contents,file_name=filename)
else:
st.error("Image not saved.")
else:
st.error("Image not saved.")
else:
st.error("File type is not valid. Please upload only jpg, jpeg, and png.")
if __name__ == "__main__":
main()
Summary
This is the small Python FastAPI that we can use and improve based on our requirements or datasets and use it.
For Other Small Projects:
For Image Processing,
Happy Learning And Keep Learning…
Thank You…