blog
Want to remove backgrounds from photos without fancy software? In this guide, I’ll show you how to do it with just a few lines of Python! Using the Rembg library and Pillow, you’ll learn to erase backgrounds from any image, batch process multiple photos, and even turn it into a web app. Perfect for eCommerce, social media, or just sprucing up your selfies. Let’s dive in!
Removing backgrounds from images used to be a task reserved for Photoshop pros. But with the help of AI, you can now achieve pro-level background removal with a few lines of Python. Whether you're building an eCommerce tool, an AI photo editor, or just want to clean up your selfies, this guide is for you.
Before we get started, make sure you have the following installed:
pip install rembg pillow
rembg is a powerful background removal tool powered by the U2Net deep learning model. It works on humans, objects, animals, and more—without needing a green screen!
from rembg import remove
from PIL import Image
# Load your image
input_path = "input.jpg"
output_path = "output.png"
# Open the input image
with open(input_path, "rb") as input_file:
input_data = input_file.read()
# Remove the background
output_data = remove(input_data)
# Save the output
with open(output_path, "wb") as output_file:
output_file.write(output_data)
print(f"Background removed! Saved to {output_path}")
A regular .jpg image with a background.
A .png image with the background removed (transparent).
You can use Pillow to display the image after processing:
Image.open(output_path).show()
Got a folder full of images?
import os
input_folder = "photos"
output_folder = "output"
os.makedirs(output_folder, exist_ok=True)
for filename in os.listdir(input_folder):
if filename.endswith(".jpg") or filename.endswith(".png"):
input_path = os.path.join(input_folder, filename)
output_path = os.path.join(output_folder, filename.replace(".jpg", ".png"))
with open(input_path, "rb") as input_file:
input_data = input_file.read()
output_data = remove(input_data)
with open(output_path, "wb") as output_file:
output_file.write(output_data)
print(f"Processed: {filename}")
eCommerce product listings (white background)
Profile photo cleanups
Social media content automation
Virtual try-ons and photo editing tools
Want to make this usable via browser? Try integrating it with Streamlit or Flask for a quick UI.
One-stop solution for next-gen tech.