# withoutBG Python SDK

**Remove backgrounds in Python. Free locally, or use the cloud API.**

Two modes that share the same API: run the Open Weights model locally (free, private, offline) or call the cloud API (better quality, no GPU, pay per image). Switch with one line of code.

Source: [github.com/withoutbg/withoutbg-python](https://github.com/withoutbg/withoutbg-python)

---

## Key Features

### Open Weights (Local)
Run entirely on your machine. Free and private.
- No API key required
- Unlimited processing
- Runs offline
- Uses the Open Weights model

### Cloud API
Best quality for hair, fur, and complex edges.
- Managed infrastructure
- Highest precision
- Hardware accelerated
- Pay-per-image

---

## Installation

```bash
# Using uv (recommended)
uv add withoutbg

# Or with pip
pip install withoutbg
```

> **Don't have `uv` yet?** Download it at [astral.sh/uv](https://astral.sh/uv), a fast, modern Python package installer.

---

## Quick Start

**Choose Your Model:**

* **[See Open Weights Results →](https://withoutbg.com/open-model/results)** - Local processing
* **[See API Results →](https://withoutbg.com/pro-model/results)** - Cloud API
* **[Compare Open Weights vs API →](https://withoutbg.com/resources/compare/oss-vs-api)**

### Local Processing (Open Weights, Free)

```python
from withoutbg import WithoutBG

# Initialize model once
model = WithoutBG.open_weights()

# Process image
result = model.remove_background("input.jpg")
result.save("output.png")
```

### Cloud API Processing

```python
from withoutbg import WithoutBG

# Pass api_key here, or set WITHOUTBG_API_KEY in the environment
model = WithoutBG.api(api_key="sk_your_key")

# Process image
result = model.remove_background("input.jpg")
result.save("output.png")
```

### CLI

```bash
# Local processing
withoutbg image.jpg

# Cloud processing
export WITHOUTBG_API_KEY=sk_your_key
withoutbg image.jpg --use-api
```

---

## API Reference

When using the cloud API, the SDK calls these endpoints:

* **Background Removal:** [Binary](/docs/pro-model/background-removal-binary) and [Base64](/docs/pro-model/background-removal-base64) variants
* **Alpha Matte Extraction:** [Binary](/docs/pro-model/alpha-matte-binary) and [Base64](/docs/pro-model/alpha-matte-base64) variants for advanced compositing
* **Credits Management:** [GET /available-credit](/docs/pro-model/credits) for usage tracking

For detailed endpoint specifications, error codes, rate limits, and advanced options, see the [API Documentation](/docs).

---

## Python API

### Single Image Processing

```python
from withoutbg import WithoutBG

# Initialize model once
model = WithoutBG.open_weights()

# Process image
result = model.remove_background("photo.jpg")
result.save("photo-withoutbg.png")

# Process with progress callback
def progress(value):
    print(f"Progress: {value * 100:.1f}%")

result = model.remove_background("photo.jpg", progress_callback=progress)
```

**Returns:** `PIL.Image.Image` in RGBA (transparent background)

---

### Batch Processing

```python
from withoutbg import WithoutBG

# Initialize model once (efficient!)
model = WithoutBG.open_weights()

# Process multiple images - model is reused for all images
images = ["photo1.jpg", "photo2.jpg", "photo3.jpg"]
results = model.remove_background_batch(images, output_dir="results/")

# Or process without saving
results = model.remove_background_batch(images)
for i, result in enumerate(results):
    result.save(f"output_{i}.png")
```

Keep the model object alive across all images in a batch. Recreating it for every image reloads the weights each time.

---

### Using the Cloud API

```python
from withoutbg import WithoutBG

# Initialize API client
model = WithoutBG.api(api_key="sk_your_key")

# Process images
result = model.remove_background("input.jpg")

# Batch processing with the cloud API
results = model.remove_background_batch(
    ["img1.jpg", "img2.jpg", "img3.jpg"],
    output_dir="api_results/"
)
```

Cloud batch requests include a 3-second delay between images to respect the 30 requests/minute rate limit.

---

### Advanced: Direct Model Access

```python
from withoutbg import OpenWeightsModel, WithoutBGAPIClient

# For advanced users who need direct control
open_weights_model = OpenWeightsModel()
result = open_weights_model.remove_background("input.jpg")

# Or with a custom model path
# Model can be downloaded from: https://huggingface.co/withoutbg/withoutbg-openweights-onnx
model = OpenWeightsModel(model_path="/path/to/withoutbg-open-weights.onnx")

# Direct cloud API access
api = WithoutBGAPIClient(api_key="sk_your_key")
result = api.remove_background("input.jpg")
usage = api.get_usage()
```

---

## Configuration

### API Key (Cloud)

```bash
export WITHOUTBG_API_KEY="sk_your_api_key"
```

Or pass per call: `WithoutBG.api(api_key="sk_your_api_key")`.

### Model Path

By default, the unified ONNX graph is downloaded from Hugging Face on first run. Set `WITHOUTBG_MODEL_PATH` to use a local copy instead:

```bash
export WITHOUTBG_MODEL_PATH=/path/to/withoutbg-open-weights.onnx
```

The sidecar metadata file (`withoutbg-open-weights.onnx.json`) must be in the same directory as the ONNX file.

**Model file (~495MB):** single unified WBGNet ONNX graph (depth, segmentation, matting, and refinement in one inference pass).

This is useful for:
- Offline environments
- CI/CD pipelines
- Custom model versions
- Faster startup times (no download needed)

### Input/Output

* **Inputs:** JPG, PNG, or WebP (typical).
* **Outputs:** Prefer **PNG** or **WebP** to retain transparency. JPEG drops transparency silently.
* **Compositing:** Use the alpha channel as a mask.

```python
from PIL import Image
from withoutbg import WithoutBG

model = WithoutBG.api(api_key="sk_your_api_key")  # or WithoutBG.open_weights()
fg = model.remove_background("subject.jpg")
bg = Image.open("background.jpg")
bg.paste(fg, (0, 0), fg)   # alpha used as mask
bg.save("composite.png")
```

---

## When to Use Which Mode?

| | Local (`open_weights()`) | Cloud (`api()`) |
| --- | --- | --- |
| **Cost** | Free forever | Pay per image |
| **Quality** | Good | Better (esp. hair, fur) |
| **Privacy** | Stays on your machine | Image sent to API |
| **GPU required** | No (CPU ONNX) | No |
| **First-run setup** | ~495MB download, once | API key only |
| **Best for** | Offline, private, batch jobs | Products, occasional use |

---

## CLI Reference

```bash
# Single image (local model)
withoutbg photo.jpg
withoutbg photo.jpg --output result.png
withoutbg photo.jpg --format webp --quality 90

# Batch
withoutbg photos/ --batch --output-dir results/

# Cloud API
export WITHOUTBG_API_KEY=sk_your_api_key
withoutbg photo.jpg --use-api

# JPEG output with white background fill
withoutbg portrait.jpg --format jpg --quality 95

withoutbg --help
```

---

## Performance

| | Local | Cloud |
| --- | --- | --- |
| **First run** | 5-10s (~495MB download) | 1-3s |
| **Per image** | 2-5s | 1-3s |
| **RAM** | ~2GB | None |
| **Disk** | 495MB (one-time cache) | None |

---

## Usage Analytics (Cloud)

```python
from withoutbg import WithoutBGAPIClient

api = WithoutBGAPIClient(api_key="sk_your_api_key")
usage = api.get_usage()  # Calls GET /available-credit
print(f"Credits: {usage['credit']}, Expires: {usage['expiration_date']}")
```

**For detailed credit management, see:** [Credits API Documentation](/docs/pro-model/credits)

---

## Error Handling

```python
from withoutbg import WithoutBG, APIError, WithoutBGError

try:
    model = WithoutBG.api()
    result = model.remove_background("photo.jpg")
    result.save("output.png")
except APIError as e:
    print(f"API error: {e}")
except WithoutBGError as e:
    print(f"Processing error: {e}")
```

---

## Advanced: Direct API Access

The SDK uses the cloud API under the hood. For advanced use cases like:
- Custom request/response handling
- Different programming languages
- Serverless environments
- Direct endpoint integration

See the [API Documentation](/docs) for:
- [Background Removal (Binary)](/docs/pro-model/background-removal-binary) - Direct PNG output for server workflows
- [Background Removal (Base64)](/docs/pro-model/background-removal-base64) - JSON responses for browser/serverless apps
- [Alpha Matte Binary](/docs/pro-model/alpha-matte-binary) - Separate alpha masks for advanced compositing
- [Alpha Matte Base64](/docs/pro-model/alpha-matte-base64) - Alpha matte in base64 encoding

The SDK is a convenience wrapper; all functionality is available through the REST API.

---

## Model (Hugging Face)

The withoutBG Open Model is a unified WBGNet ONNX graph hosted at [withoutbg/withoutbg-openweights-onnx](https://huggingface.co/withoutbg/withoutbg-openweights-onnx). It runs depth estimation, segmentation, matting, and refinement in a single inference pass at up to 768px output resolution. Built with DINOv3.

Licensed under the withoutBG Open Model License (Apache 2.0 for withoutBG portions; Meta DINOv3 License for DINOv3 backbone weights).

---

## Related Projects

Need a browser UI or HTTP API instead of Python?

**[withoutbg-inference](https://github.com/withoutbg/withoutbg-inference)** provides Docker images (CPU + GPU), a FastAPI inference service, and an optional web UI built on the same Open Weights model.

```bash
docker run --rm -p 8080:8080 withoutbg/withoutbg-openweights-v3-app-cpu
```

See also: [Self-host with Docker](/docs/open-model/docker)

---

## Migration from Older API Names

`WithoutBG.opensource()`, `OpenSourceModel`, and `ProAPI` still work as deprecated aliases but emit warnings and will be removed in the next major release. Use `WithoutBG.open_weights()`, `OpenWeightsModel`, and `WithoutBGAPIClient` instead.

The older four-file ONNX layout (`WITHOUTBG_DEPTH_MODEL_PATH`, etc.) is replaced by a single unified graph. Set `WITHOUTBG_MODEL_PATH` to point at `withoutbg-open-weights.onnx`.

Full details: [Migration Guide](https://github.com/withoutbg/withoutbg-python/blob/main/docs/MIGRATION.md)

---

## FAQ

### Is the local model really free?
Yes. The Open Weights model runs entirely on your hardware. There are no API calls, no costs, and no data leaves your machine.

### Why use the Cloud API instead?
The cloud API uses a significantly larger and more accurate model than the local Open Weights model, especially for difficult edges like hair or transparent objects. It also offloads processing from your CPU/GPU.

### Does it support batch processing?
Yes. The SDK includes optimized batch processing helpers that load the model once and process multiple images efficiently.

---

## Documentation

- **[Python SDK Documentation](https://withoutbg.com/docs/open-model/python)** - Complete online documentation
- **[Open Model Results](https://withoutbg.com/open-model/results)** - See example outputs
- **[API Results](https://withoutbg.com/pro-model/results)** - See example outputs
- **[Compare Models](https://withoutbg.com/resources/compare/oss-vs-api)** - Open Weights vs API comparison

---

## Support

* **Bugs / questions:** [GitHub Issues](https://github.com/withoutbg/withoutbg-python/issues)
* **Discussion:** [GitHub Discussions](https://github.com/withoutbg/withoutbg-python/discussions)
* **Commercial:** contact@withoutbg.com
