rembg-rs
A Rust library for removing backgrounds from images using neural networks (ONNX Runtime + U2-Net).
๏ฟฝ Features
- ๐จ Remove backgrounds from images using pretrained neural networks
- ๐ง Flexible API for library and CLI usage
- ๐ฆ Multiple models available (universal, human segmentation, fast)
- โ๏ธ Configurable postprocessing (threshold, binary mode)
- ๐ญ Export masks separately
- ๐ผ๏ธ Support for PNG, JPEG, WebP formats
- ๐ Well-documented English API
๐ Requirements
- Rust 1.70+
- ONNX Runtime (installed automatically via
ortcrate)
๐๏ธ Installation
As a Library (for Discord bots, web services, etc.)
Add to your Cargo.toml:
[]
= { = "https://github.com/WarRaft/rembg-rs" }
As a CLI Tool
[]
= { = "https://github.com/WarRaft/rembg-rs", = ["cli"] }
Or build from source:
๐ Library Usage
Basic Example
use ;
use open;
use Path;
Advanced Example (for Discord bots)
use ;
use load_from_memory;
use Path;
Memory Management
The library uses memory-mapped model loading - OS automatically manages memory:
- If you have enough RAM, model stays in memory for fast inference
- If RAM is low, OS can swap model to disk and load on demand
- Perfect for long-running Discord bots
- No manual memory management needed
See examples/ for more usage examples.
๐ฏ Models
Download Models
Available models:
- u2net.onnx (~176 MB) - Universal model for any images, best for art
- u2net_human_seg.onnx (~176 MB) - Specialized for human portraits
- silueta.onnx (~43 MB) - Fast and lightweight
๏ฟฝ๏ธ CLI Usage
# Basic usage
# With custom threshold (0.0-1.0)
# Binary mode (clean cutout, no semi-transparency)
# Save mask alongside result
CLI Parameters
-i, --input <PATH>- Input image path-o, --output <PATH>- Output image path-m, --model <PATH>- Model file path (default: u2net.onnx)-t, --threshold <0.0-1.0>- Threshold (default: 0.5)- 0.3-0.4: Soft edges
- 0.5: Balanced
- 0.6-0.7: Clean cutout
-b, --binary- Binary mode (no semi-transparency)-s, --save-mask- Save mask as separate file-q, --quality <1-100>- JPEG quality (default: 95)
๐งช Testing
- Download models:
-
Add test images to
test_input/directory -
Run the test script:
๐ API Documentation
Rembg
Main struct for background removal operations.
Methods:
new(model_path: &str) -> Result<Self>- Create new instance with ONNX modelremove_background(image, options) -> Result<RemovalResult>- Process DynamicImage
RemovalOptions
Configuration for background removal.
Fields:
threshold: f32- Alpha matting threshold (0.0-1.0)binary: bool- Binary mode (hard cutout vs soft edges)
Methods:
default()- Create with default values (threshold: 0.5, binary: false)with_threshold(f32)- Set thresholdwith_binary_mode(bool)- Set binary mode
RemovalResult
Result of background removal.
Fields:
image: RgbaImage- Processed image with transparent backgroundmask: GrayImage- Mask used for removal (0-255)
Methods:
image()- Get reference to RGBA imagemask()- Get reference to grayscale maskinto_parts()- Consume and return (image, mask)
Note: File I/O operations are not part of the library core API.
Use the image crate to load/save images as needed.
๐๏ธ Architecture
Memory Management
The library uses memory-mapped model loading for optimal memory efficiency:
// Model is memory-mapped, not loaded into RAM
let mut rembg = new?;
How it works:
- Model file is mapped into virtual memory (not loaded into RAM)
- OS kernel decides whether to cache pages in physical RAM
- If RAM is available: frequently used pages stay cached
- If RAM is low: OS swaps pages as needed
- No manual memory management required
Usage:
use Path;
// Simple and efficient
let mut rembg = new?;
Benefits for Discord bots:
- โ Model loaded once at startup
- โ OS automatically optimizes memory usage
- โ Multiple bots can share same model file (copy-on-write)
- โ No memory spikes during processing
- โ Efficient for long-running processes
Memory usage:
- Model file size: ~176 MB (u2net) or ~43 MB (silueta)
- Actual RAM usage: Managed by OS based on available memory
- Per-image processing: ~20-30 MB temporary buffers
Library Structure
lib.rs- Public API and main typeserror.rs- Error types with detailed documentationimage_processor.rs- Image loading, preprocessing, postprocessingmodel.rs- ONNX Runtime integrationcli.rs- CLI interface (optional, requiresclifeature)main.rs- CLI entry point (requiresclifeature)
Processing Pipeline
- Load Image - Read from file or use existing DynamicImage
- Preprocess - Resize to 320x320, normalize to [-1, 1]
- Inference - Run U2-Net model via ONNX Runtime
- Postprocess Mask - Apply sigmoid, resize back to original size
- Apply Mask - Apply threshold and binary mode, create RGBA output
- Save - Export result and optionally mask
๐ฆ Publishing
This library is designed to be used as a git dependency or published to crates.io.
Features
default = []- Library only, no CLIcli- Enables command-line interface
๐ Credits
- danielgatis/rembg - Original Python implementation and pretrained models
- U2-Net - Neural network architecture
๐ License
MIT License - see LICENSE file