Back ArrowBack Arrow
Back to Readme Listing

✨ AI Background Remover

Remove image backgrounds instantly with AI-powered precision

Python FastAPI License AI

Demo

Quick StartFeaturesAPI DocsExamplesDeploy


🌟 Features

🚀 Lightning Fast

  • Process images in 2-5 seconds
  • Pre-trained U^2-Net AI model
  • Optimized for performance

🎨 Beautiful Interface

  • Modern gradient UI
  • Drag & drop support
  • Real-time preview

🔒 100% Private

  • Local processing
  • No data collection
  • Auto file cleanup

Developer Ready

  • RESTful API
  • Easy integration
  • Well documented

📸 What's Supported?

FeatureDetails
Input Formats📁 JPG, JPEG, PNG, BMP, WebP
Output Format🖼️ PNG with transparent background
Max File Size📊 10MB per image
Processing Time⚡ 2-5 seconds average
Concurrent Requests🔄 Multiple simultaneous uploads

🎯 Quick Start

Prerequisites

💡 Make sure you have Python 3.8+ installed

python --version  # Should show Python 3.8 or higher

Installation

📦 Step 1: Setup Virtual Environment

Windows:

python -m venv venv
venv\Scripts\activate

Linux/Mac:

python3 -m venv venv
source venv/bin/activate
📥 Step 2: Install Dependencies
pip install -r requirements.txt

⏳ First run will download the AI model (~176MB) - this is one-time only!

▶️ Step 3: Launch Application
python main.py

🎉 Success! Open your browser at: http://localhost:8000


💻 Usage Examples

🌐 Web Interface

graph LR
    A[📤 Upload Image] --> B[🤖 AI Processing]
    B --> C[✨ Background Removed]
    C --> D[💾 Download PNG]

    style A fill:#667eea,color:#fff
    style B fill:#764ba2,color:#fff
    style C fill:#10b981,color:#fff
    style D fill:#f093fb,color:#fff

Simple Steps:

  1. 🖱️ Click upload area or drag & drop an image
  2. 🎯 Click "Remove Background" button
  3. 👀 View before/after comparison
  4. 💾 Download your image with transparent background

🔌 API Usage

🐍 Python Example
import requests

# Remove background from image
with open('photo.jpg', 'rb') as f:
    response = requests.post(
        'http://localhost:8000/remove-background',
        files={'file': f}
    )

# Save result
if response.status_code == 200:
    with open('result.png', 'wb') as output:
        output.write(response.content)
    print("✅ Background removed successfully!")
else:
    print(f"❌ Error: {response.json()['detail']}")
🌐 JavaScript Example
async function removeBackground(imageFile) {
    const formData = new FormData();
    formData.append("file", imageFile);

    const response = await fetch("http://localhost:8000/remove-background", {
        method: "POST",
        body: formData,
    });

    if (response.ok) {
        const blob = await response.blob();
        return URL.createObjectURL(blob);
    }
    throw new Error("Failed to process image");
}

// Usage
const input = document.querySelector('input[type="file"]');
input.addEventListener("change", async (e) => {
    const imageUrl = await removeBackground(e.target.files[0]);
    console.log("✅ Processed image:", imageUrl);
});
🖥️ cURL Example
curl -X POST "http://localhost:8000/remove-background" \
  -F "file=@photo.jpg" \
  -o result.png

echo "✅ Background removed! Saved as result.png"

📁 Project Structure

🖼️ Background_Remover/
│
├── 📄 main.py                 # FastAPI application with AI logic
├── 📋 requirements.txt        # Python dependencies
├── 📖 README.md              # This beautiful documentation
├── 🧪 test_api.py            # API testing script
├── 🚫 .gitignore             # Git ignore rules
│
├── 📂 uploads/               # Temporary upload storage
│   └── .gitkeep
│
└── 📂 outputs/               # Processed images
    └── .gitkeep


⚙️ Configuration

🔧 Environment Variables

Customize the application with environment variables:

# Maximum file size (in bytes)
MAX_FILE_SIZE=10485760  # 10MB

# Port number
PORT=8000

# Host address
HOST=0.0.0.0
🛠️ Code Modifications

Change Port or Host:

# Edit main.py
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)

Change Max File Size:

# Edit main.py
MAX_FILE_SIZE = 10 * 1024 * 1024  # Adjust size

Change Cleanup Schedule:

# Edit main.py
cleanup_old_files(UPLOAD_DIR, max_age_hours=24)  # Adjust hours

🐛 Troubleshooting

❌ Issue✅ Solution
Module not found error
venv\Scripts\activate
pip install -r requirements.txt
Model download failsCheck internet connection. Model is ~176MB and downloads to ~/.u2net/
Port already in use
# Windows
netstat -ano | findstr :8000
taskkill /PID <PID> /F

# Linux/Mac
lsof -i :8000
kill -9 <PID>
High memory usage • Resize images before processing
• Increase system RAM
• Process images in batches
Slow processing • First run loads model (slower)
• Large images take longer
• Consider GPU acceleration


📚 API Documentation

🔌 Available Endpoints

EndpointMethodDescription
/Returns the beautiful web interface
/remove-backgroundRemove background from uploaded image
/healthCheck API health status

📝 Request/Response Details

POST /remove-background

Request:

POST /remove-background HTTP/1.1
Content-Type: multipart/form-data

file: [image binary data]

Success Response (200):

HTTP/1.1 200 OK
Content-Type: image/png

[PNG image with transparent background]

Error Responses:

  • 400: Invalid file format or corrupted image
  • 500: Processing error
GET /health

Success Response (200):

{
    "status": "healthy",
    "service": "Background Remover API",
    "version": "1.0.0"
}

🚀 Deployment

🌐 Production Deployment

Deploy with Gunicorn (Recommended)
# Install gunicorn
pip install gunicorn

# Run with multiple workers
gunicorn main:app -w 4 -k uvicorn.workers.UvicornWorker --bind 0.0.0.0:8000

Checklist:

  • ✅ Set up reverse proxy (Nginx/Apache)
  • ✅ Enable HTTPS (Let's Encrypt)
  • ✅ Use process manager (systemd/PM2)
  • ✅ Configure firewall rules
  • ✅ Set up monitoring
🐳 Docker Deployment

Create Dockerfile:

FROM python:3.10-slim

WORKDIR /app

COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY . .

RUN mkdir -p uploads outputs

EXPOSE 8000

CMD ["python", "main.py"]

Build & Run:

docker build -t bg-remover .
docker run -d -p 8000:8000 --name bg-remover bg-remover
☁️ Cloud Platforms
PlatformQuick Deploy
AWS EC2Launch instance → Install dependencies → Run app
DigitalOceanUse App Platform → Connect repo → Auto deploy
Herokuheroku creategit push heroku main
RailwayConnect GitHub → Auto deploy on push
RenderConnect repo → Auto deploy & scale

📊 Performance & Stats

MetricValue
Processing Time2-5 seconds per image
💾 Memory Usage500MB - 2GB (with model loaded)
🔄 Concurrent RequestsMultiple simultaneous uploads
🧹 Auto CleanupFiles deleted after 24 hours
🎯 Accuracy95%+ for clear subjects

🔒 Security Features

graph TD
    A[User Upload] --> B{File Validation}
    B -->|Valid| C[Size Check < 10MB]
    B -->|Invalid| D[❌ Reject]
    C -->|OK| E[Format Check]
    C -->|Too Large| D
    E -->|Valid| F[Process Image]
    E -->|Invalid| D
    F --> G[Auto Cleanup After 24h]
    G --> H[✅ Success]

    style A fill:#667eea,color:#fff
    style F fill:#764ba2,color:#fff
    style H fill:#10b981,color:#fff
    style D fill:#ef4444,color:#fff

Security Measures:

  • ✅ File size limits (prevents DOS attacks)
  • ✅ File type validation
  • ✅ Automatic file cleanup
  • ✅ No data collection
  • ✅ Local processing only
  • ⚠️ Add authentication for production use

💡 Advanced Usage

🚀 GPU Acceleration

For faster processing with NVIDIA GPU:

# Install ONNX Runtime GPU
pip install onnxruntime-gpu

# Ensure CUDA is installed
nvidia-smi  # Check GPU availability

Performance Boost: ~3-5x faster processing

🎨 Custom AI Models

Use different rembg models:

from rembg import remove, new_session

# Available models
models = ['u2net', 'u2netp', 'u2net_human_seg', 'u2net_cloth_seg', 'silueta']

# Use specific model
session = new_session('u2net_human_seg')
output = remove(input_data, session=session)
ModelBest For
u2netGeneral purpose (default)
u2net_human_segPeople & portraits
u2net_cloth_segClothing & fashion
u2netpFaster, less accurate
siluetaArtistic silhouettes
📦 Batch Processing

Process multiple images:

from pathlib import Path
from rembg import remove

input_dir = Path("input_images")
output_dir = Path("output_images")
output_dir.mkdir(exist_ok=True)

for image_path in input_dir.glob("*.jpg"):
    with open(image_path, 'rb') as f:
        input_data = f.read()

    output_data = remove(input_data)

    output_path = output_dir / f"{image_path.stem}_no_bg.png"
    with open(output_path, 'wb') as f:
        f.write(output_data)

    print(f"✅ Processed: {image_path.name}")

🤝 Contributing

Contributions are welcome! 🎉

Contributors Issues Pull Requests

How to contribute:

  1. 🍴 Fork the repository
  2. 🔨 Create your feature branch (git checkout -b feature/AmazingFeature)
  3. 💾 Commit your changes (git commit -m 'Add some AmazingFeature')
  4. 📤 Push to the branch (git push origin feature/AmazingFeature)
  5. 🎉 Open a Pull Request

📄 License

MIT License © 2026

This project is open source and available for personal and commercial use.

License: MIT


🙏 Acknowledgments

Built with ❤️ using amazing open-source projects

ProjectDescription
rembgPython library for removing image backgrounds
U^2-NetDeep learning model for salient object detection
FastAPIModern, fast web framework for building APIs
ONNX RuntimeHigh-performance inference engine
PillowPython Imaging Library for image processing

💬 Support

Need help? We're here for you! 🚀

Documentation Issues Discussions

Common Resources:


Share with your friends:

LinkedIn Reddit


🎉 Happy Background Removing! 🎨✨

Made with 💜 by developers, for developers

⬆ Back to Top

Back to Top