0
# rembg
1
2
A comprehensive Python library for removing image backgrounds using advanced AI models including U-Net, BiRefNet, and SAM (Segment Anything Model). rembg provides both a Python library interface and command-line tools for batch processing, supporting multiple model types optimized for different use cases such as general background removal, human segmentation, anime character segmentation, and portrait processing.
3
4
## Package Information
5
6
- **Package Name**: rembg
7
- **Language**: Python
8
- **Installation**: `pip install rembg`
9
- **Optional GPU Support**: `pip install rembg[gpu]` for CUDA acceleration
10
- **CLI Tools**: `pip install rembg[cli]` for command-line interface
11
- **Entry Point**: The CLI is available as `rembg` command after installation
12
13
## Core Imports
14
15
```python
16
import rembg
17
```
18
19
For background removal:
20
21
```python
22
from rembg import remove, new_session
23
```
24
25
For specific session types:
26
27
```python
28
from rembg.sessions import sessions, sessions_names
29
from rembg.sessions.u2net import U2netSession
30
from rembg.sessions.birefnet_general import BiRefNetSessionGeneral
31
```
32
33
## Basic Usage
34
35
```python
36
from rembg import remove
37
from PIL import Image
38
import numpy as np
39
40
# Remove background from PIL Image
41
input_image = Image.open('input.jpg')
42
output_image = remove(input_image)
43
output_image.save('output.png')
44
45
# Remove background from bytes
46
with open('input.jpg', 'rb') as f:
47
input_bytes = f.read()
48
output_bytes = remove(input_bytes)
49
50
# Remove background from numpy array
51
input_array = np.array(input_image)
52
output_array = remove(input_array)
53
54
# Use specific model
55
from rembg import new_session
56
session = new_session('u2net')
57
output_image = remove(input_image, session=session)
58
59
# Advanced usage with alpha matting
60
output_image = remove(
61
input_image,
62
alpha_matting=True,
63
alpha_matting_foreground_threshold=240,
64
alpha_matting_background_threshold=10
65
)
66
```
67
68
## Architecture
69
70
rembg is built around a flexible session-based architecture:
71
72
- **Core Functions**: The `remove()` function serves as the main entry point, handling different input types (bytes, PIL Images, NumPy arrays) and returning results in the same format
73
- **Session Management**: Model sessions encapsulate AI model loading, configuration, and prediction logic, with a factory pattern for easy instantiation via `new_session()`
74
- **Model Varieties**: 23 different AI models are available, each specialized for different use cases (general purpose, portraits, anime, clothing, etc.)
75
- **Processing Pipeline**: Input normalization → model prediction → mask post-processing → cutout generation → output formatting
76
- **CLI Integration**: Command-line tools built on Click provide batch processing, server mode, and model downloading capabilities
77
78
## Capabilities
79
80
### Background Removal
81
82
Core background removal functionality supporting multiple input/output formats, advanced alpha matting, mask-only output, and custom background colors.
83
84
```python { .api }
85
def remove(
86
data: Union[bytes, PILImage, np.ndarray],
87
alpha_matting: bool = False,
88
alpha_matting_foreground_threshold: int = 240,
89
alpha_matting_background_threshold: int = 10,
90
alpha_matting_erode_size: int = 10,
91
session: Optional[BaseSession] = None,
92
only_mask: bool = False,
93
post_process_mask: bool = False,
94
bgcolor: Optional[Tuple[int, int, int, int]] = None,
95
force_return_bytes: bool = False,
96
*args,
97
**kwargs
98
) -> Union[bytes, PILImage, np.ndarray]: ...
99
```
100
101
[Background Removal](./background-removal.md)
102
103
### Session Management
104
105
Model session creation and management with support for 23 different AI models, custom providers, and GPU acceleration.
106
107
```python { .api }
108
def new_session(model_name: str = "u2net", *args, **kwargs) -> BaseSession: ...
109
110
class BaseSession:
111
def __init__(self, model_name: str, sess_opts: ort.SessionOptions, *args, **kwargs): ...
112
def predict(self, img: PILImage, *args, **kwargs) -> List[PILImage]: ...
113
```
114
115
[Session Management](./session-management.md)
116
117
### Command-Line Interface
118
119
Comprehensive CLI tools for batch processing, folder monitoring, HTTP server, and model management.
120
121
```bash
122
# Process single image
123
rembg i input.jpg output.png
124
125
# Process folder
126
rembg p input_folder output_folder
127
128
# Start HTTP server
129
rembg s
130
131
# Download models
132
rembg d u2net birefnet-general
133
```
134
135
[Command-Line Interface](./cli.md)
136
137
### Utility Functions
138
139
Image processing utilities including concatenation, orientation fixing, background color application, and alpha matting operations.
140
141
```python { .api }
142
def alpha_matting_cutout(img: PILImage, mask: PILImage, foreground_threshold: int, background_threshold: int, erode_structure_size: int) -> PILImage: ...
143
def apply_background_color(img: PILImage, color: Tuple[int, int, int, int]) -> PILImage: ...
144
def fix_image_orientation(img: PILImage) -> PILImage: ...
145
```
146
147
[Utility Functions](./utilities.md)
148
149
## Types
150
151
```python { .api }
152
from typing import Union, Optional, List, Tuple, Any
153
from PIL.Image import Image as PILImage
154
import numpy as np
155
from enum import Enum
156
157
class ReturnType(Enum):
158
BYTES = 0
159
PILLOW = 1
160
NDARRAY = 2
161
162
# Input/Output types
163
ImageInput = Union[bytes, PILImage, np.ndarray]
164
ImageOutput = Union[bytes, PILImage, np.ndarray]
165
RGBAColor = Tuple[int, int, int, int]
166
```