### Python API Examples Source: https://context7.com/danielgatis/rembg/llms.txt Examples demonstrating the use of the Rembg Python library for background removal with different prompting techniques. ```APIDOC ## Python API Examples ### Multiple Points Prompt This example shows how to use multiple foreground and background points to guide the segmentation. ```python from rembg import remove from PIL import Image # Load an image image = Image.open("input.png") # Define session (optional, for performance) session = None # or initialize session # Use multiple points for foreground and background output = remove( image, session=session, sam_prompt=[ {"type": "point", "data": [400, 350], "label": 1}, # Foreground {"type": "point", "data": [700, 400], "label": 1}, # Foreground {"type": "point", "data": [100, 100], "label": 2}, # Background ] ) output.save("output_multipoint.png") ``` ### Bounding Box Prompt This example demonstrates using a bounding box to define the region of interest for segmentation. ```python from rembg import remove from PIL import Image # Load an image image = Image.open("input.png") # Define session (optional) session = None # Use a bounding box prompt output = remove( image, session=session, sam_prompt=[ {"type": "rectangle", "data": [100, 100, 500, 400]} # [x1, y1, x2, y2] ] ) output.save("output_bbox.png") ``` ### Direct Input Points and Labels This example shows how to use NumPy arrays for input points and labels directly. ```python import numpy as np from rembg import remove from PIL import Image # Load an image image = Image.open("input.png") # Define session (optional) session = None # Define input points and labels using NumPy arrays input_points = np.array([[400, 350], [700, 400], [200, 400]]) input_labels = np.array([1, 1, 2]) # 1=foreground, 2=background output = remove( image, session=session, input_points=input_points, input_labels=input_labels ) output.save("output_direct_arrays.png") ``` ``` -------------------------------- ### Install Rembg with CPU Support Source: https://github.com/danielgatis/rembg/blob/main/README.md Install the rembg library with CPU support. Use the second option to include CLI tools. ```bash pip install "rembg[cpu]" # for library ``` ```bash pip install "rembg[cpu,cli]" # for library + cli ``` -------------------------------- ### Start HTTP Server with rembg CLI Source: https://github.com/danielgatis/rembg/blob/main/README.md Start an HTTP server for background removal using the rembg CLI, specifying host, port, and log level. ```shell rembg s --host 0.0.0.0 --port 7000 --log_level info ``` -------------------------------- ### CLI - HTTP Server (rembg s) Source: https://context7.com/danielgatis/rembg/llms.txt Starts a FastAPI-based HTTP server with REST API endpoints and an optional Gradio web UI. ```APIDOC ## CLI - HTTP Server (rembg s) The `rembg s` command starts a FastAPI-based HTTP server with REST API endpoints and an optional Gradio web UI. The API supports both GET (URL-based) and POST (file upload) requests, with full documentation available at `/api`. ```bash # Start server with default settings (port 7000) rembg s # Custom host and port rembg s --host 0.0.0.0 --port 8080 # Set log level rembg s --log_level debug # Specify number of worker threads rembg s --threads 4 # Disable Gradio UI (reduces idle CPU usage) rembg s --no-ui # Production deployment example rembg s --host 0.0.0.0 --port 7000 --log_level warning --no-ui ``` ``` -------------------------------- ### CLI: Start HTTP Server Source: https://context7.com/danielgatis/rembg/llms.txt Launch the rembg HTTP server with default settings, typically running on port 7000. Custom host and port can be specified. ```bash rembg s ``` ```bash rembg s --host 0.0.0.0 --port 8080 ``` -------------------------------- ### Install Rembg with GPU and CLI Support Source: https://github.com/danielgatis/rembg/blob/main/rembg.ipynb Installs the rembg library with GPU and command-line interface support. Ensure you have a compatible GPU and drivers for GPU acceleration. ```python ! pip install "rembg[gpu,cli]" ``` -------------------------------- ### HTTP API: Remove Background from URL (GET) Source: https://context7.com/danielgatis/rembg/llms.txt Make a GET request to the '/api/remove' endpoint, providing the image URL as a query parameter to process it remotely. ```bash curl -s "http://localhost:7000/api/remove?url=https://example.com/image.jpg" -o output.png ``` -------------------------------- ### Install Rembg with NVIDIA GPU Support Source: https://github.com/danielgatis/rembg/blob/main/README.md Install the rembg library with NVIDIA GPU support. Ensure your system is compatible with onnxruntime-gpu and has CUDA/cudnn-devel installed if necessary. Use the second option to include CLI tools. ```bash pip install "rembg[gpu]" # for library ``` ```bash pip install "rembg[gpu,cli]" # for library + cli ``` -------------------------------- ### Install Rembg with AMD GPU (ROCm) Support Source: https://github.com/danielgatis/rembg/blob/main/README.md Install the rembg library with AMD GPU (ROCm) support. This requires onnxruntime-rocm to be installed first, following AMD's documentation. Use the second option to include CLI tools. ```bash pip install "rembg[rocm]" # for library ``` ```bash pip install "rembg[rocm,cli]" # for library + cli ``` -------------------------------- ### Build NVIDIA CUDA Docker Image Source: https://github.com/danielgatis/rembg/blob/main/README.md Build a Docker image with NVIDIA CUDA and cuDNN support for GPU acceleration. Ensure the NVIDIA Container Toolkit is installed on the host. ```shell docker build -t rembg-nvidia-cuda-cudnn-gpu -f Dockerfile_nvidia_cuda_cudnn_gpu . ``` -------------------------------- ### Python: Remove Background with Multiple Points Prompt Source: https://context7.com/danielgatis/rembg/llms.txt Use multiple foreground and background points to guide the background removal process. Ensure the 'session' object is initialized before use. ```python output = remove( image, session=session, sam_prompt=[ {"type": "point", "data": [400, 350], "label": 1}, # Foreground {"type": "point", "data": [700, 400], "label": 1}, # Foreground {"type": "point", "data": [100, 100], "label": 2}, # Background ] ) output.save("output_multipoint.png") ``` -------------------------------- ### Start rembg HTTP server with Docker Source: https://context7.com/danielgatis/rembg/llms.txt This command starts the rembg HTTP server in a Docker container, exposing port 7000 for API requests. The server will be accessible from the host machine on port 7000. ```bash docker run -p 7000:7000 danielgatis/rembg s ``` -------------------------------- ### Load Image with PIL Source: https://github.com/danielgatis/rembg/blob/main/USAGE.md Loads an image using the Pillow library. Ensure Pillow is installed and the input image file exists. ```python from PIL import Image from rembg import new_session, remove input_path = 'input.png' output_path = 'output.png' input = Image.open(input_path) ``` -------------------------------- ### Run Docker server with model persistence Source: https://context7.com/danielgatis/rembg/llms.txt This command starts the rembg HTTP server in a Docker container, exposing port 7000. It also mounts the host's `~/.u2net` directory to `/root/.u2net` within the container, allowing the server to persist downloaded models. ```bash docker run -p 7000:7000 -v ~/.u2net:/root/.u2net danielgatis/rembg s ``` -------------------------------- ### Python requests example for background removal Source: https://context7.com/danielgatis/rembg/llms.txt This Python script uses the `requests` library to upload an image file and remove its background. The response content is saved as a PNG file. It demonstrates setting a specific model and an alpha channel parameter. ```python import requests # Upload file with open("input.jpg", "rb") as f: response = requests.post( "http://localhost:7000/api/remove", files={"file": f}, params={"model": "birefnet-general", "a": "true"} ) with open("output.png", "wb") as f: f.write(response.content) ``` -------------------------------- ### FFmpeg Integration with rembg CLI Source: https://github.com/danielgatis/rembg/blob/main/README.md Example of piping raw video output from FFmpeg to the rembg CLI for background removal, specifying dimensions and output format. ```shell ffmpeg -i input.mp4 -ss 10 -an -f rawvideo -pix_fmt rgb24 pipe:1 | rembg b 1280 720 -o folder/output-%03u.png ``` -------------------------------- ### Run Rembg Application Source: https://github.com/danielgatis/rembg/blob/main/rembg.ipynb Executes the main application script for Rembg. This command starts the background removal service. ```python !python app.py ``` -------------------------------- ### Python: Interactive Segmentation with SAM Source: https://context7.com/danielgatis/rembg/llms.txt Integrates the Segment Anything Model (SAM) for interactive segmentation using point and rectangle prompts. Specify foreground/background points or bounding boxes to guide segmentation. ```python from rembg import remove, new_session from PIL import Image import numpy as np # Create SAM session session = new_session("sam") # Load image image = Image.open("complex_scene.jpg") # Segment using a single foreground point (x, y coordinates) output = remove( image, session=session, sam_prompt=[ {"type": "point", "data": [500, 300], "label": 1} # Foreground point ] ) output.save("output_point.png") ``` -------------------------------- ### Rembg CLI Help Source: https://github.com/danielgatis/rembg/blob/main/README.md Get help for the main rembg command. The rembg CLI supports subcommands for single files, folders, HTTP server, and binary streams. ```shell rembg --help ``` -------------------------------- ### Python Configuration for Rembg Source: https://context7.com/danielgatis/rembg/llms.txt Configure rembg settings in Python by setting environment variables for model storage, threading, and checksum verification. This example also initializes a new session. ```python import os os.environ["U2NET_HOME"] = "/custom/models" os.environ["OMP_NUM_THREADS"] = "8" os.environ["MODEL_CHECKSUM_DISABLED"] = "1" from rembg import remove, new_session session = new_session("birefnet-general") ``` -------------------------------- ### HTTP API: Get Only Mask Source: https://context7.com/danielgatis/rembg/llms.txt Use the 'om=true' query parameter to retrieve only the generated alpha mask instead of the full background-removed image. ```bash curl -s -F file=@input.jpg "http://localhost:7000/api/remove?om=true" -o mask.png ``` -------------------------------- ### Disable Gradio UI with rembg Server Source: https://github.com/danielgatis/rembg/blob/main/README.md Start the rembg HTTP server with the --no-ui flag to disable the Gradio UI and reduce CPU usage. ```shell rembg s --no-ui ``` -------------------------------- ### Use Input Points for Masking with SAM Model Source: https://github.com/danielgatis/rembg/blob/main/USAGE.md Specifies points and their labels to guide the mask generation, specifically for the 'sam' model. Points are defined as [y, x] coordinates. ```python import numpy as np # Define the points and labels # The points are defined as [y, x] input_points = np.array([[400, 350], [700, 400], [200, 400]]) input_labels = np.array([1, 1, 2]) image = remove(image,session=session, input_points=input_points, input_labels=input_labels) ``` -------------------------------- ### Extract frames and remove backgrounds with FFmpeg Source: https://context7.com/danielgatis/rembg/llms.txt This command uses FFmpeg to extract raw RGB24 video frames from an input file and pipes them to the `rembg b` command for background removal. Output frames are saved with sequential numbering. This example specifies a 1280x720 resolution. ```bash ffmpeg -i input.mp4 -ss 10 -an -f rawvideo -pix_fmt rgb24 pipe:1 | \ rembg b 1280 720 -o output/frame-%03u.png ``` -------------------------------- ### Rembg CLI Subcommand Help Source: https://github.com/danielgatis/rembg/blob/main/README.md Get help for a specific rembg subcommand. Replace with the desired subcommand (e.g., i, p, s, b). ```shell rembg --help ``` -------------------------------- ### HTTP API - REST Endpoints Source: https://context7.com/danielgatis/rembg/llms.txt REST API endpoints for background removal. Supports GET (URL) and POST (file upload) requests with various processing options. ```APIDOC ## HTTP API - REST Endpoints The HTTP server exposes REST endpoints at `/api/remove` for background removal. GET requests accept an image URL, while POST requests accept file uploads. Both support query parameters for model selection and processing options. ### GET /api/remove Removes background from an image specified by a URL. #### Query Parameters - **url** (string) - Required - The URL of the image to process. - **model** (string) - Optional - The model to use for background removal (e.g., `birefnet-general`). - **a** (boolean) - Optional - Enable alpha matting. - **af** (integer) - Optional - Alpha matting foreground threshold. - **ab** (integer) - Optional - Alpha matting background threshold. - **ae** (integer) - Optional - Alpha matting erosion. - **om** (boolean) - Optional - Output only the mask. - **ppm** (boolean) - Optional - Post-process mask for cleaner boundaries. ### POST /api/remove Removes background from an uploaded image file. #### Request Body - **file** (file) - Required - The image file to process. #### Query Parameters (Same query parameters as GET request: `url`, `model`, `a`, `af`, `ab`, `ae`, `om`, `ppm`) ### Request Examples ```bash # Remove background from URL (GET request) curl -s "http://localhost:7000/api/remove?url=https://example.com/image.jpg" -o output.png # Remove background from uploaded file (POST request) curl -s -F file=@input.jpg "http://localhost:7000/api/remove" -o output.png # Specify model via query parameter curl -s "http://localhost:7000/api/remove?url=https://example.com/photo.jpg&model=birefnet-general" -o output.png # Enable alpha matting curl -s -F file=@input.jpg "http://localhost:7000/api/remove?a=true&af=240&ab=10&ae=10" -o output.png # Get only mask curl -s -F file=@input.jpg "http://localhost:7000/api/remove?om=true" -o mask.png # Post-process mask curl -s -F file=@input.jpg "http://localhost:7000/api/remove?ppm=true" -o output.png ``` ``` -------------------------------- ### Process specific duration of video with FFmpeg and rembg Source: https://context7.com/danielgatis/rembg/llms.txt This command processes a specific duration (10 seconds) of a video file, starting from 30 seconds in. FFmpeg extracts raw RGB24 frames, which are then piped to `rembg b` for background removal. Output frames are saved with four-digit numbering. ```bash ffmpeg -i video.mp4 -ss 00:00:30 -t 10 -an -f rawvideo -pix_fmt rgb24 pipe:1 | \ rembg b 1920 1080 -o frames/out-%04u.png ``` -------------------------------- ### CLI: Specify Different Models Source: https://context7.com/danielgatis/rembg/llms.txt Use the '-m' flag to select alternative background removal models like 'birefnet-general', 'u2net_human_seg', 'isnet-anime', or the lighter 'u2netp'. ```bash rembg i -m birefnet-general input.jpg output.png ``` ```bash rembg i -m u2net_human_seg portrait.jpg portrait_nobg.png ``` ```bash rembg i -m isnet-anime anime.png anime_nobg.png ``` ```bash rembg i -m u2netp input.jpg output.png # Faster, lighter model ``` -------------------------------- ### HTTP API: Enable Alpha Matting Source: https://context7.com/danielgatis/rembg/llms.txt Activate alpha matting for smoother edges by setting the 'a' query parameter to 'true' and optionally configuring matting parameters 'af', 'ab', and 'ae'. ```bash curl -s -F file=@input.jpg "http://localhost:7000/api/remove?a=true&af=240&ab=10&ae=10" -o output.png ``` -------------------------------- ### CLI: Server Configuration Options Source: https://context7.com/danielgatis/rembg/llms.txt Configure server behavior using flags like '--log_level' to set logging verbosity, '--threads' for worker count, and '--no-ui' to disable the Gradio interface. ```bash rembg s --log_level debug ``` ```bash rembg s --threads 4 ``` ```bash rembg s --no-ui ``` ```bash rembg s --host 0.0.0.0 --port 7000 --log_level warning --no-ui ``` -------------------------------- ### CLI: Use SAM Model with Point Prompts Source: https://context7.com/danielgatis/rembg/llms.txt Process an image using the SAM model by providing point prompts via a JSON string passed to the '-x' option. ```bash rembg i -m sam -x '{"sam_prompt": [{"type": "point", "data": [724, 740], "label": 1}]}' plants.jpg plants_out.png ``` -------------------------------- ### Use XDG_DATA_HOME for Model Storage (Bash) Source: https://context7.com/danielgatis/rembg/llms.txt Configure rembg to store models in the directory specified by XDG_DATA_HOME. Models will be located in $XDG_DATA_HOME/.u2net. ```bash # Alternative: use XDG_DATA_HOME (models stored in $XDG_DATA_HOME/.u2net) export XDG_DATA_HOME=/custom/data rembg i input.png output.png ``` -------------------------------- ### CLI: Use Custom Model File Source: https://context7.com/danielgatis/rembg/llms.txt Load and use a custom ONNX model file by specifying its path within a JSON string passed to the '-x' option. ```bash rembg i -m u2net_custom -x '{"model_path": "~/.u2net/custom.onnx"}' input.png output.png ``` -------------------------------- ### CLI: Combined Batch Processing Options Source: https://context7.com/danielgatis/rembg/llms.txt Utilize multiple options simultaneously for batch processing, such as watch mode, alpha matting, and mask post-processing. ```bash rembg p -w -a -ppm ./input ./output ``` -------------------------------- ### CLI: Batch Processing with Alpha Matting Source: https://context7.com/danielgatis/rembg/llms.txt Enable alpha matting for all images processed in a batch folder operation to ensure smoother edges. ```bash rembg p -a ./input ./output ``` -------------------------------- ### Python: Basic Image Background Removal Source: https://context7.com/danielgatis/rembg/llms.txt Demonstrates basic background removal using the `remove()` function with PIL Images and bytes. Ensure input and output files are handled correctly. ```python from rembg import remove, new_session from PIL import Image import numpy as np # Basic usage with PIL Image input_image = Image.open("input.png") output_image = remove(input_image) output_image.save("output.png") # Using bytes input/output with open("input.jpg", "rb") as f: input_bytes = f.read() output_bytes = remove(input_bytes) with open("output.png", "wb") as f: f.write(output_bytes) ``` ```python # With alpha matting for smoother edges output = remove( input_image, alpha_matting=True, alpha_matting_foreground_threshold=240, alpha_matting_background_threshold=10, alpha_matting_erode_size=10 ) ``` ```python # Get only the mask (useful for custom compositing) mask = remove(input_image, only_mask=True) ``` ```python # Apply post-processing for cleaner mask boundaries output = remove(input_image, post_process_mask=True) ``` ```python # Replace background with a solid color (RGBA) output = remove(input_image, bgcolor=(255, 255, 255, 255)) # White background ``` ```python # Using NumPy arrays (e.g., with OpenCV) import cv2 cv_image = cv2.imread("input.png") output_array = remove(cv_image) cv2.imwrite("output.png", output_array) ``` -------------------------------- ### CLI: Enable Alpha Matting Source: https://context7.com/danielgatis/rembg/llms.txt Use the '-a' flag to enable alpha matting for smoother edges in the processed image. Custom parameters can be set with '-af', '-ab', and '-ae'. ```bash rembg i -a input.jpg output.png ``` ```bash rembg i -a -af 270 -ab 20 -ae 11 input.jpg output.png ``` -------------------------------- ### Python: Remove Background with Input Points and Labels Source: https://context7.com/danielgatis/rembg/llms.txt Directly provide input points and their corresponding labels (1 for foreground, 2 for background) using NumPy arrays for background removal. ```python input_points = np.array([[400, 350], [700, 400], [200, 400]]) input_labels = np.array([1, 1, 2]) # 1=foreground, 2=background output = remove( image, session=session, input_points=input_points, input_labels=input_labels ) ``` -------------------------------- ### Run rembg with Docker and GPU support Source: https://context7.com/danielgatis/rembg/llms.txt This command runs the `rembg-gpu` Docker image with access to all available GPUs (`--gpus all`). It mounts necessary devices and directories, and performs background removal on an input file, saving the output. It uses the `birefnet-general` model. ```bash docker run --rm -it --gpus all \ -v /dev/dri:/dev/dri \ -v $(pwd):/data \ rembg-gpu i -m birefnet-general /data/input.png /data/output.png ``` -------------------------------- ### CLI: Batch Processing with Specific Model Source: https://context7.com/danielgatis/rembg/llms.txt Apply background removal to all images in a folder using a specific model, saving the processed images to another directory. ```bash rembg p -m birefnet-general ./photos ./processed ``` -------------------------------- ### Compare different rembg models on an image Source: https://context7.com/danielgatis/rembg/llms.txt This Python script demonstrates how to use `new_session` to load different rembg models and `remove` to process an image with each model. The output for each model is saved as a separate PNG file. It iterates through a list of general-purpose models. ```python from rembg import new_session, remove from PIL import Image # List of all available models: models = { # General purpose models "u2net": "Default model, good for general use cases", "u2netp": "Lightweight version of u2net, faster processing", "silueta": "Compact model (43MB), same architecture as u2net", "isnet-general-use": "High-quality general purpose segmentation", "birefnet-general": "BiRefNet model for general use, high quality", "birefnet-general-lite": "Lightweight BiRefNet for faster processing", "birefnet-massive": "BiRefNet trained on massive dataset", "bria-rmbg": "State-of-the-art BRIA AI background removal", # Specialized models "u2net_human_seg": "Optimized for human segmentation", "birefnet-portrait": "Optimized for portrait photography", "isnet-anime": "High-accuracy anime character segmentation", "u2net_cloth_seg": "Cloth parsing (upper/lower/full body)", "birefnet-dis": "Dichotomous image segmentation", "birefnet-hrsod": "High-resolution salient object detection", "birefnet-cod": "Concealed object detection", # Interactive model "sam": "Segment Anything Model with point/box prompts", } # Example: Compare models on the same image image = Image.open("test.jpg") for model_name in ["u2net", "birefnet-general", "isnet-general-use"]: session = new_session(model_name) output = remove(image, session=session) output.save(f"output_{model_name}.png") ``` -------------------------------- ### Apply Alpha Matting with rembg CLI Source: https://github.com/danielgatis/rembg/blob/main/README.md Use the -a flag to apply alpha matting for background removal with the rembg CLI. ```shell rembg i -a path/to/input.png path/to/output.png ``` -------------------------------- ### HTTP API: Specify Model via Query Parameter Source: https://context7.com/danielgatis/rembg/llms.txt Include the 'model' query parameter in your API request to select a specific background removal model for processing. ```bash curl -s "http://localhost:7000/api/remove?url=https://example.com/photo.jpg&model=birefnet-general" -o output.png ``` -------------------------------- ### Set background color with API Source: https://context7.com/danielgatis/rembg/llms.txt Use the `bgc` parameter to set a specific background color in RGBA format. The output is saved to a file. ```bash curl -s -F file=@input.jpg "http://localhost:7000/api/remove?bgc=255,255,255,255" -o output_white.png ``` -------------------------------- ### Python: Efficient Image Processing with Sessions Source: https://context7.com/danielgatis/rembg/llms.txt Utilizes `new_session()` to create reusable sessions for processing multiple images, improving performance by avoiding repeated model loading. Supports automatic GPU detection. ```python from rembg import remove, new_session from pathlib import Path # Create session with default u2net model session = new_session() # Create session with a specific model session = new_session("birefnet-general") # High-quality general purpose session = new_session("u2net_human_seg") # Optimized for humans session = new_session("isnet-anime") # Optimized for anime session = new_session("u2netp") # Lightweight/faster session = new_session("silueta") # Compact 43MB model session = new_session("birefnet-portrait") # Portrait photography session = new_session("bria-rmbg") # BRIA AI state-of-the-art model ``` ```python # Batch processing with session reuse (recommended for performance) session = new_session("birefnet-general") input_folder = Path("./images") output_folder = Path("./output") output_folder.mkdir(exist_ok=True) for image_path in input_folder.glob("*.jpg"): with open(image_path, "rb") as f: input_data = f.read() output_data = remove(input_data, session=session) output_path = output_folder / f"{image_path.stem}.png" with open(output_path, "wb") as f: f.write(output_data) print(f"Processed: {image_path.name}") ``` ```python # Using custom model file session = new_session("u2net_custom", model_path="~/.u2net/my_model.onnx") ``` -------------------------------- ### Fast Multi-Image Processing Source: https://github.com/danielgatis/rembg/blob/main/USAGE.md Optimizes background removal for multiple images by initializing a session once and reusing it for each image. This avoids the overhead of initializing a new session for every call. ```python model_name = "unet" rembg_session = new_session(model_name) for img in images: output = remove(img, session=rembg_session) ``` -------------------------------- ### Process Raw RGB24 Images with rembg CLI Source: https://github.com/danielgatis/rembg/blob/main/README.md Use the 'b' command to process a stream of raw RGB24 images from stdin, intended for use with tools like FFmpeg. Specify width, height, and an output specifier. ```shell rembg b -o ``` -------------------------------- ### Fetch image from URL with Python requests Source: https://context7.com/danielgatis/rembg/llms.txt This Python script uses the `requests` library to fetch an image from a URL and remove its background using a specified model. The response content is saved as a PNG file. ```python response = requests.get( "http://localhost:7000/api/remove", params={"url": "https://example.com/image.jpg", "model": "u2net"} ) ``` -------------------------------- ### Python: Remove Background with Bounding Box Prompt Source: https://context7.com/danielgatis/rembg/llms.txt Utilize a bounding box (rectangle) to define the area of interest for background removal. The data format is [x1, y1, x2, y2]. ```python output = remove( image, session=session, sam_prompt=[ {"type": "rectangle", "data": [100, 100, 500, 400]} # [x1, y1, x2, y2] ] ) output.save("output_bbox.png") ``` -------------------------------- ### Build GPU-enabled Docker image Source: https://context7.com/danielgatis/rembg/llms.txt This command builds a Docker image named `rembg-gpu` with support for NVIDIA GPUs, CUDA, and cuDNN. It uses the provided `Dockerfile_nvidia_cuda_cudnn_gpu` for the build process. ```bash docker build -t rembg-gpu -f Dockerfile_nvidia_cuda_cudnn_gpu . ``` -------------------------------- ### Process webcam stream with FFmpeg and rembg Source: https://context7.com/danielgatis/rembg/llms.txt This command captures frames from a webcam using FFmpeg, converts them to raw RGB24 format, and pipes them to `rembg b` for background removal. The output frames are saved with specified dimensions and sequential numbering. ```bash ffmpeg -f v4l2 -i /dev/video0 -f rawvideo -pix_fmt rgb24 pipe:1 | \ rembg b 640 480 -o captures/frame-%03u.png ``` -------------------------------- ### CLI - Batch Folder Processing (rembg p) Source: https://context7.com/danielgatis/rembg/llms.txt Command-line interface for recursively processing all images within a folder. Supports watch mode for real-time processing. ```APIDOC ## CLI - Batch Folder Processing (rembg p) The `rembg p` command processes all images in a folder recursively. It supports watch mode for real-time processing of new files, making it ideal for automated workflows and production pipelines. ```bash # Process all images in a folder rembg p ./input_folder ./output_folder # Use a specific model for batch processing rembg p -m birefnet-general ./photos ./processed # Enable alpha matting for all images rembg p -a ./input ./output # Watch mode: continuously process new/changed files rembg p -w ./input ./output # Watch mode with specific model rembg p -w -m u2net_human_seg ./portraits ./processed # Delete input files after processing rembg p -d ./input ./output # Combined options: watch, alpha matting, and post-processing rembg p -w -a -ppm ./input ./output # To stop watch mode, create a file named 'stop.txt' in the input folder touch ./input/stop.txt ``` ``` -------------------------------- ### CLI: Set Background Color Source: https://context7.com/danielgatis/rembg/llms.txt Specify a background color using the '-bgc' flag followed by RGBA values (0-255) to replace the removed background. ```bash rembg i -bgc 255 255 255 255 input.jpg output_white_bg.png ``` -------------------------------- ### Navigate to Rembg Directory Source: https://github.com/danielgatis/rembg/blob/main/rembg.ipynb Changes the current working directory to the cloned Rembg project folder. This is necessary to run project-specific commands. ```bash %cd RemBG ``` -------------------------------- ### Input/Output as Bytes with rembg Python Library Source: https://github.com/danielgatis/rembg/blob/main/README.md Read an image from a file, remove its background, and write the result to another file using byte streams with the rembg library. ```python from rembg import remove with open('input.png', 'rb') as i: with open('output.png', 'wb') as o: input = i.read() output = remove(input) o.write(output) ``` -------------------------------- ### CLI - Single File Processing (rembg i) Source: https://context7.com/danielgatis/rembg/llms.txt Command-line interface for processing individual image files. Supports file I/O, model selection, and various processing options. ```APIDOC ## CLI - Single File Processing (rembg i) The `rembg i` command processes individual image files. It supports reading from files or stdin and writing to files or stdout, enabling integration with other command-line tools like curl. All model and processing options are available via command-line flags. ```bash # Basic usage: input and output files rembg i input.png output.png # Read from stdin, write to stdout cat input.png | rembg i > output.png # Download and process remote image curl -s https://example.com/photo.jpg | rembg i > output.png # Specify a different model rembg i -m birefnet-general input.jpg output.png rembg i -m u2net_human_seg portrait.jpg portrait_nobg.png rembg i -m isnet-anime anime.png anime_nobg.png rembg i -m u2netp input.jpg output.png # Faster, lighter model # Enable alpha matting for smoother edges rembg i -a input.jpg output.png # Custom alpha matting parameters rembg i -a -af 270 -ab 20 -ae 11 input.jpg output.png # Output only the mask rembg i -om input.jpg mask.png # Post-process mask for cleaner boundaries rembg i -ppm input.jpg output.png # Set background color (R G B A) rembg i -bgc 255 255 255 255 input.jpg output_white_bg.png # Use SAM model with point prompts rembg i -m sam -x '{"sam_prompt": [{"type": "point", "data": [724, 740], "label": 1}]}' plants.jpg plants_out.png # Use custom model file rembg i -m u2net_custom -x '{"model_path": "~/.u2net/custom.onnx"}' input.png output.png ``` ``` -------------------------------- ### HTTP API: Post-process Mask Source: https://context7.com/danielgatis/rembg/llms.txt Apply mask post-processing for cleaner boundaries by including the 'ppm=true' query parameter in your API request. ```bash curl -s -F file=@input.jpg "http://localhost:7000/api/remove?ppm=true" -o output.png ``` -------------------------------- ### CLI: Stop Watch Mode Source: https://context7.com/danielgatis/rembg/llms.txt To halt the watch mode process, create an empty file named 'stop.txt' within the input folder being monitored. ```bash touch ./input/stop.txt ``` -------------------------------- ### Input/Output as PIL Image with rembg Python Library Source: https://github.com/danielgatis/rembg/blob/main/README.md Use the rembg library to remove the background from a PIL Image object and save the result. ```python from rembg import remove from PIL import Image input = Image.open('input.png') output = remove(input) output.save('output.png') ``` -------------------------------- ### CLI: Output Only Mask Source: https://context7.com/danielgatis/rembg/llms.txt Use the '-om' flag to generate and save only the alpha mask of the background removal result. ```bash rembg i -om input.jpg mask.png ``` -------------------------------- ### CLI: Watch Mode for Batch Processing Source: https://context7.com/danielgatis/rembg/llms.txt Enable watch mode to continuously monitor an input folder for new or changed image files and process them automatically. ```bash rembg p -w ./input ./output ``` ```bash rembg p -w -m u2net_human_seg ./portraits ./processed ``` -------------------------------- ### Pass extra JSON parameters to API Source: https://context7.com/danielgatis/rembg/llms.txt Provide additional JSON parameters, such as for the SAM model, using the `extras` parameter. Ensure JSON is properly escaped. ```bash curl -s -F file=@input.jpg "http://localhost:7000/api/remove?model=sam&extras=\"{\"sam_prompt\":[{\"type\":\"point\",\"data\":[400,300],\"label\":1}]})\"" -o output.png ``` -------------------------------- ### Process a folder of images with Docker Source: https://context7.com/danielgatis/rembg/llms.txt This command processes all images within a specified input folder using the rembg Docker image. It mounts the input folder to `/data/input` and the output folder to `/data/output` within the container. ```bash docker run -v $(pwd)/images:/data danielgatis/rembg p /data/input /data/output ``` -------------------------------- ### Run NVIDIA CUDA Docker Container Source: https://github.com/danielgatis/rembg/blob/main/README.md Run the rembg container with GPU acceleration enabled. Mount necessary volumes for device access, data, and models. ```shell sudo docker run --rm -it --gpus all -v /dev/dri:/dev/dri -v $PWD:/data rembg-nvidia-cuda-cudnn-gpu i -m birefnet-general /data/input.png /data/output.png ``` -------------------------------- ### Specify Model with rembg CLI Source: https://github.com/danielgatis/rembg/blob/main/README.md Use the -m flag to specify a particular model for background removal with the rembg CLI. ```shell rembg i -m u2netp path/to/input.png path/to/output.png ``` -------------------------------- ### CLI: Process Remote Image via Curl Source: https://context7.com/danielgatis/rembg/llms.txt Download an image from a URL using curl and pipe it to rembg for processing, saving the result to a file. ```bash curl -s https://example.com/photo.jpg | rembg i > output.png ``` -------------------------------- ### CLI: Batch Folder Processing Source: https://context7.com/danielgatis/rembg/llms.txt Process all images within a specified input folder and save the results to an output folder. Supports recursive processing. ```bash rembg p ./input_folder ./output_folder ``` -------------------------------- ### HTTP API: Remove Background from File Upload (POST) Source: https://context7.com/danielgatis/rembg/llms.txt Send a POST request to the '/api/remove' endpoint with the image file attached as form data for background removal. ```bash curl -s -F file=@input.jpg "http://localhost:7000/api/remove" -o output.png ``` -------------------------------- ### Persist downloaded models between Docker runs Source: https://context7.com/danielgatis/rembg/llms.txt This command runs rembg in a Docker container, mounting the host's `~/.u2net` directory to `/root/.u2net` inside the container. This ensures that downloaded models are persisted across container runs, avoiding re-downloading. ```bash docker run -v $(pwd):/data -v ~/.u2net:/root/.u2net \ danielgatis/rembg i /data/input.png /data/output.png ``` -------------------------------- ### CLI: Post-process Mask Source: https://context7.com/danielgatis/rembg/llms.txt Apply post-processing to the mask using the '-ppm' flag for cleaner boundaries in the final output. ```bash rembg i -ppm input.jpg output.png ``` -------------------------------- ### Remove Background with Default Model Source: https://github.com/danielgatis/rembg/blob/main/USAGE.md Removes the background from an image using the default 'u2net' model. The output is a PIL Image object. ```python output = remove(input) output.save(output_path) ``` -------------------------------- ### CLI: Read from Stdin, Write to Stdout Source: https://context7.com/danielgatis/rembg/llms.txt Pipe image data through stdin and capture the processed output from stdout. Useful for integrating with other command-line tools. ```bash cat input.png | rembg i > output.png ``` -------------------------------- ### Post-Process Mask for Better Results Source: https://github.com/danielgatis/rembg/blob/main/USAGE.md Applies post-processing to the mask to improve the final output quality. Use `post_process_mask=True` to activate this. ```python output = remove(input, post_process_mask=True) ``` -------------------------------- ### Video frame processing with alpha matting Source: https://context7.com/danielgatis/rembg/llms.txt This command processes video frames using FFmpeg and `rembg b`, enabling alpha matting for background removal. Raw RGB24 frames are piped from FFmpeg to `rembg b`. ```bash ffmpeg -i input.mp4 -an -f rawvideo -pix_fmt rgb24 pipe:1 | \ rembg b 1280 720 -a -o output/frame-%03u.png ``` -------------------------------- ### Use specific model for video frame processing Source: https://context7.com/danielgatis/rembg/llms.txt This command processes video frames using FFmpeg and `rembg b`, specifying the `u2netp` model for background removal. Raw RGB24 frames are piped from FFmpeg to `rembg b`. ```bash ffmpeg -i input.mp4 -an -f rawvideo -pix_fmt rgb24 pipe:1 | \ rembg b 1280 720 -m u2netp -o output/frame-%03u.png ``` -------------------------------- ### Set Custom Model Storage Directory (Bash) Source: https://context7.com/danielgatis/rembg/llms.txt Specify a custom directory for storing rembg models using the U2NET_HOME environment variable. This affects both library and CLI usage. ```bash # Set custom model storage directory export U2NET_HOME=/path/to/models rembg i input.png output.png ``` -------------------------------- ### Clone Rembg Repository Source: https://github.com/danielgatis/rembg/blob/main/rembg.ipynb Clones the Rembg project repository from Hugging Face. This command downloads all project files to your local machine. ```bash ! git clone https://huggingface.co/spaces/KenjieDec/RemBG ``` -------------------------------- ### Pass Extra Parameters (SAM) with rembg CLI Source: https://github.com/danielgatis/rembg/blob/main/README.md Pass additional parameters, such as SAM prompts, using the -x flag with the rembg CLI. ```shell rembg i -m sam -x '{ "sam_prompt": [{"type": "point", "data": [724, 740], "label": 1}] }' examples/plants-1.jpg examples/plants-1.out.png ``` -------------------------------- ### Batch Processing with Session Reuse (rembg Python Library) Source: https://github.com/danielgatis/rembg/blob/main/README.md Optimize performance for batch processing by creating a session once and reusing it for multiple calls to the remove function. ```python from pathlib import Path from rembg import remove, new_session session = new_session() for file in Path('path/to/folder').glob('*.png'): input_path = str(file) output_path = str(file.parent / (file.stem + ".out.png")) with open(input_path, 'rb') as i: with open(output_path, 'wb') as o: input = i.read() output = remove(input, session=session) o.write(output) ``` -------------------------------- ### Batch Process Folders with rembg CLI Source: https://github.com/danielgatis/rembg/blob/main/README.md Process all images within a specified input folder and save them to an output folder using the rembg CLI. ```shell rembg p path/to/input path/to/output ``` -------------------------------- ### Load Custom Model with Checksum Disabled Source: https://context7.com/danielgatis/rembg/llms.txt Use this when loading a custom ONNX model file and you need to disable checksum verification. Set the MODEL_CHECKSUM_DISABLED environment variable to '1'. ```python import os os.environ["MODEL_CHECKSUM_DISABLED"] = "1" session = new_session("u2net_custom", model_path="/path/to/custom.onnx") ``` -------------------------------- ### CPU Only Docker Usage Source: https://github.com/danielgatis/rembg/blob/main/README.md Run the rembg background removal tool within a Docker container for CPU-only processing, mounting local directories for input and output. ```shell docker run -v .:/data danielgatis/rembg i /data/input.png /data/output.png ``` -------------------------------- ### Remove Background with Alpha Matting Source: https://github.com/danielgatis/rembg/blob/main/USAGE.md Applies alpha matting as a post-processing step to enhance the quality of the background removal. Thresholds and erosion size can be adjusted. ```python output = remove(input, alpha_matting=True, alpha_matting_foreground_threshold=270,alpha_matting_background_threshold=20, alpha_matting_erode_size=11) ``` -------------------------------- ### Remove Background with Specific Model Source: https://github.com/danielgatis/rembg/blob/main/USAGE.md Removes the background using a specified model by creating a session first. This allows for model selection. ```python model_name = "isnet-general-use" session = new_session(model_name) output = remove(input, session=session) ``` -------------------------------- ### CLI: Basic Single File Processing Source: https://context7.com/danielgatis/rembg/llms.txt Process a single input image file and save the output to a specified file. This is the most straightforward usage of the rembg CLI. ```bash rembg i input.png output.png ``` -------------------------------- ### Input/Output as NumPy Array with rembg Python Library Source: https://github.com/danielgatis/rembg/blob/main/README.md Process an image represented as a NumPy array using the rembg library, suitable for integration with computer vision workflows. ```python from rembg import remove import cv2 input = cv2.imread('input.png') output = remove(input) cv2.imwrite('output.png', output) ``` -------------------------------- ### Remove Background from Remote Image using rembg CLI Source: https://github.com/danielgatis/rembg/blob/main/README.md Process a remote image by piping its content to the rembg CLI. Ensure the output is redirected to a file. ```shell curl -s http://input.png | rembg i > output.png ``` -------------------------------- ### Pass Extra Parameters (Custom Model) with rembg CLI Source: https://github.com/danielgatis/rembg/blob/main/README.md Specify custom model paths or parameters using the -x flag with the rembg CLI. ```shell rembg i -m u2net_custom -x '{"model_path": "~/.u2net/u2net.onnx"}' path/to/input.png path/to/output.png ``` -------------------------------- ### Remove Background from Local File using rembg CLI Source: https://github.com/danielgatis/rembg/blob/main/README.md Process a local image file using the rembg CLI, specifying input and output paths. ```shell rembg i path/to/input.png path/to/output.png ``` -------------------------------- ### Run rembg with Docker (CPU) Source: https://context7.com/danielgatis/rembg/llms.txt This command runs the rembg image processing command within a Docker container. It mounts the current directory to `/data` inside the container, allowing input and output files to be accessed from the host. This is for CPU processing. ```bash docker run -v $(pwd):/data danielgatis/rembg i /data/input.png /data/output.png ``` -------------------------------- ### Control ONNX Runtime Threading (Bash) Source: https://context7.com/danielgatis/rembg/llms.txt Adjust the number of threads used by ONNX Runtime for processing. Set the OMP_NUM_THREADS environment variable to the desired number. ```bash # Control ONNX Runtime threading export OMP_NUM_THREADS=4 rembg i input.png output.png ``` -------------------------------- ### Save Processed Image Source: https://github.com/danielgatis/rembg/blob/main/USAGE.md Saves the processed image to a specified output path. This is typically done after the background removal process. ```python output.save(output_path) ``` -------------------------------- ### Remove Background from Uploaded Image via API Source: https://github.com/danielgatis/rembg/blob/main/README.md Use curl to upload an image file to the rembg server's API for background removal. ```shell curl -s -F file=@/path/to/input.jpg "http://localhost:7000/api/remove" -o output.png ``` -------------------------------- ### Force Output as Bytes with rembg Python Library Source: https://github.com/danielgatis/rembg/blob/main/README.md Ensure the output of the remove function is bytes, even if the input was a different type, by using the force_return_bytes=True parameter. ```python from rembg import remove with open('input.png', 'rb') as i: with open('output.png', 'wb') as o: input = i.read() output = remove(input, force_return_bytes=True) o.write(output) ``` -------------------------------- ### CLI: Delete Input Files After Batch Processing Source: https://context7.com/danielgatis/rembg/llms.txt Configure batch processing to delete the original input files after they have been successfully processed. ```bash rembg p -d ./input ./output ``` -------------------------------- ### Disable Model Checksum Verification (Bash) Source: https://context7.com/danielgatis/rembg/llms.txt Disable checksum verification for models, typically used with custom models. This is achieved by setting the MODEL_CHECKSUM_DISABLED environment variable to '1'. ```bash # Disable model checksum verification (for custom models) export MODEL_CHECKSUM_DISABLED=1 rembg i -m u2net_custom -x '{"model_path": "/path/to/custom.onnx"}' input.png output.png ``` -------------------------------- ### Replace Background Color Source: https://github.com/danielgatis/rembg/blob/main/USAGE.md Replaces the removed background with a specified color using the `bgcolor` argument. The color is defined as an RGBA tuple. ```python output = remove(input, bgcolor=(255, 255, 255, 255)) ``` -------------------------------- ### Watch Mode for Folder Processing with rembg CLI Source: https://github.com/danielgatis/rembg/blob/main/README.md Enable watch mode with the -w flag to automatically process new or changed files in a folder using the rembg CLI. ```shell rembg p -w path/to/input path/to/output ``` -------------------------------- ### Return Only Mask with rembg CLI Source: https://github.com/danielgatis/rembg/blob/main/README.md Use the -om flag to extract only the alpha mask from an image using the rembg CLI. ```shell rembg i -om path/to/input.png path/to/output.png ``` -------------------------------- ### Remove Background from Image URL via API Source: https://github.com/danielgatis/rembg/blob/main/README.md Use curl to send a request to the rembg server's API to remove the background from a remote image URL. ```shell curl -s "http://localhost:7000/api/remove?url=http://input.png" -o output.png ``` -------------------------------- ### Extract Only the Mask Source: https://github.com/danielgatis/rembg/blob/main/USAGE.md Retrieves only the mask of the foreground object, discarding the background. Set `only_mask=True` to enable this feature. ```python output = remove(input, only_mask=True) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.