Skip to content

Segment

geoops.segment wraps skimage.segmentation. Outputs are integer-labelled GeoArrays with the input CRS / transform preserved.

  • Thresholding: Threshold — absolute, Otsu or "percentile:<p>" global threshold to a boolean mask (nodata excluded from the statistic and always False)
  • Superpixels: SLIC, Quickshift, Felzenszwalb
  • Region-based: Watershed, RandomWalker, ChanVese
  • Post-processing: ExpandLabels, MarkBoundaries, MergeNearbyInstances, MaskNMS
  • Tier-A primitives: threshold_mask, otsu_threshold, resolve_threshold, fill_invalid, merge_nearby_instances, mask_nms (geoops.plume.PlumeMask uses the same thresholding)

Operators that accept non-JSON-safe carrier params (mask, markers, label_img) set forbid_in_yaml=True so hydra-zen won't try to round-trip them.

geoops.segment

Segmentation operators backed by :mod:skimage.segmentation.

ChanVese

Bases: Operator

Active-contour segmentation via :func:skimage.segmentation.chan_vese.

Expects a single-band (H, W) or (1, H, W) image. Nodata pixels (non-finite or fill_value) are median-filled before evolution and forced to label 0 in the output. Accepts a GeoArray or a plain np.ndarray and returns an int32 label map (0 = outside, 1 = inside) in the same carrier kind.

Parameters:

Name Type Description Default
mu float

Edge-length penalty weight; higher values give smoother boundaries.

0.25
lambda1 float

Weight of the interior fitting term.

1.0
lambda2 float

Weight of the exterior fitting term.

1.0
tol float

Convergence tolerance on the level set.

0.001
max_num_iter int

Maximum number of iterations.

500
Source code in packages/geotoolz-ops/src/geoops/segment/_src/operators.py
class ChanVese(Operator):
    """Active-contour segmentation via :func:`skimage.segmentation.chan_vese`.

    Expects a single-band ``(H, W)`` or ``(1, H, W)`` image. Nodata pixels
    (non-finite or ``fill_value``) are median-filled before
    evolution and forced to label ``0`` in the output. Accepts a
    ``GeoArray`` or a plain ``np.ndarray`` and returns an ``int32`` label
    map (0 = outside, 1 = inside) in the same carrier kind.

    Args:
        mu: Edge-length penalty weight; higher values give smoother
            boundaries.
        lambda1: Weight of the interior fitting term.
        lambda2: Weight of the exterior fitting term.
        tol: Convergence tolerance on the level set.
        max_num_iter: Maximum number of iterations.
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    coupling: ClassVar[Coupling] = Coupling(couples={"space"}, reach=None)

    def __init__(
        self,
        *,
        mu: float = 0.25,
        lambda1: float = 1.0,
        lambda2: float = 1.0,
        tol: float = 1e-3,
        max_num_iter: int = 500,
    ) -> None:
        self.mu = mu
        self.lambda1 = lambda1
        self.lambda2 = lambda2
        self.tol = tol
        self.max_num_iter = max_num_iter

    @over_frames
    def _apply(self, gt: GeoArrayType | np.ndarray) -> GeoArrayType | np.ndarray:
        chan_vese = optional_name(
            "skimage.segmentation",
            "chan_vese",
            "morph",
            feature="geoops.segment.ChanVese",
        )
        valid = valid_pixels(gt)
        labels = chan_vese(
            single_band(fill_invalid(np.asarray(gt), valid), name="ChanVese"),
            mu=self.mu,
            lambda1=self.lambda1,
            lambda2=self.lambda2,
            tol=self.tol,
            max_num_iter=self.max_num_iter,
        )
        return _labels(gt, labels.astype(np.int32), mask=valid)

ExpandLabels

Bases: Operator

Grow label regions by a fixed pixel distance without overlap.

Wraps :func:skimage.segmentation.expand_labels. Expects a single-band (H, W) or (1, H, W) integer label map. Accepts a GeoArray or a plain np.ndarray and returns an int32 label map in the same carrier kind.

Parameters:

Name Type Description Default
distance float

Euclidean distance (in pixels) by which each labelled region is grown into the background.

1.0
Source code in packages/geotoolz-ops/src/geoops/segment/_src/operators.py
class ExpandLabels(Operator):
    """Grow label regions by a fixed pixel distance without overlap.

    Wraps :func:`skimage.segmentation.expand_labels`. Expects a
    single-band ``(H, W)`` or ``(1, H, W)`` integer label map. Accepts a
    ``GeoArray`` or a plain ``np.ndarray`` and returns an ``int32``
    label map in the same carrier kind.

    Args:
        distance: Euclidean distance (in pixels) by which each labelled
            region is grown into the background.
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    coupling: ClassVar[Coupling] = Coupling(couples={"space"}, reach=1)

    def spatial_reach(self) -> int:
        """The spatial reach in pixels: the expansion distance."""
        return int(np.ceil(self.distance))

    def __init__(self, *, distance: float = 1.0) -> None:
        self.distance = distance

    @over_frames
    def _apply(self, gt: GeoArrayType | np.ndarray) -> GeoArrayType | np.ndarray:
        expand_labels = optional_name(
            "skimage.segmentation",
            "expand_labels",
            "morph",
            feature="geoops.segment.ExpandLabels",
        )
        labels = expand_labels(
            single_band(np.asarray(gt), name="ExpandLabels").astype(
                np.int32, copy=False
            ),
            distance=self.distance,
        )
        return _labels(gt, labels)

spatial_reach()

The spatial reach in pixels: the expansion distance.

Source code in packages/geotoolz-ops/src/geoops/segment/_src/operators.py
def spatial_reach(self) -> int:
    """The spatial reach in pixels: the expansion distance."""
    return int(np.ceil(self.distance))

Felzenszwalb

Bases: Operator

Graph-based segmentation via :func:skimage.segmentation.felzenszwalb.

Nodata pixels (non-finite or fill_value in any band) are median-filled before segmentation and forced to label 0 in the output; valid segments are labelled from 1. Accepts a GeoArray or a plain np.ndarray (channel-first) and returns an int32 label map in the same carrier kind.

Parameters:

Name Type Description Default
scale float

Free parameter controlling segment size; larger values produce larger segments.

1.0
sigma float

Width of the Gaussian pre-smoothing kernel, in pixels.

0.8
min_area_px int

Minimum segment area in pixels, enforced by postprocessing (skimage's min_size).

20
dim str | None

Name of the band dim (default "band"); its position is read from the carrier's dims.

'band'
axis int | None

Deprecated: the band axis position. -3 maps to dim="band"; removed in the next minor release.

None

Called as op(image, mask=None). The optional mask is an (H, W) (or (1, H, W)) boolean carrier on the image's pixel grid (ValueError otherwise); pixels outside it get label 0. Pass it positionally to wire it as a graph input, Felzenszwalb()(Input("image"), Input("mask")).

Source code in packages/geotoolz-ops/src/geoops/segment/_src/operators.py
class Felzenszwalb(Operator):
    """Graph-based segmentation via :func:`skimage.segmentation.felzenszwalb`.

    Nodata pixels (non-finite or ``fill_value`` in any band) are
    median-filled before segmentation and forced to label ``0`` in the
    output; valid segments are labelled from ``1``.
    Accepts a ``GeoArray`` or a plain
    ``np.ndarray`` (channel-first) and returns an ``int32`` label map in
    the same carrier kind.

    Args:
        scale: Free parameter controlling segment size; larger values
            produce larger segments.
        sigma: Width of the Gaussian pre-smoothing kernel, in pixels.
        min_area_px: Minimum segment area in pixels, enforced by
            postprocessing (skimage's ``min_size``).
        dim: Name of the band dim (default ``"band"``); its position is read
            from the carrier's dims.
        axis: Deprecated: the band axis position. ``-3`` maps to
            ``dim="band"``; removed in the next minor release.

    Called as ``op(image, mask=None)``. The optional ``mask`` is an
    ``(H, W)`` (or ``(1, H, W)``) boolean carrier on the image's pixel grid
    (``ValueError`` otherwise); pixels outside it get label ``0``. Pass it
    positionally to wire it as a graph input,
    ``Felzenszwalb()(Input("image"), Input("mask"))``.
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    coupling: ClassVar[Coupling] = Coupling(
        couples={"band", "space"}, effects={"band": "reduce"}, reach=None
    )

    def __init__(
        self,
        *,
        scale: float = 1.0,
        sigma: float = 0.8,
        min_area_px: int = 20,
        dim: str | None = "band",
        axis: int | None = None,
    ) -> None:
        self.scale = scale
        self.sigma = sigma
        self.min_area_px = min_area_px
        self.dim = band_dim(dim, axis, "Felzenszwalb", legacy=(0, -3))

    @over_frames
    def _apply(
        self,
        gt: GeoArrayType | np.ndarray,
        mask: GeoArrayType | np.ndarray | None = None,
    ) -> GeoArrayType | np.ndarray:
        felzenszwalb = optional_name(
            "skimage.segmentation",
            "felzenszwalb",
            "morph",
            feature="geoops.segment.Felzenszwalb",
        )
        _check_input_grid(gt, mask, "Felzenszwalb", "mask")
        valid = valid_pixels(gt)
        image = fill_invalid(np.asarray(gt), valid)
        mask = _as_mask(mask, gt.shape[-2:], name="Felzenszwalb mask")
        if mask is not None:
            valid &= mask
        labels = felzenszwalb(
            image,
            scale=self.scale,
            sigma=self.sigma,
            min_size=self.min_area_px,
            channel_axis=(
                None
                if self.dim is None
                else dim_axis(gt, self.dim, name="Felzenszwalb")
            ),
        )
        # skimage numbers segments from 0, which collides with the
        # invalid-pixel label; shift so valid segments start at 1.
        return _labels(gt, labels + 1, valid)

MarkBoundaries

Bases: Operator

Overlay segmentation boundaries on an image for visual inspection.

Wraps :func:skimage.segmentation.mark_boundaries. Accepts a single-band (H, W) / (1, H, W) image or a 3-band (3, H, W) RGB image; channel-first inputs are moved to channel-last for skimage and back afterwards. The output is always a (3, H, W) RGB overlay. Any other band count raises ValueError. Accepts a GeoArray or a plain np.ndarray and returns the overlay in the same carrier kind.

Called as op(image, label_img): label_img is the single-band integer label map whose region boundaries are drawn, on the image's pixel grid (ValueError otherwise).

Parameters:

Name Type Description Default
color tuple[float, float, float]

RGB color (floats in 0-1) of the boundary lines.

(1.0, 1.0, 0.0)
mode str

Boundary style — "thick", "inner", "outer" or "subpixel".

'thick'
Source code in packages/geotoolz-ops/src/geoops/segment/_src/operators.py
class MarkBoundaries(Operator):
    """Overlay segmentation boundaries on an image for visual inspection.

    Wraps :func:`skimage.segmentation.mark_boundaries`. Accepts a
    single-band ``(H, W)`` / ``(1, H, W)`` image or a 3-band ``(3, H, W)``
    RGB image; channel-first inputs are moved to channel-last for skimage
    and back afterwards. The output is always a ``(3, H, W)`` RGB overlay.
    Any other band count raises ``ValueError``. Accepts a ``GeoArray``
    or a plain ``np.ndarray`` and returns the overlay in the same carrier
    kind.

    Called as ``op(image, label_img)``: ``label_img`` is the single-band
    integer label map whose region boundaries are drawn, on the image's
    pixel grid (``ValueError`` otherwise).

    Args:
        color: RGB color (floats in 0-1) of the boundary lines.
        mode: Boundary style — ``"thick"``, ``"inner"``, ``"outer"`` or
            ``"subpixel"``.
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # boundaries of the labels, drawn thick
    coupling: ClassVar[Coupling] = Coupling(couples={"space"}, reach=2)

    def __init__(
        self,
        *,
        color: tuple[float, float, float] = (1.0, 1.0, 0.0),
        mode: str = "thick",
    ) -> None:
        self.color = as_tuple(color)
        self.mode = mode

    @over_frames
    def _apply(
        self, gt: GeoArrayType | np.ndarray, label_img: GeoArrayType | np.ndarray
    ) -> GeoArrayType | np.ndarray:
        mark_boundaries = optional_name(
            "skimage.segmentation",
            "mark_boundaries",
            "morph",
            feature="geoops.segment.MarkBoundaries",
        )
        _check_input_grid(gt, label_img, "MarkBoundaries", "label_img")
        image = np.asarray(gt)
        if image.ndim == 3:
            if image.shape[0] == 1:
                image = single_band(image, name="MarkBoundaries")
            elif image.shape[0] == 3:
                image = einx.id("c h w -> h w c", image)
            else:
                raise ValueError(
                    "MarkBoundaries expects a single-band (H, W) / (1, H, W) "
                    f"image or a 3-band (3, H, W) RGB image; got shape {image.shape}"
                )
        marked = mark_boundaries(
            image,
            single_band(label_img, name="MarkBoundaries label_img").astype(
                np.int32, copy=False
            ),
            color=self.color,
            mode=self.mode,
        )
        if marked.ndim == 3:
            marked = einx.id("h w c -> c h w", marked)
        return wrap_filled(
            gt, marked, fill_value=carried_fill(gt, np.asarray(marked).dtype)
        )

MaskNMS

Bases: Operator

Mask-IoU non-maximum suppression over a stack of instance masks.

Adapted from Pérez Carrasco et al. (2026), metrics_instance_segmentation. non_max_suppression_masks. The operator ranks instance masks by their score (or by pixel area when no scores are supplied), then suppresses any later mask whose mask-IoU against a kept mask exceeds iou_threshold. Surviving masks are pasted into a 2-D label map numbered from start_label in keep order.

Input is a (N, H, W) mask stack carrier — one plane per candidate instance. This is the natural shape for raw detector output before fragments have been merged into a single non-overlapping label map; use this before :class:MergeNearbyInstances when multiple detections may cover the same object.

Parameters:

Name Type Description Default
iou_threshold float

Pairs with mask-IoU above this are suppressed.

0.1
scores ndarray | None

Optional length-N array of per-instance scores. When None, instances are ranked by pixel area (largest first).

None
start_label int

Starting integer label for the renumbered output.

1

Accepts a GeoArray or a plain np.ndarray mask stack and returns an int32 label map in the same carrier kind, with fill_value=0; pixels that are nodata in any plane are 0.

Source code in packages/geotoolz-ops/src/geoops/segment/_src/operators.py
class MaskNMS(Operator):
    """Mask-IoU non-maximum suppression over a stack of instance masks.

    Adapted from Pérez Carrasco et al. (2026), ``metrics_instance_segmentation.
    non_max_suppression_masks``. The operator ranks instance masks by
    their score (or by pixel area when no scores are supplied), then
    suppresses any later mask whose mask-IoU against a kept mask exceeds
    ``iou_threshold``. Surviving masks are pasted into a 2-D label map
    numbered from ``start_label`` in keep order.

    Input is a ``(N, H, W)`` mask stack carrier — one plane per candidate
    instance. This is the natural shape for raw detector output before
    fragments have been merged into a single non-overlapping label map;
    use this *before* :class:`MergeNearbyInstances` when multiple
    detections may cover the same object.

    Args:
        iou_threshold: Pairs with mask-IoU above this are suppressed.
        scores: Optional length-``N`` array of per-instance scores. When
            None, instances are ranked by pixel area (largest first).
        start_label: Starting integer label for the renumbered output.

    Accepts a ``GeoArray`` or a plain ``np.ndarray`` mask stack and
    returns an ``int32`` label map in the same carrier kind, with
    ``fill_value=0``; pixels that are nodata in any plane are ``0``.
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # instance masks compared by overlap
    coupling: ClassVar[Coupling] = Coupling(
        couples={"band", "space"}, effects={"band": "reduce"}, reach=None
    )

    def __init__(
        self,
        *,
        iou_threshold: float = 0.1,
        scores: np.ndarray | None = None,
        start_label: int = 1,
    ) -> None:
        if not 0.0 < iou_threshold < 1.0:
            raise ValueError("iou_threshold must be in (0, 1)")
        if start_label < 1:
            raise ValueError("start_label must be >= 1")
        self.iou_threshold = float(iou_threshold)
        self.scores = None if scores is None else np.asarray(scores, dtype=float)
        self.start_label = int(start_label)

    @over_frames
    def _apply(self, gt: GeoArrayType | np.ndarray) -> GeoArrayType | np.ndarray:
        masks = np.asarray(gt)
        out = mask_nms(
            masks,
            self.scores,
            iou_threshold=self.iou_threshold,
            start_label=self.start_label,
        )
        return _labels(gt, out, valid_pixels(gt))

    def get_config(self) -> dict[str, Any]:
        return {
            "iou_threshold": self.iou_threshold,
            "scores": None if self.scores is None else self.scores.tolist(),
            "start_label": self.start_label,
        }

MergeNearbyInstances

Bases: Operator

Merge instance labels whose bboxes are close and partially overlap.

Adapted from Pérez Carrasco et al. (2026), Plume Segmentation from MethaneSAT with Cross-Sensor Transfer Learning and Physics-Informed Postprocessing (merging.merge_spatial_fragments_v2). Used there as Mask R-CNN postprocessing to stitch instance fragments split across sliding-window patches.

Two instances are connected when their bounding boxes are within distance_threshold pixels edge-to-edge and their box IoU is in the open interval (iou_threshold_min, iou_threshold_max). Connected components are then merged into single instances via pixel-wise union. Note that the IoU lower bound is strict, so two close-but-disjoint boxes (IoU = 0) never merge — match the paper's behavior; loosen iou_threshold_min to 0.0 to recover proximity-only merging.

Parameters:

Name Type Description Default
distance_threshold float

Maximum edge-to-edge bbox distance (pixels).

40.0
iou_threshold_min float

Lower (exclusive) bound on box IoU.

0.01
iou_threshold_max float

Upper (exclusive) bound on box IoU.

0.65
classes Mapping[int, int] | list[list[int]] | None

Optional {instance_label: class_id} mapping (or the [[instance_label, class_id], ...] pairs get_config emits); when provided, only same-class pairs are eligible to merge.

None
start_label int

Starting integer label for the relabeled output.

1

Accepts a single-band GeoArray or a plain np.ndarray label map and returns an int32 label map in the same carrier kind, with fill_value=0; nodata input pixels are 0.

Source code in packages/geotoolz-ops/src/geoops/segment/_src/operators.py
class MergeNearbyInstances(Operator):
    """Merge instance labels whose bboxes are close and partially overlap.

    Adapted from Pérez Carrasco et al. (2026), *Plume Segmentation from
    MethaneSAT with Cross-Sensor Transfer Learning and Physics-Informed
    Postprocessing* (``merging.merge_spatial_fragments_v2``). Used there as
    Mask R-CNN postprocessing to stitch instance fragments split across
    sliding-window patches.

    Two instances are connected when their bounding boxes are within
    ``distance_threshold`` pixels edge-to-edge **and** their box IoU is in
    the open interval ``(iou_threshold_min, iou_threshold_max)``. Connected
    components are then merged into single instances via pixel-wise union.
    Note that the IoU lower bound is strict, so two close-but-disjoint
    boxes (IoU = 0) never merge — match the paper's behavior; loosen
    ``iou_threshold_min`` to ``0.0`` to recover proximity-only merging.

    Args:
        distance_threshold: Maximum edge-to-edge bbox distance (pixels).
        iou_threshold_min: Lower (exclusive) bound on box IoU.
        iou_threshold_max: Upper (exclusive) bound on box IoU.
        classes: Optional ``{instance_label: class_id}`` mapping (or the
            ``[[instance_label, class_id], ...]`` pairs ``get_config``
            emits); when provided, only same-class pairs are eligible to
            merge.
        start_label: Starting integer label for the relabeled output.

    Accepts a single-band ``GeoArray`` or a plain ``np.ndarray`` label
    map and returns an ``int32`` label map in the same carrier kind, with
    ``fill_value=0``; nodata input pixels are ``0``.
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # instances merged by distance and overlap
    coupling: ClassVar[Coupling] = Coupling(couples={"space"}, reach=None)

    def __init__(
        self,
        *,
        distance_threshold: float = 40.0,
        iou_threshold_min: float = 0.01,
        iou_threshold_max: float = 0.65,
        classes: Mapping[int, int] | list[list[int]] | None = None,
        start_label: int = 1,
    ) -> None:
        if distance_threshold < 0:
            raise ValueError("distance_threshold must be non-negative")
        if not 0.0 <= iou_threshold_min < iou_threshold_max <= 1.0:
            raise ValueError("require 0 <= iou_threshold_min < iou_threshold_max <= 1")
        if start_label < 1:
            raise ValueError("start_label must be >= 1")
        self.distance_threshold = float(distance_threshold)
        self.iou_threshold_min = float(iou_threshold_min)
        self.iou_threshold_max = float(iou_threshold_max)
        self.classes = mapping_from_pairs(classes)
        self.start_label = int(start_label)

    @over_frames
    def _apply(self, gt: GeoArrayType | np.ndarray) -> GeoArrayType | np.ndarray:
        labels_in = single_band(np.asarray(gt), name="MergeNearbyInstances")
        merged = merge_nearby_instances(
            labels_in,
            distance_threshold=self.distance_threshold,
            iou_threshold_min=self.iou_threshold_min,
            iou_threshold_max=self.iou_threshold_max,
            classes=self.classes,
            start_label=self.start_label,
        )
        # Label map: 0 is "no instance", including at nodata input pixels.
        return _labels(gt, merged, valid_pixels(gt))

    def get_config(self) -> dict[str, Any]:
        return {
            "distance_threshold": self.distance_threshold,
            "iou_threshold_min": self.iou_threshold_min,
            "iou_threshold_max": self.iou_threshold_max,
            "classes": mapping_to_pairs(self.classes),
            "start_label": self.start_label,
        }

Quickshift

Bases: Operator

Mode-seeking superpixels via :func:skimage.segmentation.quickshift.

Nodata pixels (non-finite or fill_value in any band) are median-filled before segmentation and forced to label 0 in the output; valid segments are labelled from 1. Accepts a GeoArray or a plain np.ndarray (channel-first) and returns an int32 label map in the same carrier kind.

Parameters:

Name Type Description Default
kernel_size float

Width of the Gaussian kernel used to estimate the local density.

5.0
max_dist float

Cut-off point for data distances; higher values mean fewer clusters.

10.0
ratio float

Balance (0-1) between color-space and image-space proximity.

1.0
sigma float

Width of the Gaussian pre-smoothing kernel, in pixels.

0.0
dim str | None

Name of the band dim (default "band"); its position is read from the carrier's dims.

'band'
axis int | None

Deprecated: the band axis position. -3 maps to dim="band"; removed in the next minor release.

None
convert2lab bool

Convert the image to LAB space first. Defaults to False (unlike skimage) so non-RGB / multispectral / single-band inputs work out of the box.

False

Called as op(image, mask=None). The optional mask is an (H, W) (or (1, H, W)) boolean carrier on the image's pixel grid (ValueError otherwise); pixels outside it get label 0. Pass it positionally to wire it as a graph input, Quickshift()(Input("image"), Input("mask")).

Source code in packages/geotoolz-ops/src/geoops/segment/_src/operators.py
class Quickshift(Operator):
    """Mode-seeking superpixels via :func:`skimage.segmentation.quickshift`.

    Nodata pixels (non-finite or ``fill_value`` in any band) are
    median-filled before segmentation and forced to label ``0`` in the
    output; valid segments are labelled from ``1``.
    Accepts a ``GeoArray`` or a plain
    ``np.ndarray`` (channel-first) and returns an ``int32`` label map in
    the same carrier kind.

    Args:
        kernel_size: Width of the Gaussian kernel used to estimate the
            local density.
        max_dist: Cut-off point for data distances; higher values mean
            fewer clusters.
        ratio: Balance (0-1) between color-space and image-space
            proximity.
        sigma: Width of the Gaussian pre-smoothing kernel, in pixels.
        dim: Name of the band dim (default ``"band"``); its position is read
            from the carrier's dims.
        axis: Deprecated: the band axis position. ``-3`` maps to
            ``dim="band"``; removed in the next minor release.
        convert2lab: Convert the image to LAB space first. Defaults to
            ``False`` (unlike skimage) so non-RGB / multispectral /
            single-band inputs work out of the box.

    Called as ``op(image, mask=None)``. The optional ``mask`` is an
    ``(H, W)`` (or ``(1, H, W)``) boolean carrier on the image's pixel grid
    (``ValueError`` otherwise); pixels outside it get label ``0``. Pass it
    positionally to wire it as a graph input,
    ``Quickshift()(Input("image"), Input("mask"))``.
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    coupling: ClassVar[Coupling] = Coupling(
        couples={"band", "space"}, effects={"band": "reduce"}, reach=None
    )

    def __init__(
        self,
        *,
        kernel_size: float = 5.0,
        max_dist: float = 10.0,
        ratio: float = 1.0,
        sigma: float = 0.0,
        dim: str | None = "band",
        convert2lab: bool = False,
        axis: int | None = None,
    ) -> None:
        self.kernel_size = kernel_size
        self.max_dist = max_dist
        self.ratio = ratio
        self.sigma = sigma
        self.dim = band_dim(dim, axis, "Quickshift", legacy=(0, -3))
        # Default to False so non-RGB / multispectral / single-band inputs
        # work out of the box. skimage's quickshift defaults convert2lab=True,
        # which raises on any input that is not exactly 3-channel RGB.
        self.convert2lab = convert2lab

    @over_frames
    def _apply(
        self,
        gt: GeoArrayType | np.ndarray,
        mask: GeoArrayType | np.ndarray | None = None,
    ) -> GeoArrayType | np.ndarray:
        quickshift = optional_name(
            "skimage.segmentation",
            "quickshift",
            "morph",
            feature="geoops.segment.Quickshift",
        )
        _check_input_grid(gt, mask, "Quickshift", "mask")
        valid = valid_pixels(gt)
        image = fill_invalid(np.asarray(gt), valid)
        mask = _as_mask(mask, gt.shape[-2:], name="Quickshift mask")
        if mask is not None:
            valid &= mask
        if self.dim is None:
            # skimage's quickshift has no channel-free mode: a single-band
            # image gets a trailing channel of one
            image, channel_axis = image[..., np.newaxis], -1
        else:
            channel_axis = dim_axis(gt, self.dim, name="Quickshift")
        labels = quickshift(
            image,
            kernel_size=self.kernel_size,
            max_dist=self.max_dist,
            ratio=self.ratio,
            sigma=self.sigma,
            channel_axis=channel_axis,
            convert2lab=self.convert2lab,
        )
        # skimage numbers segments from 0, which collides with the
        # invalid-pixel label; shift so valid segments start at 1.
        return _labels(gt, labels + 1, valid)

RandomWalker

Bases: Operator

Seeded segmentation via :func:skimage.segmentation.random_walker.

Expects a single-band (H, W) or (1, H, W) image. Nodata pixels (non-finite or fill_value) are median-filled, marked inactive (removed from the diffusion graph) and labelled 0 in the output. Accepts a GeoArray or a plain np.ndarray and returns an int32 label map in the same carrier kind.

Called as op(image, markers): markers is a single-band integer carrier of seed labels (0 = unseeded) on the image's pixel grid (ValueError otherwise).

Parameters:

Name Type Description Default
beta float

Penalisation coefficient for the random-walk motion; higher values make diffusion harder across intensity edges.

130.0
mode str

Linear-system solver mode (see skimage docs).

'cg_j'
tol float

Solver convergence tolerance.

0.001
Source code in packages/geotoolz-ops/src/geoops/segment/_src/operators.py
class RandomWalker(Operator):
    """Seeded segmentation via :func:`skimage.segmentation.random_walker`.

    Expects a single-band ``(H, W)`` or ``(1, H, W)`` image. Nodata pixels
    (non-finite or ``fill_value``) are median-filled, marked
    inactive (removed from the diffusion graph) and labelled ``0`` in the
    output. Accepts a ``GeoArray``
    or a plain ``np.ndarray`` and returns an ``int32`` label map in the
    same carrier kind.

    Called as ``op(image, markers)``: ``markers`` is a single-band integer
    carrier of seed labels (0 = unseeded) on the image's pixel grid
    (``ValueError`` otherwise).

    Args:
        beta: Penalisation coefficient for the random-walk motion;
            higher values make diffusion harder across intensity edges.
        mode: Linear-system solver mode (see skimage docs).
        tol: Solver convergence tolerance.
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    coupling: ClassVar[Coupling] = Coupling(couples={"space"}, reach=None)

    def __init__(
        self,
        *,
        beta: float = 130.0,
        mode: str = "cg_j",
        tol: float = 1e-3,
    ) -> None:
        self.beta = beta
        self.mode = mode
        self.tol = tol

    @over_frames
    def _apply(
        self, gt: GeoArrayType | np.ndarray, markers: GeoArrayType | np.ndarray
    ) -> GeoArrayType | np.ndarray:
        random_walker = optional_name(
            "skimage.segmentation",
            "random_walker",
            "morph",
            feature="geoops.segment.RandomWalker",
        )
        _check_input_grid(gt, markers, "RandomWalker", "markers")
        valid = valid_pixels(gt)
        seeds = single_band(markers, name="RandomWalker markers").astype(
            np.int32, copy=True
        )
        # Negative markers are inactive in skimage: nodata pixels are removed
        # from the diffusion graph so no label can spread through them.
        seeds[~valid] = -1
        labels = random_walker(
            single_band(fill_invalid(np.asarray(gt), valid), name="RandomWalker"),
            seeds,
            beta=self.beta,
            mode=self.mode,
            tol=self.tol,
        )
        return _labels(gt, labels, valid)

SLIC

Bases: Operator

SLIC superpixels via :func:skimage.segmentation.slic.

Nodata pixels (non-finite or fill_value in any band) are median-filled, excluded from clustering and forced to label 0 in the output. Accepts a GeoArray or a plain np.ndarray (channel-first) and returns an int32 label map in the same carrier kind.

Parameters:

Name Type Description Default
n_segments int

Approximate number of superpixels to produce.

100
compactness float

Balance between color and spatial proximity; higher values yield more compact (squarer) segments.

10.0
sigma float

Width of the Gaussian pre-smoothing kernel, in pixels.

0.0
dim str | None

Name of the band dim (default "band"); its position is read from the carrier's dims.

'band'
axis int | None

Deprecated: the band axis position. -3 maps to dim="band"; removed in the next minor release.

None
start_label int

First label assigned to a superpixel.

1

Called as op(image, mask=None). The optional mask is an (H, W) (or (1, H, W)) boolean carrier on the image's pixel grid (ValueError otherwise); pixels outside it get label 0. Pass it positionally to wire it as a graph input, SLIC()(Input("image"), Input("mask")).

Source code in packages/geotoolz-ops/src/geoops/segment/_src/operators.py
class SLIC(Operator):
    """SLIC superpixels via :func:`skimage.segmentation.slic`.

    Nodata pixels (non-finite or ``fill_value`` in any band) are
    median-filled, excluded from clustering and forced to label ``0`` in
    the output. Accepts a ``GeoArray`` or a plain
    ``np.ndarray`` (channel-first) and returns an ``int32`` label map in
    the same carrier kind.

    Args:
        n_segments: Approximate number of superpixels to produce.
        compactness: Balance between color and spatial proximity; higher
            values yield more compact (squarer) segments.
        sigma: Width of the Gaussian pre-smoothing kernel, in pixels.
        dim: Name of the band dim (default ``"band"``); its position is read
            from the carrier's dims.
        axis: Deprecated: the band axis position. ``-3`` maps to
            ``dim="band"``; removed in the next minor release.
        start_label: First label assigned to a superpixel.

    Called as ``op(image, mask=None)``. The optional ``mask`` is an
    ``(H, W)`` (or ``(1, H, W)``) boolean carrier on the image's pixel grid
    (``ValueError`` otherwise); pixels outside it get label ``0``. Pass it
    positionally to wire it as a graph input,
    ``SLIC()(Input("image"), Input("mask"))``.
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    coupling: ClassVar[Coupling] = Coupling(
        couples={"band", "space"}, effects={"band": "reduce"}, reach=None
    )

    def __init__(
        self,
        *,
        n_segments: int = 100,
        compactness: float = 10.0,
        sigma: float = 0.0,
        dim: str | None = "band",
        start_label: int = 1,
        axis: int | None = None,
    ) -> None:
        self.n_segments = n_segments
        self.compactness = compactness
        self.sigma = sigma
        self.dim = band_dim(dim, axis, "SLIC", legacy=(0, -3))
        self.start_label = start_label

    @over_frames
    def _apply(
        self,
        gt: GeoArrayType | np.ndarray,
        mask: GeoArrayType | np.ndarray | None = None,
    ) -> GeoArrayType | np.ndarray:
        slic = optional_name(
            "skimage.segmentation",
            "slic",
            "morph",
            feature="geoops.segment.SLIC",
        )
        _check_input_grid(gt, mask, "SLIC", "mask")
        valid = valid_pixels(gt)
        image = fill_invalid(np.asarray(gt), valid)
        mask = _as_mask(mask, gt.shape[-2:], name="SLIC mask")
        if mask is not None:
            valid &= mask
        # A 2-D image has no channel axis; skimage raises if one is given.
        channel_axis = (
            None
            if image.ndim == 2 or self.dim is None
            else dim_axis(gt, self.dim, name="SLIC")
        )
        labels = slic(
            image,
            n_segments=self.n_segments,
            compactness=self.compactness,
            sigma=self.sigma,
            channel_axis=channel_axis,
            start_label=self.start_label,
            mask=valid,
        )
        return _labels(gt, labels, valid)

Threshold

Bases: Operator

Binary mask of the pixels strictly above a global threshold.

Delegates to :func:geoops.segment.threshold_mask: the threshold is an absolute number, Otsu's (1979) between-class-variance optimum, or a percentile of the input, and the mask is values > t. The data-driven modes use one threshold over every band and pixel of a frame; a (T, C, H, W) time stack is thresholded frame by frame.

Nodata pixels (non-finite or equal to the input's fill value, in any band) are excluded from the Otsu / percentile statistic and are always False; the output declares fill_value=False. Accepts a GeoArray or a plain np.ndarray and returns a boolean mask of the input's shape in the same carrier kind.

:class:geoops.plume.PlumeMask is this thresholding followed by a minimum-component-size filter.

Parameters:

Name Type Description Default
threshold ThresholdMode

float (absolute), "otsu", or "percentile:<p>" with p in [0, 100].

'otsu'
nbins int

Histogram bins for the "otsu" threshold; ignored by the other modes. Default 256.

256

Raises:

Type Description
ValueError

If threshold is a string other than "otsu" or "percentile:<p>".

Examples:

>>> mask = gz.segment.Threshold(threshold="otsu")(score_map)
>>> hot = gz.segment.Threshold(threshold="percentile:99")(score_map)
>>> above = gz.segment.Threshold(threshold=0.5)(probability)
Source code in packages/geotoolz-ops/src/geoops/segment/_src/operators.py
class Threshold(Operator):
    """Binary mask of the pixels strictly above a global threshold.

    Delegates to :func:`geoops.segment.threshold_mask`: the threshold is
    an absolute number, Otsu's (1979) between-class-variance optimum, or
    a percentile of the input, and the mask is ``values > t``. The
    data-driven modes use one threshold over every band and pixel of a
    frame; a ``(T, C, H, W)`` time stack is thresholded frame by frame.

    Nodata pixels (non-finite or equal to the input's fill value, in any
    band) are excluded from the Otsu / percentile statistic and are always
    ``False``; the output declares ``fill_value=False``. Accepts a
    ``GeoArray`` or a plain ``np.ndarray`` and returns a boolean mask of
    the input's shape in the same carrier kind.

    :class:`geoops.plume.PlumeMask` is this thresholding followed by a
    minimum-component-size filter.

    Args:
        threshold: ``float`` (absolute), ``"otsu"``, or
            ``"percentile:<p>"`` with ``p`` in ``[0, 100]``.
        nbins: Histogram bins for the ``"otsu"`` threshold; ignored by
            the other modes. Default ``256``.

    Raises:
        ValueError: If ``threshold`` is a string other than ``"otsu"`` or
            ``"percentile:<p>"``.

    Examples:
        >>> mask = gz.segment.Threshold(threshold="otsu")(score_map)
        >>> hot = gz.segment.Threshold(threshold="percentile:99")(score_map)
        >>> above = gz.segment.Threshold(threshold=0.5)(probability)
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # a threshold over the scene (Otsu or a percentile)
    coupling: ClassVar[Coupling] = Coupling(couples={"space"}, reach=None)

    def __init__(self, *, threshold: ThresholdMode = "otsu", nbins: int = 256) -> None:
        if isinstance(threshold, str) and not (
            threshold == "otsu" or threshold.startswith("percentile:")
        ):
            raise ValueError(
                "threshold must be a number, 'otsu', or 'percentile:<p>'; "
                f"got {threshold!r}"
            )
        self.threshold = threshold
        self.nbins = nbins

    @over_frames
    def _apply(self, gt: GeoArrayType | np.ndarray) -> GeoArrayType | np.ndarray:
        mask = threshold_mask(mask_invalid_to_nan(gt), self.threshold, nbins=self.nbins)
        return wrap_like(gt, mask, fill_value=False)

Watershed

Bases: Operator

Watershed segmentation via :func:skimage.segmentation.watershed.

Expects a single-band (H, W) or (1, H, W) image. Nodata pixels (non-finite or fill_value) are median-filled, masked out of the flooding and forced to label 0 in the output. Accepts a GeoArray or a plain np.ndarray and returns an int32 label map in the same carrier kind.

Called as op(image, markers=None, mask=None), both optional carriers on the image's pixel grid (ValueError otherwise): markers is a single-band integer array seeding the basins (when omitted, local minima of the image are used) and mask an (H, W) (or (1, H, W)) boolean mask; pixels outside it get label 0.

Parameters:

Name Type Description Default
connectivity Connectivity

4 (edge neighbours, default) or 8 (edge + diagonal neighbours) used for flooding -- the package-wide spelling, converted to a footprint for skimage (whose 1 / 2 spelling is not accepted).

4
compactness float

Compactness parameter; higher values produce more regularly-shaped basins.

0.0
watershed_line bool

Separate basins with a zero-labelled line.

False
Source code in packages/geotoolz-ops/src/geoops/segment/_src/operators.py
class Watershed(Operator):
    """Watershed segmentation via :func:`skimage.segmentation.watershed`.

    Expects a single-band ``(H, W)`` or ``(1, H, W)`` image. Nodata pixels
    (non-finite or ``fill_value``) are median-filled, masked out of
    the flooding and forced to label ``0`` in the output. Accepts a
    ``GeoArray`` or a plain ``np.ndarray`` and returns an ``int32`` label
    map in the same carrier kind.

    Called as ``op(image, markers=None, mask=None)``, both optional
    carriers on the image's pixel grid (``ValueError`` otherwise):
    ``markers`` is a single-band integer array seeding the basins (when
    omitted, local minima of the image are used) and ``mask`` an
    ``(H, W)`` (or ``(1, H, W)``) boolean mask; pixels outside it get
    label ``0``.

    Args:
        connectivity: ``4`` (edge neighbours, default) or ``8`` (edge +
            diagonal neighbours) used for flooding -- the package-wide
            spelling, converted to a footprint for skimage (whose ``1`` /
            ``2`` spelling is not accepted).
        compactness: Compactness parameter; higher values produce more
            regularly-shaped basins.
        watershed_line: Separate basins with a zero-labelled line.
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    coupling: ClassVar[Coupling] = Coupling(couples={"space"}, reach=None)

    def __init__(
        self,
        *,
        connectivity: Connectivity = 4,
        compactness: float = 0.0,
        watershed_line: bool = False,
    ) -> None:
        connectivity_structure(connectivity)  # validate 4 | 8 up front
        self.connectivity = connectivity
        self.compactness = compactness
        self.watershed_line = watershed_line

    @over_frames
    def _apply(
        self,
        gt: GeoArrayType | np.ndarray,
        markers: GeoArrayType | np.ndarray | None = None,
        mask: GeoArrayType | np.ndarray | None = None,
    ) -> GeoArrayType | np.ndarray:
        watershed = optional_name(
            "skimage.segmentation",
            "watershed",
            "morph",
            feature="geoops.segment.Watershed",
        )
        _check_input_grid(gt, markers, "Watershed", "markers")
        _check_input_grid(gt, mask, "Watershed", "mask")
        valid = valid_pixels(gt)
        image = single_band(fill_invalid(np.asarray(gt), valid), name="Watershed")
        mask_arr = _as_mask(mask, gt.shape[-2:], name="Watershed mask")
        if mask_arr is not None:
            valid &= mask_arr
        markers = (
            None if markers is None else single_band(markers, name="Watershed markers")
        )
        labels = watershed(
            image,
            markers=markers,
            connectivity=connectivity_structure(self.connectivity),
            mask=valid,
            compactness=self.compactness,
            watershed_line=self.watershed_line,
        )
        return _labels(gt, labels, valid)

fill_invalid(image, valid)

Float copy of image with every invalid pixel set to the valid median.

The fill statistic is the median over valid pixels only, so neither a fill_value sentinel nor +/-inf can leak into it. The segmenters run on the filled image, because skimage has no notion of nodata.

Parameters:

Name Type Description Default
image Num[ndarray, '*dims']

(H, W) or (C, H, W) image.

required
valid Bool[ndarray, 'h w']

(H, W) validity; False pixels are filled in every band.

required

Returns:

Type Description
Float[ndarray, '*dims']

A float copy (image itself, as float, when all pixels are

Float[ndarray, '*dims']

valid). An image with no valid pixel is filled with 0.

Examples:

>>> image = np.array([[1.0, 2.0], [3.0, -9999.0]])
>>> fill_invalid(image, image != -9999.0)
array([[1., 2.],
       [3., 2.]])
Source code in packages/geotoolz-ops/src/geoops/segment/_src/array.py
def fill_invalid(
    image: Num[np.ndarray, "*dims"], valid: Bool[np.ndarray, "h w"]
) -> Float[np.ndarray, "*dims"]:
    """Float copy of ``image`` with every invalid pixel set to the valid median.

    The fill statistic is the median over valid pixels only, so neither a
    ``fill_value`` sentinel nor ``+/-inf`` can leak into it. The
    segmenters run on the filled image, because skimage has no notion of
    nodata.

    Args:
        image: ``(H, W)`` or ``(C, H, W)`` image.
        valid: ``(H, W)`` validity; ``False`` pixels are filled in every
            band.

    Returns:
        A float copy (``image`` itself, as float, when all pixels are
        valid). An image with no valid pixel is filled with ``0``.

    Examples:
        >>> image = np.array([[1.0, 2.0], [3.0, -9999.0]])
        >>> fill_invalid(image, image != -9999.0)
        array([[1., 2.],
               [3., 2.]])
    """
    arr = np.asarray(image, dtype=float)
    if valid.all():
        return arr
    invalid = np.broadcast_to(~valid, arr.shape)
    fill = float(np.median(arr[~invalid])) if valid.any() else 0.0
    arr = arr.copy()
    arr[invalid] = fill
    return arr

mask_nms(masks, scores, iou_threshold, start_label)

Suppress overlapping mask predictions via mask-IoU and stitch survivors into a 2-D label map (suppressed planes -> background).

Mirrors Pérez Carrasco et al. (2026), non_max_suppression_masks. When scores is None instances are ranked by area, largest first.

Parameters:

Name Type Description Default
masks Num[ndarray, 'n h w'] | Bool[ndarray, 'n h w']

(N, H, W) instance mask stack.

required
scores Float[ndarray, ' n'] | None

(N,) confidence per mask, or None to rank by area.

required
iou_threshold float

Masks whose IoU with a kept mask exceeds this are suppressed.

required
start_label int

Label of the first kept mask.

required

Returns:

Type Description
Int[ndarray, 'h w']

(H, W) int64 label map; earlier-ranked survivors keep

Int[ndarray, 'h w']

overlapping pixels.

Raises:

Type Description
ValueError

If masks is not 3-D or scores has the wrong length.

Examples:

>>> masks = np.zeros((2, 3, 3), dtype=bool)
>>> masks[0, :2], masks[1, :3] = True, True
>>> mask_nms(masks, None, 0.5, 1)
array([[1, 1, 1],
       [1, 1, 1],
       [1, 1, 1]])
Source code in packages/geotoolz-ops/src/geoops/segment/_src/array.py
def mask_nms(
    masks: Num[np.ndarray, "n h w"] | Bool[np.ndarray, "n h w"],
    scores: Float[np.ndarray, " n"] | None,
    iou_threshold: float,
    start_label: int,
) -> Int[np.ndarray, "h w"]:
    """Suppress overlapping mask predictions via mask-IoU and stitch
    survivors into a 2-D label map (suppressed planes -> background).

    Mirrors Pérez Carrasco et al. (2026), ``non_max_suppression_masks``.
    When ``scores`` is None instances are ranked by area, largest first.

    Args:
        masks: ``(N, H, W)`` instance mask stack.
        scores: ``(N,)`` confidence per mask, or ``None`` to rank by area.
        iou_threshold: Masks whose IoU with a kept mask exceeds this are
            suppressed.
        start_label: Label of the first kept mask.

    Returns:
        ``(H, W)`` ``int64`` label map; earlier-ranked survivors keep
        overlapping pixels.

    Raises:
        ValueError: If ``masks`` is not 3-D or ``scores`` has the wrong
            length.

    Examples:
        >>> masks = np.zeros((2, 3, 3), dtype=bool)
        >>> masks[0, :2], masks[1, :3] = True, True
        >>> mask_nms(masks, None, 0.5, 1)
        array([[1, 1, 1],
               [1, 1, 1],
               [1, 1, 1]])
    """
    if masks.ndim != 3:
        raise ValueError(f"expected a (N, H, W) mask stack, got shape {masks.shape}")
    n, h, w = masks.shape
    if n == 0:
        return np.zeros((h, w), dtype=np.int64)
    bool_masks = masks.astype(bool, copy=False)
    areas = bool_masks.reshape(n, -1).sum(axis=1).astype(np.int64)
    if scores is None:
        rank = np.argsort(-areas, kind="stable")
    else:
        if scores.shape != (n,):
            raise ValueError(
                f"scores length {scores.shape} does not match mask count ({n})"
            )
        rank = np.argsort(-scores, kind="stable")

    keep: list[int] = []
    suppressed = np.zeros(n, dtype=bool)
    for idx in rank:
        i = int(idx)
        if suppressed[i] or areas[i] == 0:
            continue
        keep.append(i)
        mi = bool_masks[i]
        ai = int(areas[i])
        for jdx in rank:
            j = int(jdx)
            if j == i or suppressed[j] or j in keep:
                continue
            inter = int(np.logical_and(mi, bool_masks[j]).sum())
            if inter == 0:
                continue
            union = ai + int(areas[j]) - inter
            if union <= 0:
                continue
            if (inter / union) > iou_threshold:
                suppressed[j] = True

    # Higher-ranked masks claim pixels first; later survivors below the
    # suppression threshold but with some overlap must not overwrite that
    # claim, or downstream area/statistics for the highest-confidence
    # detection would silently shrink. Paste in keep order, into pixels
    # still unassigned.
    out = np.zeros((h, w), dtype=np.int64)
    for new_offset, src in enumerate(keep):
        target = bool_masks[src] & (out == 0)
        out[target] = start_label + new_offset
    return out

merge_nearby_instances(labels, *, distance_threshold, iou_threshold_min, iou_threshold_max, classes, start_label)

Merge instance labels whose bboxes are close and partially overlap.

Connectivity rule (from Pérez Carrasco et al. 2026): two instances are connected iff their bbox edge-to-edge distance is strictly below distance_threshold and their box IoU lies in the open interval (iou_threshold_min, iou_threshold_max). Connected components are then merged via pixel-wise union.

Parameters:

Name Type Description Default
labels Num[ndarray, 'h w']

(H, W) instance label map; <= 0 is background.

required
distance_threshold float

Maximum edge-to-edge bbox distance (pixels), exclusive.

required
iou_threshold_min float

Lower (exclusive) bound on box IoU.

required
iou_threshold_max float

Upper (exclusive) bound on box IoU.

required
classes Mapping[int, int] | None

Optional {instance_label: class_id}; only same-class pairs may merge.

required
start_label int

First label of the relabelled output.

required

Returns:

Type Description
Int[ndarray, 'h w']

int64 label map, merged groups numbered from start_label

Int[ndarray, 'h w']

in order of their first member label.

Examples:

>>> labels = np.full((4, 4), 2)  # an L-shaped 1 wrapping a block of 2
>>> labels[0, :], labels[:, 0] = 1, 1
>>> np.unique(merge_nearby_instances(
...     labels, distance_threshold=5, iou_threshold_min=0.0,
...     iou_threshold_max=1.0, classes=None, start_label=1))
array([1])
Source code in packages/geotoolz-ops/src/geoops/segment/_src/array.py
def merge_nearby_instances(
    labels: Num[np.ndarray, "h w"],
    *,
    distance_threshold: float,
    iou_threshold_min: float,
    iou_threshold_max: float,
    classes: Mapping[int, int] | None,
    start_label: int,
) -> Int[np.ndarray, "h w"]:
    """Merge instance labels whose bboxes are close and partially overlap.

    Connectivity rule (from Pérez Carrasco et al. 2026):
    two instances are connected iff their bbox edge-to-edge distance is
    strictly below ``distance_threshold`` *and* their box IoU lies in the
    open interval ``(iou_threshold_min, iou_threshold_max)``.
    Connected components are then merged via pixel-wise union.

    Args:
        labels: ``(H, W)`` instance label map; ``<= 0`` is background.
        distance_threshold: Maximum edge-to-edge bbox distance (pixels),
            exclusive.
        iou_threshold_min: Lower (exclusive) bound on box IoU.
        iou_threshold_max: Upper (exclusive) bound on box IoU.
        classes: Optional ``{instance_label: class_id}``; only same-class
            pairs may merge.
        start_label: First label of the relabelled output.

    Returns:
        ``int64`` label map, merged groups numbered from ``start_label``
        in order of their first member label.

    Examples:
        >>> labels = np.full((4, 4), 2)  # an L-shaped 1 wrapping a block of 2
        >>> labels[0, :], labels[:, 0] = 1, 1
        >>> np.unique(merge_nearby_instances(
        ...     labels, distance_threshold=5, iou_threshold_min=0.0,
        ...     iou_threshold_max=1.0, classes=None, start_label=1))
        array([1])
    """
    work = np.where(labels > 0, labels, 0).astype(np.int64, copy=False)
    ids = np.unique(work)
    ids = ids[ids > 0]
    if ids.size == 0:
        return np.zeros_like(work, dtype=np.int64)

    # ``find_objects`` returns a list indexed by ``label - 1`` whose entries are
    # ``(slice_y, slice_x)`` with exclusive ``stop`` — matching the paper's
    # ``[y1, x1, y2, x2]`` convention used by ``_bbox_edge_distance``/``_bbox_iou``.
    slices = ndimage.find_objects(work)
    boxes: dict[int, tuple[int, int, int, int]] = {}
    for lbl_value in ids:
        lbl = int(lbl_value)
        sl = slices[lbl - 1]
        if sl is None:
            continue
        y_sl, x_sl = sl
        boxes[lbl] = (
            int(y_sl.start),
            int(x_sl.start),
            int(y_sl.stop),
            int(x_sl.stop),
        )

    instance_ids = list(boxes.keys())
    n = len(instance_ids)

    parent = list(range(n))

    def find(i: int) -> int:
        while parent[i] != i:
            parent[i] = parent[parent[i]]
            i = parent[i]
        return i

    def union(i: int, j: int) -> None:
        ri, rj = find(i), find(j)
        if ri != rj:
            parent[ri] = rj

    for i in range(n):
        bi = boxes[instance_ids[i]]
        ci = None if classes is None else classes.get(instance_ids[i])
        for j in range(i + 1, n):
            if classes is not None:
                cj = classes.get(instance_ids[j])
                if ci != cj:
                    continue
            bj = boxes[instance_ids[j]]
            if _bbox_edge_distance(bi, bj) >= distance_threshold:
                continue
            iou = _bbox_iou(bi, bj)
            if not (iou_threshold_min < iou < iou_threshold_max):
                continue
            union(i, j)

    root_to_new: dict[int, int] = {}
    remap: dict[int, int] = {}
    next_label = start_label
    for i, lbl in enumerate(instance_ids):
        root = find(i)
        if root not in root_to_new:
            root_to_new[root] = next_label
            next_label += 1
        remap[lbl] = root_to_new[root]

    max_label = int(work.max())
    lookup = np.zeros(max_label + 1, dtype=np.int64)
    for old_lbl, new_lbl in remap.items():
        lookup[old_lbl] = new_lbl
    return lookup[work]

otsu_threshold(values, *, nbins=256)

Compute Otsu's between-class-variance threshold, ignoring NaNs.

Builds an nbins-bin histogram of the finite values and returns the bin center that maximises the between-class variance w_bg * w_fg * (mu_bg - mu_fg)^2 (Otsu, 1979). A constant input returns that constant.

Parameters:

Name Type Description Default
values Num[ndarray, '*dims']

Array of any shape; non-finite entries are ignored.

required
nbins int

Number of histogram bins. Default 256.

256

Returns:

Type Description
float

The threshold; pixels strictly above it are foreground.

Raises:

Type Description
ValueError

If values contains no finite entries.

Examples:

>>> values = np.r_[np.zeros(50), np.ones(50)]
>>> 0.0 < otsu_threshold(values) < 1.0
True
Source code in packages/geotoolz-ops/src/geoops/segment/_src/array.py
def otsu_threshold(values: Num[np.ndarray, "*dims"], *, nbins: int = 256) -> float:
    """Compute Otsu's between-class-variance threshold, ignoring NaNs.

    Builds an ``nbins``-bin histogram of the finite values and returns
    the bin center that maximises the between-class variance
    ``w_bg * w_fg * (mu_bg - mu_fg)^2`` (Otsu, 1979). A constant input
    returns that constant.

    Args:
        values: Array of any shape; non-finite entries are ignored.
        nbins: Number of histogram bins. Default ``256``.

    Returns:
        The threshold; pixels strictly above it are foreground.

    Raises:
        ValueError: If ``values`` contains no finite entries.

    Examples:
        >>> values = np.r_[np.zeros(50), np.ones(50)]
        >>> 0.0 < otsu_threshold(values) < 1.0
        True
    """
    finite = np.asarray(values, dtype=float)
    finite = finite[np.isfinite(finite)]
    if finite.size == 0:
        raise ValueError("cannot compute an Otsu threshold on all-NaN data")
    if np.all(finite == finite[0]):
        return float(finite[0])

    hist, bin_edges = np.histogram(finite, bins=nbins)
    centers = (bin_edges[:-1] + bin_edges[1:]) / 2.0
    weight_bg = np.cumsum(hist)
    weight_fg = finite.size - weight_bg

    valid = (weight_bg > 0) & (weight_fg > 0)
    mean_bg = np.divide(
        np.cumsum(hist * centers),
        weight_bg,
        out=np.zeros_like(centers, dtype=float),
        where=weight_bg > 0,
    )
    mean_fg = np.divide(
        np.cumsum((hist * centers)[::-1])[::-1] - hist * centers,
        weight_fg,
        out=np.zeros_like(centers, dtype=float),
        where=weight_fg > 0,
    )
    variance = weight_bg * weight_fg * (mean_bg - mean_fg) ** 2
    variance[~valid] = -np.inf
    return float(centers[int(np.argmax(variance))])

resolve_threshold(values, threshold, *, nbins=256)

Resolve an absolute, Otsu, or percentile threshold to a float.

Parameters:

Name Type Description Default
values Num[ndarray, '*dims']

Data the data-driven modes are evaluated on.

required
threshold ThresholdMode

A number (returned as-is), "otsu" (see :func:otsu_threshold), or "percentile:<p>" with p in [0, 100] (NaN-aware percentile of values).

required
nbins int

Histogram bins for the "otsu" mode, passed to :func:otsu_threshold. Default 256.

256

Returns:

Type Description
float

The resolved threshold value.

Raises:

Type Description
ValueError

If a string threshold is neither "otsu" nor a valid "percentile:<p>" spec.

Examples:

>>> resolve_threshold(np.arange(101.0), "percentile:90")
90.0
>>> resolve_threshold(np.arange(101.0), 3)
3.0
Source code in packages/geotoolz-ops/src/geoops/segment/_src/array.py
def resolve_threshold(
    values: Num[np.ndarray, "*dims"], threshold: ThresholdMode, *, nbins: int = 256
) -> float:
    """Resolve an absolute, Otsu, or percentile threshold to a float.

    Args:
        values: Data the data-driven modes are evaluated on.
        threshold: A number (returned as-is), ``"otsu"`` (see
            :func:`otsu_threshold`), or ``"percentile:<p>"`` with ``p``
            in ``[0, 100]`` (NaN-aware percentile of ``values``).
        nbins: Histogram bins for the ``"otsu"`` mode, passed to
            :func:`otsu_threshold`. Default ``256``.

    Returns:
        The resolved threshold value.

    Raises:
        ValueError: If a string threshold is neither ``"otsu"`` nor a
            valid ``"percentile:<p>"`` spec.

    Examples:
        >>> resolve_threshold(np.arange(101.0), "percentile:90")
        90.0
        >>> resolve_threshold(np.arange(101.0), 3)
        3.0
    """
    if isinstance(threshold, str):
        if threshold == "otsu":
            return otsu_threshold(values, nbins=nbins)
        prefix = "percentile:"
        if threshold.startswith(prefix):
            percentile = float(threshold.removeprefix(prefix))
            if not 0.0 <= percentile <= 100.0:
                raise ValueError("percentile threshold must be in [0, 100]")
            return float(np.nanpercentile(values, percentile))
        raise ValueError("threshold must be a number, 'otsu', or 'percentile:<p>'")
    return float(threshold)

threshold_mask(values, threshold='otsu', *, nbins=256)

Binary mask of the samples strictly above a resolved threshold.

mask = values > t,   t = resolve_threshold(values, threshold)

Non-finite samples are ignored by the data-driven modes and are never foreground (NaN > t is False).

Parameters:

Name Type Description Default
values Num[ndarray, '*dims']

Array of any shape; mark nodata as NaN.

required
threshold ThresholdMode

A number, "otsu" or "percentile:<p>"; see :func:resolve_threshold.

'otsu'
nbins int

Histogram bins for the "otsu" mode. Default 256.

256

Returns:

Type Description
Bool[ndarray, '*dims']

Boolean array shaped like values.

Examples:

>>> threshold_mask(np.array([0.0, np.nan, 5.0]), 1.0)
array([False, False,  True])
Source code in packages/geotoolz-ops/src/geoops/segment/_src/array.py
def threshold_mask(
    values: Num[np.ndarray, "*dims"],
    threshold: ThresholdMode = "otsu",
    *,
    nbins: int = 256,
) -> Bool[np.ndarray, "*dims"]:
    """Binary mask of the samples strictly above a resolved threshold.

        mask = values > t,   t = resolve_threshold(values, threshold)

    Non-finite samples are ignored by the data-driven modes and are never
    foreground (``NaN > t`` is ``False``).

    Args:
        values: Array of any shape; mark nodata as ``NaN``.
        threshold: A number, ``"otsu"`` or ``"percentile:<p>"``; see
            :func:`resolve_threshold`.
        nbins: Histogram bins for the ``"otsu"`` mode. Default ``256``.

    Returns:
        Boolean array shaped like ``values``.

    Examples:
        >>> threshold_mask(np.array([0.0, np.nan, 5.0]), 1.0)
        array([False, False,  True])
    """
    arr = np.asarray(values, dtype=float)
    with np.errstate(invalid="ignore"):
        return arr > resolve_threshold(arr, threshold, nbins=nbins)