Python + PixelPanda API

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.

$ pip install requests

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 account

Download 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"), 500

Response 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
}
FieldTypeDescription
successbooleantrue if background was removed successfully
image_urlstringURL to the transparent PNG result (permanent, hosted on CDN)
credits_remainingintegerHow many credits are left on your account

Error codes

CodeMeaning
200Success — image_url contains the transparent PNG
400Bad request — invalid image format or missing file
401Unauthorized — invalid or missing API key
402Payment required — out of credits
413Image too large — max 10MB
429Rate limited — too many requests
500Server error — retry the request

Common issues

Getting 401 Unauthorized
Check that your API key starts with pk_live_ and is included in the Authorization header as 'Bearer pk_live_xxx'. Generate a new key from your dashboard if needed.
Getting 402 Payment Required
You're out of credits. Buy more at pixelpanda.ai/pricing — $7.99/week for 280 credits/week (cancel anytime).
Image quality is poor
Upload the highest resolution version of your image. The API accepts up to 10MB. Low-resolution input produces low-resolution output.
Edges are rough on hair/fur
This is a limitation of all AI background removal models. Results are best on clean product photos with good contrast between subject and background.
Request times out
Set a timeout of at least 30 seconds. Large images take 3-5 seconds to process. Use the retry pattern from the error handling example above.

Common questions

No. The background removal AI runs on PixelPanda's servers. Your Python code just makes an HTTP request and gets back a URL. The only dependency is the requests library (pip install requests). No GPU, no CUDA, no model downloads.
Loop over your files and call the API for each one. See the 'Process an entire folder' example above. Each image takes 2-4 seconds. For 100 images, that's about 5 minutes. Add time.sleep(0.5) between requests to avoid rate limits.
Yes — see the Django and Flask code examples above. Accept a file upload from your user, forward it to the PixelPanda API, and return the transparent PNG URL. Works with any Python web framework including FastAPI.
Python 3.6+ with the requests library. That's the only requirement. Works on macOS, Linux, Windows, Docker, AWS Lambda, Google Cloud Functions, and anywhere else Python runs.
See the 'Add a white background' example above using PIL/Pillow. Remove the background to get a transparent PNG, then composite onto a white canvas. Three lines of Pillow code. Perfect for Amazon and eBay listings.
1 credit per image ($0.029). Get started with 280 credits/week for $7.99 — cancel anytime. That's 200 background removals. Monthly plans from $24/month for 1,125 credits if you need more volume.
Starter plans allow 30 requests per minute. Growth and Pro plans allow 100+ per minute. For bulk processing, add a small delay between requests (0.5-1 second) and you'll never hit the limit.
Yes. Replace requests with httpx or aiohttp for async HTTP calls. The API endpoint is the same — only your HTTP client changes. Works great with FastAPI and async Django views.

Start removing backgrounds with Python

280 credits/week for $7.99. Copy the code above and go.

Get Your API Key