Remove image background using advanced AI models including U-Net, BiRefNet, and SAM with support for multiple input formats and GPU acceleration
84
Core background removal functionality that provides the main API for removing backgrounds from images using AI models. Supports multiple input/output formats, advanced alpha matting, and various post-processing options.
The main function for removing backgrounds from images with comprehensive configuration options.
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]:
"""
Remove the background from an input image.
Parameters:
- data: Input image as bytes, PIL Image, or numpy array
- alpha_matting: Use advanced alpha matting for smoother edges
- alpha_matting_foreground_threshold: Threshold for foreground detection (0-255)
- alpha_matting_background_threshold: Threshold for background detection (0-255)
- alpha_matting_erode_size: Erosion size for alpha matting refinement
- session: Specific model session to use (defaults to u2net)
- only_mask: Return only the binary mask instead of cutout
- post_process_mask: Apply morphological operations to smooth mask
- bgcolor: RGBA background color tuple for non-transparent output
- force_return_bytes: Force output as bytes regardless of input type
Returns:
Processed image in same format as input (or bytes if force_return_bytes=True)
"""Usage Examples:
from rembg import remove
from PIL import Image
# Basic usage
input_img = Image.open('photo.jpg')
result = remove(input_img)
# With alpha matting for higher quality
result = remove(input_img, alpha_matting=True)
# Get only the mask
mask = remove(input_img, only_mask=True)
# Apply custom background color
result = remove(input_img, bgcolor=(255, 255, 255, 255)) # White background
# Process bytes directly
with open('input.jpg', 'rb') as f:
input_bytes = f.read()
output_bytes = remove(input_bytes)Specialized cutout functions for different quality levels and use cases.
def alpha_matting_cutout(
img: PILImage,
mask: PILImage,
foreground_threshold: int,
background_threshold: int,
erode_structure_size: int
) -> PILImage:
"""
Perform alpha matting cutout for high-quality edge refinement.
Parameters:
- img: Input PIL image
- mask: Binary mask PIL image
- foreground_threshold: Threshold for foreground pixels (0-255)
- background_threshold: Threshold for background pixels (0-255)
- erode_structure_size: Size of erosion structure for refinement
Returns:
PIL Image with refined alpha channel
"""
def naive_cutout(img: PILImage, mask: PILImage) -> PILImage:
"""
Perform simple cutout using mask composite operation.
Parameters:
- img: Input PIL image
- mask: Binary mask PIL image
Returns:
PIL Image with background removed
"""
def putalpha_cutout(img: PILImage, mask: PILImage) -> PILImage:
"""
Apply mask directly as alpha channel to image.
Parameters:
- img: Input PIL image
- mask: Binary mask PIL image
Returns:
PIL Image with mask applied as alpha channel
"""Functions for improving mask quality through morphological operations.
def post_process(mask: np.ndarray) -> np.ndarray:
"""
Post-process mask for smooth boundaries using morphological operations.
Applies opening operation followed by Gaussian blur and threshold
to create smoother mask boundaries.
Parameters:
- mask: Binary numpy mask array
Returns:
Processed numpy mask array with smoother boundaries
"""Utility for downloading AI models used in background removal.
def download_models(models: tuple[str, ...]) -> None:
"""
Download AI models for background removal.
Parameters:
- models: Tuple of model names to download. If empty, downloads all models.
Available models: u2net, u2netp, u2net_human_seg, u2net_cloth_seg,
u2net_custom, birefnet_general, birefnet_general_lite, birefnet_portrait,
birefnet_dis, birefnet_hrsod, birefnet_cod, birefnet_massive, dis_anime,
dis_custom, dis_general_use, sam, silueta, bria_rmbg, ben_custom
"""The remove() function raises ValueError for unsupported input types:
try:
result = remove(unsupported_data)
except ValueError as e:
print(f"Unsupported input type: {e}")
# Use force_return_bytes=True as fallback
result = remove(unsupported_data, force_return_bytes=True)pip install rembg[gpu] for CUDA supportInstall with Tessl CLI
npx tessl i tessl/pypi-rembgevals
scenario-1
scenario-2
scenario-3
scenario-4
scenario-5
scenario-6
scenario-7
scenario-8
scenario-9
scenario-10