
Deep Learning Background Removal (Transparent / RGBA)
Source:R/utils_neural.R
image_remove_bg_dl.RdRemoves the background of an image using pre-trained Deep Learning models, producing a 4-channel RGBA image with a transparent background by default, or replacing the background with a solid color.
Usage
image_remove_bg_dl(
img,
model = c("rmbg-1.4", "rmbg-2.0", "u2netp", "ben2", "grounded-sam", "sam2.1", "persam",
"withoutbg", "birefnet-lite", "isnet-general-use", "silueta", "u2net"),
threshold = 0.5,
fill_hull = TRUE,
filter = 0,
erode = 0,
dilate = 0,
opening = 0,
closing = 0,
min_area = 0,
invert = FALSE,
pick_object = FALSE,
prompt = NULL,
exemplar = FALSE,
threads = 0,
engine = c("gpu", "cpu"),
device_id = -1,
verbose = TRUE,
transparent = TRUE,
bg_color = "black",
plot = TRUE,
dir = pliman_model_dir(),
...
)
image_remove_bg(
img,
model = c("rmbg-1.4", "u2netp", "ben2", "grounded-sam", "sam2.1", "persam", "rmbg-2.0",
"withoutbg", "birefnet-lite", "isnet-general-use", "silueta", "u2net"),
threshold = 0.5,
fill_hull = TRUE,
filter = 0,
erode = 0,
dilate = 0,
opening = 0,
closing = 0,
min_area = 0,
invert = FALSE,
pick_object = FALSE,
prompt = NULL,
exemplar = FALSE,
threads = 0,
engine = c("gpu", "cpu"),
device_id = -1,
verbose = TRUE,
transparent = TRUE,
bg_color = "black",
plot = TRUE,
dir = pliman_model_dir(),
...
)Arguments
- img
An
imageobject, 2D grayscale matrix, 3D color array (RGB/RGBA), or alistof images/arrays. When a list is passed, each element is automatically processed in batch, returning a corresponding list of binary masks.- model
Character string specifying the pre-trained neural network architecture to use:
General Salient Object Detection & Background Extraction:
"u2netp"(default): Ultra-lightweight U2-Net Portable (~4.6 MB, 320x320 input). Highly recommended for rapid CPU batch processing on standard laptops without requiring a dedicated GPU."ben2"(or"ben"): Boundary-aware Extraction Network Base (~212.6 MB, 1024x1024 input). High-accuracy crisp boundary extraction, exceptional for fine leaf contours, intricate roots, thin petioles, and plant serrations."rmbg-1.4"(or"rmbg"): BRIA AI RMBG 1.4 (~176.1 MB, 1024x1024 input). Enterprise-grade salient foreground extractor trained on diverse commercial datasets, exceptionally robust against studio lighting, reflections, and shadows."rmbg-2.0": BRIA AI RMBG 2.0 (~976.9 MB, 1024x1024 input). Next-generation BiRefNet-based model for maximum boundary detail, fine textures, and translucent edge matting."isnet-general-use": Intermediate Supervision Network (~178.6 MB, 1024x1024 input). High-precision boundary matting, ideal for subtle leaf lesions, chlorotic halos, and fine botanical structures."withoutbg": withoutBG Open Weights (~433.4 MB, 448x448 input). Combines DepthAnythingV2 3D depth features with ConvNeXt-fused U-Net matting, excelling in depth-cluttered backgrounds."birefnet-lite"(or"birefnet"): Bilateral Reference Network Lite (~213.6 MB, 1024x1024 input). Bilateral reference architecture specialized in dichotomous image segmentation and complex shapes."silueta": Compact silhouette extraction model (~44.2 MB, 320x320 input). Fast inference with solid accuracy on edge/CPU hardware."u2net": Full-depth U2-Net architecture (~176.3 MB, 320x320 input). Deep multi-scale salient object detection model.
Zero-Shot & Interactive Foundation Models:
"grounded-sam": Zero-shot open-vocabulary text-prompted instance segmentation (~314.8 MB: Grounding DINO Tiny + SAM 2.1). Detects and segments specific concepts described in natural language (e.g.,prompt = "leaf",prompt = "fruit",prompt = "insect")."persam": Personalize Segment Anything via SAM 2.1 embeddings (~120.2 MB, 1024x1024 input). Segments all instances visually similar to one or more user-clicked exemplar objects using Multi-Prototype Cosine Similarity Max-Pooling."sam2.1"(or"sam2"): Meta AI Segment Anything 2.1 (Hiera-Tiny, ~120.2 MB, 1024x1024 input). Foundation vision transformer supporting point prompts, box prompts, or interactive clicking (pick_object = TRUE).
- threshold
Numeric value in
[0, 1]specifying the cutoff threshold applied to the model's continuous probability/logit output map. Default is0.5. Increasing this threshold (e.g.,0.7) makes segmentation more conservative (avoiding background noise), whereas decreasing it (e.g.,0.3) includes faint, thin, or translucent object edges.- fill_hull
Logical. If
TRUE(default), automatically fills internal holes and voids (such as specular glare or reflective spots) within the segmented foreground object using morphological hole reconstruction (fill_holes_cpp()).- filter
Integer specifying the window radius for binary median filtering (
median_filter_binary_cpp()). Default is0(disabled). A positive value (e.g.,2or3) eliminates salt-and-pepper noise and smoothes jagged boundaries without blurring sharp object corners.- erode
Integer specifying the radius for morphological erosion (
erode_cpp()). Default is0(disabled). Shrinks foreground boundaries inward by the given pixel radius, useful for severing thin touching bridges between adjacent objects or removing outer halo artifacts.- dilate
Integer specifying the radius for morphological dilation (
dilate_cpp()). Default is0(disabled). Expands foreground boundaries outward by the given pixel radius, useful for restoring peripheral details or slightly undersized masks.- opening
Integer specifying the radius for morphological opening (erosion followed by dilation). Default is
0(disabled). Removes small stray islands and thin protrusions while preserving overall object geometry.- closing
Integer specifying the radius for morphological closing (dilation followed by erosion). Default is
0(disabled). Fuses narrow internal cracks, gaps, and small indentations along the perimeter.- min_area
Integer minimum object size in pixels evaluated via connected component labeling (
bwlabel_cpp()). If positive, discards all foreground connected components smaller than this area. If0(default), automatically isolates and retains only the single largest connected component in the image.- invert
Logical. If
TRUE, inverts the output binary mask such that foreground becomes0and background becomes1. Default isFALSE.- pick_object
Logical. If
TRUE, activates an interactive graphics prompt viagraphics::locator(), allowing the user to directly click on the object(s) of interest in the plot window to guide SAM models. Press<Esc>or right-click when finished. Default isFALSE.- prompt
Flexible prompt specification for SAM, Grounded-SAM, and PerSAM models:
NULL(default): Defaults to the center of the imagec(width / 2, height / 2)for SAM models.Character string (e.g.,
"leaf","fruit","weed"): Triggers Grounded-SAM open-vocabulary object detection.Numeric vector
c(x, y): Coordinates of a single foreground point prompt or single visual exemplar.Two-column numeric matrix or data frame
cbind(x, y): Specifies multiple positive point prompts or multiple exemplar prototypes.Numeric vector of length 4
c(xmin, ymin, xmax, ymax): Specifies a bounding box prompt in pixel coordinates. The corners can be given in any order (e.g.c(x1, y2, x2, y1), as ingraphics::rect()); they are sorted internally."center": Uses the image center coordinatesc(width / 2, height / 2)."box": Uses a bounding box spanning the full image canvas.
- exemplar
Logical. If
TRUE(or ifmodel = "persam"), activates one-shot visual exemplar segmentation (PerSAM) using SAM 2.1 embeddings. Default isFALSE.- threads
Integer specifying the number of threads for parallel ONNX Runtime execution. Default is
0, which automatically detects and utilizes all available logical CPU cores on the system.- engine
Character specifying the backend execution engine:
"cpu"(default) or"gpu". On Windows,"gpu"utilizes Microsoft DirectML over DirectX 12 hardware (compatible with NVIDIA, AMD, and Intel GPUs without requiring CUDA toolkit installation). Inimage_segment_dl(), whenengineis not given, Grounded-SAM and PerSAM use the GPU whenever a dedicated GPU is present (only integrated or absent GPUs default to the CPU). Withengine = "gpu", Grounded-SAM runs Grounding DINO on the GPU and SAM 2.1 on the GPU too, except on GPUs with less than 6 GB of memory, where SAM 2.1 runs on the CPU so that both models stay loaded (about 4x faster than the CPU alone and much faster than reloading the models for every image on a 4 GB card); force the SAM device withoptions(pliman.gsam_sam_device = "gpu")or"cpu". Speed-ups depend on the GPU and driver.- device_id
Integer GPU device adapter index. Default is
-1, which automatically selects the high-performance discrete GPU adapter with the maximum dedicated video memory (VRAM).- verbose
Logical. If
TRUE(default), displays step-by-step progress feedback and timing indicators viacli::cli_progress_step(). Set toFALSEfor silent execution in automated pipelines.- transparent
Logical. If
TRUE(default), returns a 4-channel RGBAimageobject where background pixels have an alpha channel value of0(100% transparent).- bg_color
Optional background color to fill when
transparent = FALSE. Accepts standard R color names (e.g.,"white","black") or hex strings (e.g.,"#FFFFFF"). Defaults to"black".- plot
Logical. If
TRUE(default), renders the resulting binary mask to the active graphics device.- dir
Character string specifying the local directory where ONNX model files are stored and cached. Defaults to
pliman_model_dir().- ...
Additional arguments passed down to internal plotting methods.
Value
An image object (4-channel RGBA if transparent = TRUE, 3-channel RGB otherwise) or a list of images.
License notice
The default model ("rmbg-1.4") and "rmbg-2.0", both from BRIA AI, are licensed for
non-commercial use only. In general, the pre-trained models available through
pliman are provided for research and non-commercial use; see
system.file("MODEL_LICENSES.md", package = "pliman") for the license of each model.
Examples
if (FALSE) { # interactive()
library(pliman)
flower <- image_pliman("flaxflower.jpg")
# Robust background removal under complex shadows and reflections
img_rmbg <- image_remove_bg_dl(flower, model = "rmbg-1.4")
# Replace background with solid white
img_white <- image_remove_bg_dl(flower, transparent = FALSE, bg_color = "red")
# Keep only the objects described by a text prompt (Grounded-SAM): the flowers,
# without the hand that holds them
img_flowers <- image_remove_bg_dl(flower, model = "grounded-sam", prompt = "flower")
}