Remove Background with Python
Complete guide to removing image backgrounds with Python. No ML setup, no GPU, no dependencies beyond requests. Works with Django, Flask, FastAPI, and scripts.
Python examples — copy and go
Each example is self-contained. Copy the one that matches your use case.
Quick start
The simplest possible example. Three lines to remove a background.
import requests
response = requests.post(
"https://pixelpanda.ai/api/v1/remove-background",
headers={"Authorization": "Bearer pk_live_your_api_key"},
files={"file": open("product.jpg", "rb")}
)
data = response.json()
print(data["image_url"]) # Transparent PNG URL
print(data["credits_remaining"]) # Credits left on your accountDownload the result
Fetch the transparent PNG and save it to disk.
import requests
API_KEY = "pk_live_your_api_key"
API_URL = "https://pixelpanda.ai/api/v1/remove-background"
def remove_bg(image_path: str, output_path: str) -> str:
"""Remove background and save the transparent PNG locally."""
with open(image_path, "rb") as f:
resp = requests.post(
API_URL,
headers={"Authorization": f"Bearer {API_KEY}"},
files={"file": f}
)
resp.raise_for_status()
data = resp.json()
# Download the transparent PNG
img_resp = requests.get(data["image_url"])
with open(output_path, "wb") as out:
out.write(img_resp.content)
return data["image_url"]
# Usage
url = remove_bg("product.jpg", "product_nobg.png")
print(f"Saved to product_nobg.png ({url})")Process an entire folder
Loop through a directory of images and remove all backgrounds.
import os
import requests
import time
API_KEY = "pk_live_your_api_key"
API_URL = "https://pixelpanda.ai/api/v1/remove-background"
input_dir = "products/"
output_dir = "products_nobg/"
os.makedirs(output_dir, exist_ok=True)
files = [f for f in os.listdir(input_dir) if f.lower().endswith((".jpg", ".jpeg", ".png", ".webp"))]
print(f"Processing {len(files)} images...")
for i, filename in enumerate(files, 1):
input_path = os.path.join(input_dir, filename)
output_path = os.path.join(output_dir, filename.rsplit(".", 1)[0] + ".png")
with open(input_path, "rb") as f:
resp = requests.post(
API_URL,
headers={"Authorization": f"Bearer {API_KEY}"},
files={"file": f}
)
if resp.status_code == 200:
data = resp.json()
img = requests.get(data["image_url"])
with open(output_path, "wb") as out:
out.write(img.content)
print(f"[{i}/{len(files)}] {filename} -> {output_path}")
else:
print(f"[{i}/{len(files)}] {filename} FAILED: {resp.text}")
time.sleep(0.5) # Be nice to the API
print(f"Done! {len(files)} images processed.")Error handling
Production-ready code with retries and error handling.
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
API_KEY = "pk_live_your_api_key"
API_URL = "https://pixelpanda.ai/api/v1/remove-background"
# Set up retry logic
session = requests.Session()
retries = Retry(total=3, backoff_factor=1, status_forcelist=[429, 500, 502, 503])
session.mount("https://", HTTPAdapter(max_retries=retries))
def remove_bg_safe(image_path: str) -> dict:
"""Remove background with error handling and retries."""
try:
with open(image_path, "rb") as f:
resp = session.post(
API_URL,
headers={"Authorization": f"Bearer {API_KEY}"},
files={"file": f},
timeout=30
)
if resp.status_code == 200:
return resp.json()
elif resp.status_code == 401:
raise Exception("Invalid API key")
elif resp.status_code == 402:
raise Exception("Out of credits — top up at pixelpanda.ai/pricing")
elif resp.status_code == 413:
raise Exception("Image too large — max 10MB")
else:
raise Exception(f"API error {resp.status_code}: {resp.text}")
except requests.exceptions.Timeout:
raise Exception("Request timed out — try again")
except requests.exceptions.ConnectionError:
raise Exception("Could not connect to API")
# Usage
try:
result = remove_bg_safe("product.jpg")
print(f"Success: {result['image_url']}")
print(f"Credits remaining: {result['credits_remaining']}")
except Exception as e:
print(f"Error: {e}")Add a white background (PIL/Pillow)
Remove the background, then composite onto white — perfect for Amazon/eBay listings.
import requests
from PIL import Image
from io import BytesIO
API_KEY = "pk_live_your_api_key"
# Step 1: Remove background via API
with open("product.jpg", "rb") as f:
resp = requests.post(
"https://pixelpanda.ai/api/v1/remove-background",
headers={"Authorization": f"Bearer {API_KEY}"},
files={"file": f}
)
data = resp.json()
# Step 2: Download the transparent PNG
img_resp = requests.get(data["image_url"])
foreground = Image.open(BytesIO(img_resp.content)).convert("RGBA")
# Step 3: Create white background and composite
white_bg = Image.new("RGBA", foreground.size, (255, 255, 255, 255))
result = Image.alpha_composite(white_bg, foreground)
# Step 4: Save as JPEG (Amazon requirement)
result.convert("RGB").save("product_white_bg.jpg", quality=95)
print("Saved product_white_bg.jpg with pure white background")Django view
Accept a user upload in Django and return the processed image.
# views.py
import requests
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings
@csrf_exempt
def remove_background(request):
if request.method != "POST":
return JsonResponse({"error": "POST required"}, status=405)
image = request.FILES.get("image")
if not image:
return JsonResponse({"error": "No image uploaded"}, status=400)
resp = requests.post(
"https://pixelpanda.ai/api/v1/remove-background",
headers={"Authorization": f"Bearer {settings.PIXELPANDA_API_KEY}"},
files={"file": (image.name, image.read(), image.content_type)}
)
if resp.status_code == 200:
return JsonResponse(resp.json())
return JsonResponse({"error": "Processing failed"}, status=500)
# urls.py
# path("api/remove-bg/", views.remove_background),Flask route
Same thing in Flask — accept upload, call API, return result.
from flask import Flask, request, jsonify
import requests as http_requests
import os
app = Flask(__name__)
API_KEY = os.environ["PIXELPANDA_API_KEY"]
@app.route("/remove-bg", methods=["POST"])
def remove_bg():
image = request.files.get("image")
if not image:
return jsonify(error="No image uploaded"), 400
resp = http_requests.post(
"https://pixelpanda.ai/api/v1/remove-background",
headers={"Authorization": f"Bearer {API_KEY}"},
files={"file": (image.filename, image.read(), image.mimetype)}
)
if resp.status_code == 200:
return jsonify(resp.json())
return jsonify(error="Processing failed"), 500Response format
Every successful request returns this JSON. The image_url is a permanent link to the transparent PNG.
{
"success": true,
"image_url": "https://pub-xxx.r2.dev/results/abc123.png",
"credits_remaining": 199
}| Field | Type | Description |
|---|---|---|
| success | boolean | true if background was removed successfully |
| image_url | string | URL to the transparent PNG result (permanent, hosted on CDN) |
| credits_remaining | integer | How many credits are left on your account |
Error codes
| Code | Meaning |
|---|---|
| 200 | Success — image_url contains the transparent PNG |
| 400 | Bad request — invalid image format or missing file |
| 401 | Unauthorized — invalid or missing API key |
| 402 | Payment required — out of credits |
| 413 | Image too large — max 10MB |
| 429 | Rate limited — too many requests |
| 500 | Server error — retry the request |
Common issues
Common questions
Start removing backgrounds with Python
280 credits/week for $7.99. Copy the code above and go.
Get Your API Key