Skip to contents

Segments foreground objects (such as leaves, fruits, seeds, grains, roots, animals, or plants) from complex, textured, or out-of-focus backgrounds using pre-trained Deep Learning models in ONNX format.

Usage

image_segment_dl(
  img,
  type = c("highlight", "segment", "mask"),
  col_background = "white",
  col_highlight = "salmon",
  mask_color = NULL,
  alpha = 0.7,
  border = NA,
  lwd = 1,
  bbox = FALSE,
  mask = TRUE,
  cex = 1,
  pad = 0,
  badge_pad = 1,
  show_text = TRUE,
  show_conf = TRUE,
  show_class = TRUE,
  show_id = FALSE,
  show_point = FALSE,
  show_box = NULL,
  point_size = 1,
  point_pch = 16,
  point_col = NULL,
  badge = TRUE,
  rainbow = TRUE,
  model = c("rmbg-1.4", "u2netp", "ben2", "yolo26n-seg", "stardist", "grounded-sam",
    "sam2.1", "persam", "rmbg-2.0", "withoutbg", "birefnet-lite", "isnet-general-use",
    "silueta", "u2net"),
  threshold = 0.5,
  box_threshold = 0.25,
  text_threshold = 0.25,
  iou_threshold = 0.5,
  exemplar = FALSE,
  sim_threshold = 0.5,
  min_dist = 16,
  feat_res = 256,
  max_objects = NULL,
  superres_map = FALSE,
  return_features = FALSE,
  feature_model = c("yolo", "clip-vit-b32", "dinov2"),
  plot_features = FALSE,
  threads = 0,
  engine = c("gpu", "cpu"),
  sam_device = c("auto", "gpu", "cpu"),
  device_id = -1,
  fill_hull = TRUE,
  filter = 0,
  erode = 0,
  dilate = 0,
  opening = 0,
  closing = 0,
  min_area = 0,
  invert = FALSE,
  pick_object = FALSE,
  prompt = NULL,
  classes = NULL,
  filter_nested = TRUE,
  show_mask = FALSE,
  verbose = TRUE,
  plot = TRUE,
  dir = pliman_model_dir(),
  imgsz = NULL,
  ...
)

Arguments

img

An image object, 2D grayscale matrix, 3D color array (RGB/RGBA), or a list of images/arrays. When a list is passed, each element is automatically processed in batch, returning a corresponding list of binary masks.

type

Character specifying the visual and output modality:

  • "highlight"(default): Overlays the original image with semi-transparent colored polygons covering each detected instance, ideal for visual inspection, quality control, and publication figures.

  • "segment": Returns an image object where detected foreground is preserved and background is replaced by a solid color specified by col_background.

  • "mask": Returns the binary mask (for semantic models) or single multi-label integer instance map (for YOLO-seg, StarDist, Grounded-SAM, and PerSAM) as an image object (colormode = "Grayscale"). When mask = FALSE, overlays bounding boxes directly.

  • "boxes": Overlays bounding boxes on the original image and returns a data frame of detected boxes.

col_background

Character string or hex code specifying the solid background color when type = "segment". Defaults to "white". Accepts any valid R color name (e.g., "black", "transparent") or hexadecimal code (e.g., "#FFFFFF"). When set to "transparent", "none", or NA, returns an image with an alpha transparency channel (4 channels, RGBA).

col_highlight

Fill color for the semi-transparent overlay polygon when type = "highlight". Defaults to "salmon". When multiple instances are detected, distinct categorical colors are automatically generated from a rainbow palette.

mask_color

Fill color(s) for the highlight polygon overlay and bounding boxes when type = "highlight". Defaults to NULL (falling back to col_highlight). When rainbow = FALSE, allows passing a vector of colors with the same length as the classes specified in prompt (e.g. mask_color = c("red", "green") for prompt = c("red tomato", "green tomato")), or a named vector matching class names (e.g., c("red tomato" = "red", "green tomato" = "green")).

alpha

Numeric transparency value in [0, 1] for the highlight polygon overlay when type = "highlight". Default is 0.4 (40% opacity).

border

Color for the border stroke of the highlight polygon when type = "highlight". Default is NA (no border stroke).

lwd

Numeric line width for the bounding boxes and highlight polygon contours. Default is 1 for the contours. When lwd is not given, bounding boxes are drawn with width 2; when it is given, the same width is used for both. Values below 1 draw thinner lines.

bbox

Logical. If TRUE, draws YOLO-style bounding boxes with class labels and confidence scores around detected instances. Defaults to FALSE.

mask

Logical. If TRUE (default), computes pixel-accurate instance or semantic masks. When mask = FALSE and bbox = TRUE, skips the mask decoder step and returns only the detected bounding box coordinates (fast object detection). Defaults to TRUE.

cex

Size factor for bounding box label text (default 1.5). Use smaller values (e.g., 0.2 or 0.5) to reduce text size for dense scenes or many objects.

pad

Padding added to expand bounding boxes around detected instances when bbox = TRUE (default 0). Can be an absolute number of pixels (e.g., pad = 10), a relative expansion fraction when between 0 and 1 (e.g., pad = 0.05 for 5% margin), or a length-2 vector c(pad_x, pad_y).

badge_pad

Padding multiplier controlling the background badge size around label text (default 1.0). Use badge_pad = 0 for a badge fitting tightly to the text.

show_text

Logical. Whether to display text labels on bounding boxes (default TRUE).

show_conf

Logical. Whether to display confidence scores in labels (default TRUE).

show_class

Logical. Whether to display class names in labels (default TRUE).

show_id

Logical. If TRUE, overlays object instance IDs in bounding box labels or at their center of mass (computed via poly_mass()) when type = "highlight" and bbox = FALSE. Defaults to FALSE.

show_point

Logical. Whether to show a point at the centroid of each segmented object. Defaults to FALSE.

show_box

Logical. Whether to draw bounding boxes. Defaults to NULL (drawn if bbox = TRUE).

point_size

Numeric. Size (cex) of the centroid point when show_point = TRUE. Defaults to 1.

point_pch

Integer. Plotting symbol (pch) for the centroid point. Defaults to 16 (filled circle).

point_col

Character. Color of the centroid point. Defaults to NULL (matches the object color / rainbow).

badge

Logical. Whether to draw a solid background badge behind label text (default TRUE). If FALSE, only the text is drawn directly.

rainbow

Logical. If TRUE, assigns a distinct, unique color to each segmented object. If FALSE, objects of the same class share the exact same color (using col_highlight / mask_color). Defaults to TRUE unless col_highlight or mask_color is explicitly provided.

model

Model architecture or path to a custom ONNX file. Built-in choices:

  • "yolo26n-seg" (or "yolo26s-seg", "yolo26m-seg", "yolo26l-seg", "yolo26x-seg"): YOLO26 Instance Segmentation (real-time polygon mask & box detection, 80 COCO categories).

  • "stardist" (or "stardist-dsb2018"): StarDist star-convex radial polygon segmentation for overlapping grains/cells.

  • "grounded-sam": Zero-shot open-vocabulary instance segmentation prompted by text.

  • "persam": One-shot visual exemplar segmentation guided by reference click points.

  • "u2netp", "u2net": U2-Net salient foreground cutout (fast CPU-friendly default).

  • "ben2": Boundary-aware Enhanced Network (BEN2) for razor-sharp leaf margins, serrations, and roots.

  • "rmbg-1.4", "rmbg-2.0": BRIA state-of-the-art commercial-grade background removal.

  • "withoutbg", "birefnet-lite", "isnet-general-use", "silueta": Specialized salient cutout backends.

threshold

Numeric value in [0, 1] specifying the cutoff threshold applied to the model's continuous probability/logit output map. Default is 0.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.

box_threshold

Numeric confidence threshold in [0, 1] for Grounded-SAM and YOLO detection bounding box proposals. Default is 0.25.

text_threshold

Numeric token logit confidence threshold in [0, 1] for Grounded-SAM text-to-box association. Default is 0.25.

iou_threshold

Numeric Non-Maximum Suppression (NMS) Intersection over Union (IoU) threshold in [0, 1] for deduplicating overlapping bounding box proposals. Default is 0.5.

exemplar

Logical. If TRUE (or if model = "persam"), activates one-shot visual exemplar segmentation (PerSAM) using SAM 2.1 embeddings. The user can click on 1 or more representative exemplar objects in the plot window (or pass coordinates via prompt), and the model will automatically compute visual feature embeddings, search the entire image for all similar instances via cosine similarity, and segment all matching objects. Multi-Prototype Max-Pooling: When multiple exemplars are clicked (e.g., one bright log, one dark log, one with moss), each click forms an independent 256-D prototype vector. The similarity map calculates the maximum cosine similarity against any prototype, preventing vector dilution and capturing wide visual diversity without prototype cancellation. Default is FALSE.

sim_threshold

Numeric cosine similarity threshold in [0, 1] for PerSAM visual exemplar matching. Higher values (e.g. 0.55 - 0.65) require closer visual resemblance, while lower values (e.g. 0.40 - 0.50) capture more diverse, shadowed, or smaller instances. Default is 0.5.

min_dist

Numeric minimum spatial distance in pixels (within the 1024x1024 embedding space) between candidate peaks to prevent duplicate instance detections of the same object. Default is 16.

feat_res

Spatial resolution / algorithm for exemplar matching. Options:

  • 64 (or "fast", "vit", "low"): Fast 64x64 ViT patch token matching (stride 16). Extremely fast and ideal for large objects (e.g. people, leaves, fruits, animals).

  • 256 (or "medium"): 256x256 multi-scale CNN feature fusion (stride 4).

  • 1024 (or "dense", "conv", "high", "grain"): Dense Stride-1 Convolutional Exemplar matching at full 1024x1024 pixel resolution with single-pass Zero-Mean Normalized Cross-Correlation (ZNCC) and ViT semantic guidance. Essential for resolving small touching objects, seeds, and grains with sharp pixel boundaries. Defaults to 256.

max_objects

Maximum number of instances to detect and segment. Default is 300.

superres_map

Logical. If TRUE, applies Real-ESRGAN neural super-resolution to upscale the PerSAM similarity map for finer object boundaries and visualization. Defaults to FALSE.

return_features

Logical. If TRUE, extracts deep feature representations for detected or segmented objects and the global image. Attaches "features" (an \(N \times D\) matrix of per-object deep embeddings, 512-D for CLIP or 384-D for DINOv2) and "feature_map" (dense spatial 3-component PCA false-color Image) as attributes to the returned object. Defaults to FALSE.

feature_model

Foundation model used for feature representation when return_features = TRUE. Options are "clip-vit-b32" (default, OpenAI CLIP ViT-B/32 producing 512-D semantic embeddings) or "dinov2" (Meta DINOv2-S ViT producing 384-D self-supervised patch embeddings).

plot_features

Logical. If TRUE and return_features = TRUE, visualizes the dense spatial PCA feature map. Defaults to FALSE.

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). In image_segment_dl(), when engine is not given, Grounded-SAM and PerSAM use the GPU whenever a dedicated GPU is present (only integrated or absent GPUs default to the CPU). With engine = "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 with options(pliman.gsam_sam_device = "gpu") or "cpu". Speed-ups depend on the GPU and driver.

sam_device

Execution device for SAM 2.1 inference: "auto" (default), "gpu", or "cpu".

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).

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 is 0 (disabled). A positive value (e.g., 2 or 3) 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 is 0 (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 is 0 (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. If 0 (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 becomes 0 and background becomes 1. Default is FALSE.

pick_object

Logical. If TRUE, activates an interactive graphics prompt via graphics::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 is FALSE.

prompt

Flexible prompt specification for SAM, Grounded-SAM, and PerSAM models:

  • NULL (default): Defaults to the center of the image c(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 in graphics::rect()); they are sorted internally.

  • "center": Uses the image center coordinates c(width / 2, height / 2).

  • "box": Uses a bounding box spanning the full image canvas.

classes

Optional character or numeric vector of target classes to keep/filter. When specified, only detected instances matching these classes are kept, segmented, and plotted.

filter_nested

Logical. If TRUE (the default), removes larger container bounding boxes that enclose smaller boxes of the same class (e.g. discarding an encompassing box around an entire branch of leaves).

show_mask

Deprecated. If TRUE, equivalent to type = "mask".

verbose

Logical. If TRUE (default), displays step-by-step progress feedback and timing indicators via cli::cli_progress_step(). Set to FALSE for silent execution in automated pipelines.

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().

imgsz

Target input image resolution for YOLO segmentation inference (e.g., 640, 960, or 1024). If NULL (default), inferred automatically from the model or defaults to 640.

...

Additional arguments passed down to internal plotting methods.

Value

  • If mask = FALSE and bbox = TRUE: A data frame containing the bounding box coordinates (id, xmin, ymin, xmax, ymax, score, label).

  • If type = "segment": An image object containing the segmented image.

  • If type = "mask": A single multi-label or binary image object (colormode = "Grayscale").

  • If type = "highlight": Invisibly returns a list with:

    • "results": Data frame of detected bounding boxes, scores, and morphometric traits.

    • "labels": Single multi-label integer mask image where each pixel value corresponds to instance id.

    • "summary": Text summary of detected objects and counts.

    • "counts": Data frame of instance counts per class label.

    • "contours": List of polygon contour coordinate matrices.

    • "features": If return_features = TRUE, numeric matrix of per-object deep feature embeddings.

    • "feature_map": If return_features = TRUE, dense spatial 3-component PCA false-color Image.

    • "similarity_map": Continuous cosine similarity image object (when exemplar = TRUE).

  • If img is a list: A list of the corresponding outputs.

Details

This unified function supports five major computer vision workflows:

  1. Salient Foreground Segmentation & Background Removal: Semantic cutout using architectures such as U2-Net, BEN2, BRIA RMBG 1.4/2.0, IS-Net, withoutBG, BiRefNet, and Silueta.

  2. Real-Time YOLO26 Instance Segmentation (yolo26n-seg): Real-time instance segmentation combining bounding box detection with 32 prototype mask channels and continuous bilinear sub-pixel interpolation. Returns a single multi-label mask image (type = "mask"), smooth polygon overlays (type = "highlight"), or background cutouts (type = "segment"), accompanied by per-instance morphological measurements (area, perimeter, circularity, etc.).

  3. Star-Convex Object Detection & Segmentation (stardist): Predicts 48 radial star-convex distance rays and object probability, specifically tailored for densely packed, touching, or convex structures such as seeds, grains, nuclei, and cells.

  4. Zero-Shot Text-Prompted Detection & Instance Segmentation (Grounded-SAM): Combines Grounding DINO with SAM 2.1 to locate, outline, and count arbitrary concepts described in natural language (e.g., prompt = "leaf, fruit, insect").

  5. One-Shot Visual Exemplar Segmentation & Counting (PerSAM): Personalize Segment Anything via SAM 2.1. The user clicks on 1 or more exemplar objects (or provides coordinates), and the algorithm automatically searches, segments, and counts all visually similar objects across the entire image using Multi-Prototype Max-Pooling.

Examples

if (FALSE) { # interactive()
  library(pliman)

  # ---- Foreground (background removal) segmentation: flax flowers ----
  flower <- image_pliman("flaxflower.jpg")

  # 1. Basic salient foreground segmentation with white background (rmbg-1.4)
  seg <- image_segment_dl(flower, model = "rmbg-1.4")

  # 2. Zero-shot text-prompted instance segmentation (Grounded-SAM)
  # Finds and segments every flax flower, displaying bounding boxes
  res_gs <- image_segment_dl(
    flower,
    model = "grounded-sam",
    prompt = "flower",
    type = "highlight",
    bbox = TRUE
  )
  # Inspect counts and morphological measures
  res_gs$counts
  head(res_gs$results)

  # 3. One-shot visual exemplar segmentation (PerSAM):
  # A point (x, y) on the blue flower finds all similar flowers.
  # Leave `prompt` out to click on the exemplar(s) in the plot window instead.
  res_persam <- image_segment_dl(
    flower,
    exemplar = TRUE,
    prompt = c(565, 340),
    sim_threshold = 0.6,
    type = "highlight",
    bbox = TRUE
  )

  # 4. Multi-prototype exemplar segmentation: one point on each flower
  # (white and blue); each point is a separate prototype.
  pts <- rbind(c(330, 370), c(565, 340))
  res_multi <- image_segment_dl(
    flower,
    exemplar = TRUE,
    prompt = pts,
    sim_threshold = 0.65,
    type = "highlight"
  )


  # ---- Instance segmentation and detection: a farm scene ----
  farm <- image_pliman("farm.jpg")

  # 5. YOLO26 instance segmentation (real-time polygon mask & box detection)
  res_yolo <- image_segment_dl(
    farm,
    model = "yolo26n-seg",
    type = "highlight",
    bbox = TRUE
  )
  res_yolo$counts
  head(res_yolo$results[, c("label", "score", "area", "perimeter")])

  # 6. Keep only some classes
  image_segment_dl(farm, model = "yolo26n-seg", classes = c("cow", "dog"), type = "highlight")

  # 7. Text-prompted segmentation of classes YOLO was not trained on
  people <- image_segment_dl(
    farm,
    model = "grounded-sam",
    prompt = "people",
    type = "highlight",
    bbox = TRUE
  )

  # 8. Fast text-prompted detection without mask generation
  # (skips SAM 2.1, returning only the bounding boxes)
  boxes <- image_segment_dl(
    farm,
    model = "grounded-sam",
    prompt = "people",
    mask = FALSE,
    bbox = TRUE
  )

  # 9. SAM 2.1 with a box prompt c(xmin, ymin, xmax, ymax): the man in the center
  res_box <- image_segment_dl(farm,
   model = "sam2.1",
   prompt = c(312, 285, 390, 485),
   bbox = TRUE,
   type = "highlight")
}