Skip to content

Team-Exopy/bgremover

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

16 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Background Remover API

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.

✨ Features

  • πŸ–ΌοΈ 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 rembg for faster initial processing when available
  • πŸ–±οΈ User-Friendly: Simple web interface for quick testing

πŸ› οΈ Technical Stack

  • 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

πŸ“‹ Requirements

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.6

πŸš€ Quick Start

1. Clone and Setup

git clone https://github.com/Team-Exopy/bgremover.git
cd bgremover

2. Create Virtual Environment

# Create virtual environment
python3 -m venv venv

# Activate virtual environment
# On Linux/macOS:
source venv/bin/activate

# On Windows:
venv\Scripts\activate

3. Install Dependencies

pip install -r requirements.txt

4. Download UΒ²-Net Model

Download 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.pth

Note: Download u2net-human-seg.pth from the official UΒ²-Net repository and save it in saved_models/u2net/ directory.

5. Run the Application

python3 main.py

The API will be available at:

πŸ“š API Usage

Web Interface

  1. Open your browser and go to http://localhost:8000
  2. Upload an image using the web form
  3. Click "Remove Background"
  4. Download the processed image

Programmatic API

Upload Image

curl -X POST "http://localhost:8000/remove-bg" \
     -H "accept: image/jpeg" \
     -H "Content-Type: multipart/form-data" \
     -F "file=@your-image.jpg"

Python Example

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}")

JavaScript Example

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
  });

πŸ“ Project Structure

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

βš™οΈ Configuration

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.

🐳 Docker Support (Optional)

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

πŸ”§ Troubleshooting

Common Issues

  1. Model Not Found Error

    • Ensure u2net-human-seg.pth is in saved_models/u2net/ directory
    • Check file permissions
  2. Memory Issues

    • Reduce image size before processing
    • Increase system RAM or use GPU acceleration
  3. Slow Processing

    • Install rembg for faster preprocessing
    • Consider using GPU-enabled PyTorch

Performance Tips

  • Use GPU acceleration if available
  • Resize large images before processing
  • Consider batch processing for multiple images
  • Implement caching for frequently processed images

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/new-feature)
  3. Commit your changes (git commit -am 'Add new feature')
  4. Push to the branch (git push origin feature/new-feature)
  5. Create a Pull Request

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ“– Citation

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}
}

πŸ”— Related Links

πŸ“ž Support

If you encounter any issues or have questions:

  1. Check the Issues section
  2. Create a new issue with detailed description
  3. Include error logs and system information

Made with ❀️ using U²-Net and FastAPI

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published