Remove image background using advanced AI models including U-Net, BiRefNet, and SAM with support for multiple input formats and GPU acceleration
npx @tessl/cli install tessl/pypi-rembg@2.0.0A 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.
pip install rembgpip install rembg[gpu] for CUDA accelerationpip install rembg[cli] for command-line interfacerembg command after installationimport rembgFor background removal:
from rembg import remove, new_sessionFor specific session types:
from rembg.sessions import sessions, sessions_names
from rembg.sessions.u2net import U2netSession
from rembg.sessions.birefnet_general import BiRefNetSessionGeneralfrom rembg import remove
from PIL import Image
import numpy as np
# Remove background from PIL Image
input_image = Image.open('input.jpg')
output_image = remove(input_image)
output_image.save('output.png')
# Remove background from bytes
with open('input.jpg', 'rb') as f:
input_bytes = f.read()
output_bytes = remove(input_bytes)
# Remove background from numpy array
input_array = np.array(input_image)
output_array = remove(input_array)
# Use specific model
from rembg import new_session
session = new_session('u2net')
output_image = remove(input_image, session=session)
# Advanced usage with alpha matting
output_image = remove(
input_image,
alpha_matting=True,
alpha_matting_foreground_threshold=240,
alpha_matting_background_threshold=10
)rembg is built around a flexible session-based architecture:
remove() function serves as the main entry point, handling different input types (bytes, PIL Images, NumPy arrays) and returning results in the same formatnew_session()Core background removal functionality supporting multiple input/output formats, advanced alpha matting, mask-only output, and custom background colors.
def remove(
data: Union[bytes, PILImage, np.ndarray],
alpha_matting: bool = False,
alpha_matting_foreground_threshold: int = 240,
alpha_matting_background_threshold: int = 10,
alpha_matting_erode_size: int = 10,
session: Optional[BaseSession] = None,
only_mask: bool = False,
post_process_mask: bool = False,
bgcolor: Optional[Tuple[int, int, int, int]] = None,
force_return_bytes: bool = False,
*args,
**kwargs
) -> Union[bytes, PILImage, np.ndarray]: ...Model session creation and management with support for 23 different AI models, custom providers, and GPU acceleration.
def new_session(model_name: str = "u2net", *args, **kwargs) -> BaseSession: ...
class BaseSession:
def __init__(self, model_name: str, sess_opts: ort.SessionOptions, *args, **kwargs): ...
def predict(self, img: PILImage, *args, **kwargs) -> List[PILImage]: ...Comprehensive CLI tools for batch processing, folder monitoring, HTTP server, and model management.
# Process single image
rembg i input.jpg output.png
# Process folder
rembg p input_folder output_folder
# Start HTTP server
rembg s
# Download models
rembg d u2net birefnet-generalImage processing utilities including concatenation, orientation fixing, background color application, and alpha matting operations.
def alpha_matting_cutout(img: PILImage, mask: PILImage, foreground_threshold: int, background_threshold: int, erode_structure_size: int) -> PILImage: ...
def apply_background_color(img: PILImage, color: Tuple[int, int, int, int]) -> PILImage: ...
def fix_image_orientation(img: PILImage) -> PILImage: ...from typing import Union, Optional, List, Tuple, Any
from PIL.Image import Image as PILImage
import numpy as np
from enum import Enum
class ReturnType(Enum):
BYTES = 0
PILLOW = 1
NDARRAY = 2
# Input/Output types
ImageInput = Union[bytes, PILImage, np.ndarray]
ImageOutput = Union[bytes, PILImage, np.ndarray]
RGBAColor = Tuple[int, int, int, int]