Skip to contents

This function performs a morphological watershed segmentation on a binary image. It implements a highly optimized Spanning Forest algorithm coupled with a Disjoint-Set (Union-Find) data structure. This approach eliminates the need for slow iterative scans ($O(N^2)$ complexity), allowing the algorithm to execute in milliseconds even when resolving tens of thousands of distinct objects. It also features a mechanism to merge highly connected objects, effectively preventing over-segmentation.

Usage

image_watershed(
  img,
  sensitivity = "medium",
  tolerance = NULL,
  ext = 1,
  min_size = NULL,
  rel_size = NULL,
  fill_hull = FALSE,
  max_size = NULL
)

Arguments

img

A binary image object or a matrix/array.

sensitivity

Text ("low", "medium", "high", "extreme") or Number (e.g. 2.5). Automatically defines the best parameters for optimal precision. (Overrides manual adjustment of tolerance).

tolerance

Manual Fine-Tuning. If provided, overrides sensitivity and directly controls the merging threshold for connected components. Values < 1.0 are interpreted as relative tolerance (percentage of the peak height). Values >= 1.0 are interpreted as absolute tolerance in pixels (linear Euclidean distance).

ext

Pixel neighborhood radius (default = 1). Specifies the extension radius used during the regional maxima calculation and watershed flooding.

min_size

Minimum area (in pixels) for an object segment retained after watershed.

rel_size

Relative threshold as a fraction of the mean segment area (e.g. 0.1 for 10% of mean area).

fill_hull

Logical. Fill holes in the binary mask before watershed segmentation. Default is FALSE.

max_size

Maximum area (in pixels) for an object segment retained after watershed. Default is NULL.

Value

A grayscale image object containing the labels.

Examples

if (FALSE) { # interactive()
  library(pliman)
  bin <- image_pliman("soybean_touch.jpg") |> image_binary(index = "B")
  w_med <- image_watershed(bin$B)
}