A powerful Python FastAPI application that intelligently removes image backgrounds using the state-of-the-art UΒ²-Net deep learning model. The API processes images entirely in memory and returns clean results with white backgrounds in JPEG format.
- πΌοΈ Smart Background Removal: Uses UΒ²-Net for accurate human and object segmentation
- π Dual Interface: Upload images via web form or programmatic API
- β‘ Memory Efficient: Processes images entirely in memory without temporary files
- π― High Accuracy: Leverages deep learning for precise edge detection
- π± RESTful API: Easy integration with any application
- π Optional Preprocessing: Uses
rembgfor faster initial processing when available - π±οΈ User-Friendly: Simple web interface for quick testing
- FastAPI: Modern, fast web framework
- UΒ²-Net: Deep learning model for salient object detection
- PyTorch: Deep learning framework
- OpenCV: Computer vision operations
- Pillow: Image processing
- rembg: Optional preprocessing library
torch>=2.0.0
torchvision>=0.15.0
numpy>=1.24.0
Pillow>=9.5.0
opencv-python>=4.7.0
rembg>=2.0.50
fastapi>=0.104.0
uvicorn>=0.24.0
python-multipart>=0.0.6git clone https://github.com/Team-Exopy/bgremover.git
cd bgremover# Create virtual environment
python3 -m venv venv
# Activate virtual environment
# On Linux/macOS:
source venv/bin/activate
# On Windows:
venv\Scripts\activatepip install -r requirements.txtDownload the pre-trained UΒ²-Net model and place it in the correct directory:
# Create model directory
mkdir -p saved_models/u2net
# Download the model (replace with actual download command or manual download)
# Download u2net-human-seg.pth from the official UΒ²-Net repository
# Save it to: saved_models/u2net/u2net-human-seg.pthNote: Download
u2net-human-seg.pthfrom the official UΒ²-Net repository and save it insaved_models/u2net/directory.
python3 main.pyThe API will be available at:
- Web Interface: http://localhost:8000
- API Documentation: http://localhost:8000/docs
- Alternative Docs: http://localhost:8000/redoc
- Open your browser and go to
http://localhost:8000 - Upload an image using the web form
- Click "Remove Background"
- Download the processed image
curl -X POST "http://localhost:8000/remove-bg" \
-H "accept: image/jpeg" \
-H "Content-Type: multipart/form-data" \
-F "file=@your-image.jpg"import requests
url = "http://localhost:8000/remove-bg"
files = {"file": open("your-image.jpg", "rb")}
response = requests.post(url, files=files)
if response.status_code == 200:
with open("output-image.jpg", "wb") as f:
f.write(response.content)
print("Background removed successfully!")
else:
print(f"Error: {response.status_code}")const formData = new FormData();
formData.append("file", fileInput.files[0]);
fetch("http://localhost:8000/remove-bg", {
method: "POST",
body: formData,
})
.then((response) => response.blob())
.then((blob) => {
const url = URL.createObjectURL(blob);
// Use the URL to display or download the image
});background-remover-api/
βββ main.py # FastAPI application
βββ requirements.txt # Python dependencies
βββ README.md # This file
βββ saved_models/
β βββ u2net/
β βββ u2net-human-seg.pth # UΒ²-Net model file
βββ templates/ # HTML templates (if any)
βββ u2Net # u2net repo
The application can be configured by modifying the following parameters in main.py:
- Host: Default
0.0.0.0 - Port: Default
8000 - Model Path:
saved_models/u2net/u2net-human-seg.pth - Maximum File Size: Configure in FastAPI settings
- Allowed File Types: JPG, PNG, JPEG, etc.
Create a Dockerfile for containerized deployment:
FROM python:3.9-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["python", "main.py"]Build and run:
docker build -t background-remover .
docker run -p 8000:8000 background-remover-
Model Not Found Error
- Ensure
u2net-human-seg.pthis insaved_models/u2net/directory - Check file permissions
- Ensure
-
Memory Issues
- Reduce image size before processing
- Increase system RAM or use GPU acceleration
-
Slow Processing
- Install
rembgfor faster preprocessing - Consider using GPU-enabled PyTorch
- Install
- Use GPU acceleration if available
- Resize large images before processing
- Consider batch processing for multiple images
- Implement caching for frequently processed images
- Fork the repository
- Create a feature branch (
git checkout -b feature/new-feature) - Commit your changes (
git commit -am 'Add new feature') - Push to the branch (
git push origin feature/new-feature) - Create a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
If you use this project in your research, please cite the original UΒ²-Net paper:
@InProceedings{Qin_2020_PR,
title = {U2-Net: Going Deeper with Nested U-Structure for Salient Object Detection},
author = {Qin, Xuebin and Zhang, Zichen and Huang, Chenyang and Dehghan, Masood and Zaiane, Osmar and Jagersand, Martin},
journal = {Pattern Recognition},
volume = {106},
pages = {107404},
year = {2020}
}If you encounter any issues or have questions:
- Check the Issues section
- Create a new issue with detailed description
- Include error logs and system information
Made with β€οΈ using UΒ²-Net and FastAPI