✨ AI Background Remover
Remove image backgrounds instantly with AI-powered precision
Quick Start • Features • API Docs • Examples • Deploy
🌟 Features
🚀 Lightning Fast
|
🎨 Beautiful Interface
|
🔒 100% Private
|
⚡ Developer Ready
|
📸 What's Supported?
| Feature | Details |
|---|---|
| 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!
💻 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:
- 🖱️ Click upload area or drag & drop an image
- 🎯 Click "Remove Background" button
- 👀 View before/after comparison
- 💾 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 |
|
| Model download fails | Check internet connection. Model is ~176MB and downloads to ~/.u2net/ |
| Port already in use |
|
| 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
| Endpoint | Method | Description |
|---|---|---|
/ | Returns the beautiful web interface | |
/remove-background | Remove background from uploaded image | |
/health | Check 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 image500: 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
| Platform | Quick Deploy |
|---|---|
| AWS EC2 | Launch instance → Install dependencies → Run app |
| DigitalOcean | Use App Platform → Connect repo → Auto deploy |
| Heroku | heroku create → git push heroku main |
| Railway | Connect GitHub → Auto deploy on push |
| Render | Connect repo → Auto deploy & scale |
📊 Performance & Stats
| Metric | Value |
|---|---|
| ⚡ Processing Time | 2-5 seconds per image |
| 💾 Memory Usage | 500MB - 2GB (with model loaded) |
| 🔄 Concurrent Requests | Multiple simultaneous uploads |
| 🧹 Auto Cleanup | Files deleted after 24 hours |
| 🎯 Accuracy | 95%+ 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)
| Model | Best For |
|---|---|
u2net | General purpose (default) |
u2net_human_seg | People & portraits |
u2net_cloth_seg | Clothing & fashion |
u2netp | Faster, less accurate |
silueta | Artistic 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
How to contribute:
- 🍴 Fork the repository
- 🔨 Create your feature branch (
git checkout -b feature/AmazingFeature) - 💾 Commit your changes (
git commit -m 'Add some AmazingFeature') - 📤 Push to the branch (
git push origin feature/AmazingFeature) - 🎉 Open a Pull Request
📄 License
🙏 Acknowledgments
Built with ❤️ using amazing open-source projects
| Project | Description |
|---|---|
| rembg | Python library for removing image backgrounds |
| U^2-Net | Deep learning model for salient object detection |
| FastAPI | Modern, fast web framework for building APIs |
| ONNX Runtime | High-performance inference engine |
| Pillow | Python Imaging Library for image processing |
💬 Support
Common Resources:
- 📖 Check the troubleshooting section
- 💬 Read the API documentation
- 🐛 Report bugs via GitHub Issues
- 💡 Share ideas in Discussions
Share with your friends: