Create Your Own Photo Background Remover App

Johnny Chan
4 min readOct 20, 2023

--

In today’s digital age, privacy matters more than ever. While there are numerous online services offering photo editing and processing, each upload potentially risks exposing your personal photos to unknown parties. Imagine harnessing advanced photo processing without the privacy concerns of third-party platforms. By building your own background remover app, you can keep your photos secure, ensuring they never leave the confines of your device or designated server.

In this guide, I’ll walk you through creating a photo background remover application using Python and Streamlit. You can deploy it to your own server or run it locally. Dive in, prioritize your privacy, and gain the power of custom photo editing!

1. Requirements

Install the following two packages in your terminal or command prompt. For example, pip install backgroundremover==0.1.9

backgroundremover==0.1.9
streamlit==1.16.0

2. Import Necessary Libraries

import streamlit as st
import os
import subprocess
from PIL import Image
import shutil

Here, we’re importing:

  • streamlit for our app interface.
  • os for interacting with the operating system.
  • subprocess to run shell commands.
  • PIL (Python Imaging Library) for image processing.
  • shutil for high-level file operations.

3. Define Helper Functions

def bgr(img_path, output_path):
'''background remove'''
res = subprocess.run(
'backgroundremover -i {} -o {}'.format(
img_path, output_path
),
shell = True,
capture_output = True
)

def purge_folder(folder_path):
for f in os.listdir(folder_path):
os.remove(os.path.join(folder_path,f))

def format_file_name(file_name):
fname = file_name.split('.')[0]
ftype = file_name.split('.')[1]
fname2 = ''.join(e for e in fname if e.isalnum())
return fname2 + '.' + ftype

def save_buffered(buffered_file,buffered_folder):
# save the streamlit buffered files to temp folder
if os.path.isdir(buffered_folder) == False:
os.mkdir(buffered_folder)
with open(os.path.join(buffered_folder,buffered_file.name),"wb") as f:
f.write(buffered_file.getbuffer())

bgr function runs a shell command to remove backgrounds from images. It uses an external tool called backgroundremover , which you install in Requirements section. The input image img_path is processed, and the result is saved in output_path.

purge_folder function deletes all files inside the specified folder_path. It's a way to clean up before and after processing images.

format_file_name function ensures that the file name consists of alphanumeric characters. It’s helpful to avoid issues with strange file names.

In save_buffered function, Streamlit handles uploaded files as ‘buffered’ files in memory. This function saves these buffered files to a directory on disk.

4. Set Up Directories

if os.path.isdir('temp'):
pass
else:
os.mkdir('temp')
if os.path.isdir('outputs'):
pass
else:
os.mkdir('outputs')

Before processing, we ensure two folders exist:

  • temp: Where we save the uploaded images.
  • outputs: Where we save the processed images.

5. Streamlit App UI

st.title("Background Remover")
st.markdown('''
This application utilizes deep learning to distinguish
the object from the background of a photo...
''')
example_img = Image.open('images/example_1.jpg')
st.image(example_img)

This sets up the title, a brief description, and an example image on the Streamlit app’s main page. The example_1.jpg is the horse image above.

6. Upload and Process Images

files = st.sidebar.file_uploader(
label="Upload images",
type=['png', 'jpg'],
accept_multiple_files=True
)
btn = st.sidebar.button('Upload')

We provide users with a file uploader in the sidebar where they can upload images (PNG, JPG). After uploading, they can press the ‘Upload’ button to start processing.

When the ‘Upload’ button is pressed, several actions are taken:

  1. Previous images in temp and outputs are deleted.
  2. New images are saved in the temp folder.
  3. Background removal is applied to each image.
  4. Processed images are displayed in the Streamlit app.

7. Download Processed Images

cwd = os.getcwd()
shutil.make_archive(
base_name=cwd + '/outputs',
format='zip',
root_dir=cwd,
base_dir='outputs',
)
with open("outputs.zip", 'rb') as f:
st.sidebar.download_button('Download All', f, file_name='bgr_images.zip')
os.remove('outputs.zip')

Finally, users can download all processed images as a ZIP file.

8. Results

The landing page has a brief introduction. The usage is simple. Drag and drop your photo file or use the Browser files button to select. Then click Upload to start the processing. Let’s use this cute corgi as a test.

After processed, here is what you see, and you can download the photo

Here is the Github repository where you can access the full code.

Deploy with Ease Using Hazl

Ever been fascinated by building your own Background Remover app? How about deploying it? It’s now at your fingertips, thanks to Hazl. Deploying it has never been this straightforward: select your server, and within a mere three minutes, it’s up and running. And the technicalities? We’ve minimized them for you.

At the heart of Hazl lies a mission: to make cloud computing accessible to all. And when we say “all”, we envision a world where cloud computing is as easy for beginners as it is for the pros.

But Hazl isn’t confined to just being a platform. We extend our expertise, offering personalized consultations. Need a custom server? A specific application? We’re here to guide, build, and support.

Dive deeper into what Hazl offers. Visit us at hazl.ca and embark on a seamless cloud computing journey.

--

--

Johnny Chan
Johnny Chan

Written by Johnny Chan

Co-founder of Hazl AI -- a platform for your one-stop AI and cloud services. Visit us at hazl.ca

No responses yet