Remove image background using advanced AI models including U-Net, BiRefNet, and SAM with support for multiple input formats and GPU acceleration
84
Image processing utilities that support the core background removal functionality. These functions handle image manipulation, orientation correction, background application, and specialized cutout operations.
Correct image orientation based on EXIF metadata to ensure proper processing.
def fix_image_orientation(img: PILImage) -> PILImage:
"""
Fix the orientation of the image based on its EXIF data.
Automatically rotates and flips the image according to the EXIF orientation
tag to ensure the image displays correctly.
Parameters:
- img: Input PIL image that may have orientation metadata
Returns:
PIL Image with corrected orientation
"""Usage Example:
from rembg.bg import fix_image_orientation
from PIL import Image
# Fix orientation for camera photos
image = Image.open('camera_photo.jpg')
corrected_image = fix_image_orientation(image)Apply solid background colors to images with transparency.
def apply_background_color(
img: PILImage,
color: Tuple[int, int, int, int]
) -> PILImage:
"""
Apply the specified background color to a transparent image.
Creates a new background layer with the specified RGBA color and
composites the input image over it.
Parameters:
- img: Input PIL image (should have alpha channel)
- color: RGBA color tuple (red, green, blue, alpha) with values 0-255
Returns:
PIL Image with background color applied
"""Usage Examples:
from rembg.bg import apply_background_color
from PIL import Image
# Apply white background
transparent_img = Image.open('cutout.png')
white_bg = apply_background_color(transparent_img, (255, 255, 255, 255))
# Apply colored background
blue_bg = apply_background_color(transparent_img, (0, 100, 200, 255))
# Apply semi-transparent background
semi_bg = apply_background_color(transparent_img, (255, 255, 255, 128))Combine multiple images vertically for comparison or batch visualization.
def get_concat_v(img1: PILImage, img2: PILImage) -> PILImage:
"""
Concatenate two images vertically.
Creates a new image with img1 on top and img2 below it.
Parameters:
- img1: First (top) PIL image
- img2: Second (bottom) PIL image to concatenate
Returns:
PIL Image with both images concatenated vertically
"""
def get_concat_v_multi(imgs: List[PILImage]) -> PILImage:
"""
Concatenate multiple images vertically.
Stacks all images in the list from top to bottom in order.
Parameters:
- imgs: List of PIL images to concatenate
Returns:
PIL Image with all images concatenated vertically
"""Usage Examples:
from rembg.bg import get_concat_v, get_concat_v_multi
from PIL import Image
# Concatenate two images
original = Image.open('original.jpg')
processed = Image.open('processed.png')
comparison = get_concat_v(original, processed)
# Concatenate multiple images
images = [Image.open(f'step_{i}.png') for i in range(1, 5)]
process_steps = get_concat_v_multi(images)Advanced cutout operations for high-quality edge refinement.
def alpha_matting_cutout(
img: PILImage,
mask: PILImage,
foreground_threshold: int,
background_threshold: int,
erode_structure_size: int
) -> PILImage:
"""
Perform alpha matting cutout for smooth, natural edges.
Uses advanced alpha matting algorithms to create smooth transitions
between foreground and background based on trimap generation.
Parameters:
- img: Input PIL image to cut out
- mask: Binary mask PIL image indicating foreground/background
- foreground_threshold: Pixel values above this are definitely foreground (0-255)
- background_threshold: Pixel values below this are definitely background (0-255)
- erode_structure_size: Size of erosion structure for trimap refinement
Returns:
PIL Image with refined alpha channel and smooth edges
"""
def naive_cutout(img: PILImage, mask: PILImage) -> PILImage:
"""
Perform simple cutout using basic image compositing.
Fast cutout operation that directly applies the mask without
edge refinement. Suitable for simple cases or when speed is critical.
Parameters:
- img: Input PIL image to cut out
- mask: Binary mask PIL image
Returns:
PIL Image with background removed using simple compositing
"""
def putalpha_cutout(img: PILImage, mask: PILImage) -> PILImage:
"""
Apply mask directly as the alpha channel of the image.
Directly assigns the mask as the alpha channel, preserving
original pixel values while making background transparent.
Parameters:
- img: Input PIL image
- mask: Binary mask PIL image to use as alpha channel
Returns:
PIL Image with mask applied as alpha channel
"""Usage Examples:
from rembg.bg import alpha_matting_cutout, naive_cutout, putalpha_cutout
from PIL import Image
# Load image and mask
image = Image.open('input.jpg')
mask = Image.open('mask.png')
# High-quality cutout with alpha matting
refined = alpha_matting_cutout(
image, mask,
foreground_threshold=240,
background_threshold=10,
erode_structure_size=5
)
# Fast simple cutout
simple = naive_cutout(image, mask)
# Direct alpha application
alpha_applied = putalpha_cutout(image, mask)Improve mask quality through morphological operations and smoothing.
def post_process(mask: np.ndarray) -> np.ndarray:
"""
Post-process binary mask for smoother boundaries.
Applies morphological opening followed by Gaussian blur and
re-thresholding to create smoother, more natural mask edges.
Based on research for improved boundary quality.
Parameters:
- mask: Binary numpy array representing the mask
Returns:
Processed numpy array with smoother boundaries and reduced noise
"""Usage Example:
from rembg.bg import post_process
import numpy as np
from PIL import Image
# Process a rough mask
rough_mask = np.array(Image.open('rough_mask.png'))
smooth_mask = post_process(rough_mask)
result_image = Image.fromarray(smooth_mask)from enum import Enum
class ReturnType(Enum):
"""Enumeration for specifying return type format."""
BYTES = 0 # Return as bytes
PILLOW = 1 # Return as PIL Image
NDARRAY = 2 # Return as numpy arrayThese utilities are used internally by the main remove() function but can also be used independently for custom processing workflows:
from rembg import remove, new_session
from rembg.bg import fix_image_orientation, apply_background_color, post_process
from PIL import Image
import numpy as np
# Custom processing workflow
image = Image.open('input.jpg')
# Fix orientation first
image = fix_image_orientation(image)
# Get mask only
session = new_session('u2net')
mask_pil = remove(image, session=session, only_mask=True)
# Post-process mask
mask_array = np.array(mask_pil)
smooth_mask_array = post_process(mask_array)
smooth_mask = Image.fromarray(smooth_mask_array)
# Apply custom cutout
from rembg.bg import naive_cutout
cutout = naive_cutout(image, smooth_mask)
# Apply background color
final_result = apply_background_color(cutout, (255, 255, 255, 255))Install 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