How to Remove Background from Photos Using Python
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.
Prerequisites
Before we get started, make sure you have the following installed:
pip install rembg pillow
- rembg – Open-source AI-based background remover.
- Pillow – For image handling and saving.
What is Rembg?
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!
Step-by-Step: Remove Background from an Image
Code Example
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}")
Input
A regular .jpg image with a background.
Output
A .png image with the background removed (transparent).

Want to Preview the Result?
You can use Pillow to display the image after processing:
Image.open(output_path).show()
Batch Process Multiple Images
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}")
Use Cases
-
eCommerce product listings (white background)
-
Profile photo cleanups
-
Social media content automation
-
Virtual try-ons and photo editing tools
Bonus: Run It as a Web App
Want to make this usable via browser? Try integrating it with Streamlit or Flask for a quick UI.