Skip to content

Measure

geoops.measure wraps skimage.measure for region properties and contour extraction. Outputs are either label GeoArrays or GeoDataFrames with geometries in the input CRS.

  • LabelConnectedComponents — component labelling with connectivity=4|8 (skimage's 1|2 spelling is not accepted) and an optional min_area_px filter
  • RegionProps — per-component property table, called as RegionProps()(labels, intensity_image) (the optional intensity image must share the label map's grid); carries forbid_in_yaml=True (extra_properties callables cannot round-trip). Property columns are in pixel units (areas in pixels, lengths in pixel widths, positions as (row, col)); scale_to_crs=True converts areas / lengths / second moments to CRS units. The geometry column is always in CRS units.
  • FindContours — marching-squares iso-contours emitted as LineString features (CRS units)
  • SkeletonLength — longest Euclidean path through the mask skeleton, in pixel widths (scale_to_crs=True for CRS units)
  • ProfileLine — sample values along a line between two points
  • RANSAC — generic model fitting on (N, 2) coordinate pairs
  • ShannonEntropy — single-band scalar entropy

Shared primitives (also used by geoops.mask and geoops.plume): label_components, skeleton_length, regionprops_frame and DEFAULT_REGIONPROPS, plus regionprops_to_crs_units (the scale_to_crs=True conversion).

geoops.measure

Measurement operators for labels, regions, contours, and transects.

DEFAULT_REGIONPROPS = ('label', 'area', 'area_convex', 'area_filled', 'centroid', 'major_axis_length', 'minor_axis_length', 'orientation', 'eccentricity', 'solidity', 'perimeter', 'bbox', 'inertia_tensor_eigvals') module-attribute

Region properties computed by default by measure.RegionProps and plume.PlumeFootprint. All are in pixel units (areas in pixels, lengths in pixel widths, positions as (row, col) indices).

FindContours

Bases: Operator

Extract iso-value contours as LineString geometries.

Wraps :func:skimage.measure.find_contours over a single-band (H, W) or (1, H, W) image and maps each contour's pixel coordinates into world coordinates. Geo-dependent: the output geometries need the carrier's transform/CRS, so the input must be a georeferenced GeoArray (plain arrays raise TypeError).

Units: the geometry column is in CRS units (contour vertices are sub-pixel positions mapped through the transform, pixel centres at integer (row, col)); contour_id is a 1-based index. There are no pixel-unit columns, so there is no scale_to_crs switch.

Parameters:

Name Type Description Default
level float | None

Iso-value along which to find contours; None uses the midpoint of the image's value range.

None
fully_connected str

Whether high- or low-valued pixels are considered fully connected ("low" or "high").

'low'

Raises:

Type Description
TypeError

If the input is not a georeferenced GeoArray.

Source code in packages/geotoolz-ops/src/geoops/measure/_src/operators.py
class FindContours(Operator):
    """Extract iso-value contours as LineString geometries.

    Wraps :func:`skimage.measure.find_contours` over a single-band
    ``(H, W)`` or ``(1, H, W)`` image and maps each contour's pixel
    coordinates into world coordinates. Geo-dependent: the output
    geometries need the carrier's transform/CRS, so the input must be a
    georeferenced ``GeoArray`` (plain arrays raise ``TypeError``).

    Units: the ``geometry`` column is in CRS units (contour vertices are
    sub-pixel positions mapped through the transform, pixel centres at
    integer ``(row, col)``); ``contour_id`` is a 1-based index. There are
    no pixel-unit columns, so there is no ``scale_to_crs`` switch.

    Args:
        level: Iso-value along which to find contours; ``None`` uses the
            midpoint of the image's value range.
        fully_connected: Whether high- or low-valued pixels are
            considered fully connected (``"low"`` or ``"high"``).

    Raises:
        TypeError: If the input is not a georeferenced GeoArray.
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # marching squares over 2 x 2 cells
    coupling: ClassVar[Coupling] = Coupling(
        couples={"space"}, reach=1, kind="conversion"
    )

    _terminal: ClassVar[bool] = True

    def __init__(
        self,
        *,
        level: float | None = None,
        fully_connected: str = "low",
    ) -> None:
        self.level = level
        self.fully_connected = fully_connected

    def _apply(self, gt: GeoArray) -> gpd.GeoDataFrame:
        LineString = optional_name(
            "shapely.geometry",
            "LineString",
            "vector",
            feature="geoops.measure.FindContours",
        )
        find_contours = optional_name(
            "skimage.measure",
            "find_contours",
            "morph",
            feature="geoops.measure.FindContours",
        )
        gpd = optional_module(
            "geopandas", "vector", feature="geoops.measure.FindContours"
        )
        require_geoarray(gt, "FindContours")
        contours = find_contours(
            single_band(np.asarray(gt, dtype=float), name="FindContours"),
            level=self.level,
            fully_connected=self.fully_connected,
        )
        rows = []
        for contour_id, coords in enumerate(contours, start=1):
            if len(coords) >= 2:
                xs, ys = pixel_xy(gt.transform, coords[:, 0], coords[:, 1])
                geometry = LineString(np.column_stack([xs, ys]))
                rows.append({"contour_id": contour_id, "geometry": geometry})
        if not rows:
            # No contours (constant raster, out-of-range level, or all
            # segments degenerate to <2 points). Return an empty
            # GeoDataFrame with the expected schema instead of letting the
            # constructor raise on a missing ``geometry`` column.
            return gpd.GeoDataFrame(
                {"contour_id": [], "geometry": []},
                geometry="geometry",
                crs=gt.crs,
            )
        return gpd.GeoDataFrame(rows, geometry="geometry", crs=gt.crs)

LabelConnectedComponents

Bases: Operator

Convert a binary mask into an int32 connected-component label map.

Delegates to :func:geoops.measure.label_components. Expects a single-band (H, W) or (1, H, W) mask; pixels different from background are foreground. Accepts a GeoArray or a plain np.ndarray and returns an int32 label map (contiguous labels 1..K in raster order) in the same carrier kind, with fill_value=0. Nodata input pixels (non-finite or equal to the input's fill) are background 0 and never join components.

Parameters:

Name Type Description Default
connectivity Connectivity

4 (edge neighbours, default) or 8 (edge + diagonal neighbours).

4
background int

Pixel value treated as background and labelled 0.

0
min_area_px int

Minimum component size in pixels; smaller components become background. 0 keeps every component.

0
Source code in packages/geotoolz-ops/src/geoops/measure/_src/operators.py
class LabelConnectedComponents(Operator):
    """Convert a binary mask into an int32 connected-component label map.

    Delegates to :func:`geoops.measure.label_components`. Expects a
    single-band ``(H, W)`` or ``(1, H, W)`` mask; pixels different from
    ``background`` are foreground. Accepts a ``GeoArray`` or a plain
    ``np.ndarray`` and returns an ``int32`` label map (contiguous labels
    ``1..K`` in raster order) in the same carrier kind, with
    ``fill_value=0``. Nodata input pixels (non-finite or equal to
    the input's fill) are background ``0`` and never join components.

    Args:
        connectivity: ``4`` (edge neighbours, default) or ``8`` (edge +
            diagonal neighbours).
        background: Pixel value treated as background and labelled ``0``.
        min_area_px: Minimum component size in pixels; smaller components
            become background. ``0`` keeps every component.
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # a connected component can span the scene
    coupling: ClassVar[Coupling] = Coupling(couples={"space"}, reach=None)

    def __init__(
        self,
        *,
        connectivity: Connectivity = 4,
        background: int = 0,
        min_area_px: int = 0,
    ) -> None:
        self.connectivity = connectivity
        self.background = background
        self.min_area_px = min_area_px

    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        values = single_band(np.asarray(gt), name="LabelConnectedComponents")
        labels = label_components(
            (values != self.background) & single_band(valid_pixels(gt)),
            connectivity=self.connectivity,
            min_area_px=self.min_area_px,
        )
        return wrap_like(gt, labels, fill_value=0)

ProfileLine

Bases: Operator

Sample values along a line between two pixel coordinates.

Wraps :func:skimage.measure.profile_line over a single-band (H, W) or (1, H, W) image. Endpoints are pixel (row, col) coordinates and the returned profile is a plain 1-D np.ndarray, so both GeoArray and plain-array carriers are accepted.

Parameters:

Name Type Description Default
src tuple[int, int]

(row, col) start pixel of the profile.

required
dst tuple[int, int]

(row, col) end pixel of the profile.

required
linewidth int

Width of the sampling band, in pixels.

1
order int

Spline interpolation order (0 = nearest neighbour).

1
mode str

Boundary handling mode for samples outside the image.

'reflect'
Source code in packages/geotoolz-ops/src/geoops/measure/_src/operators.py
class ProfileLine(Operator):
    """Sample values along a line between two pixel coordinates.

    Wraps :func:`skimage.measure.profile_line` over a single-band
    ``(H, W)`` or ``(1, H, W)`` image. Endpoints are pixel ``(row, col)``
    coordinates and the returned profile is a plain 1-D ``np.ndarray``,
    so both ``GeoArray`` and plain-array carriers are accepted.

    Args:
        src: ``(row, col)`` start pixel of the profile.
        dst: ``(row, col)`` end pixel of the profile.
        linewidth: Width of the sampling band, in pixels.
        order: Spline interpolation order (0 = nearest neighbour).
        mode: Boundary handling mode for samples outside the image.
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # values interpolated along a line: a profile, not a raster
    coupling: ClassVar[Coupling] = Coupling(
        couples={"space"}, reach=None, kind="conversion"
    )

    _terminal: ClassVar[bool] = True

    def __init__(
        self,
        *,
        src: tuple[int, int],
        dst: tuple[int, int],
        linewidth: int = 1,
        order: int = 1,
        mode: str = "reflect",
    ) -> None:
        self.src = as_tuple(src)
        self.dst = as_tuple(dst)
        self.linewidth = linewidth
        self.order = order
        self.mode = mode

    def _apply(self, gt: GeoArray | np.ndarray) -> np.ndarray:
        profile_line = optional_name(
            "skimage.measure",
            "profile_line",
            "morph",
            feature="geoops.measure.ProfileLine",
        )
        reject_geotensor(gt, type(self).__name__)
        return profile_line(
            single_band(np.asarray(gt), name="ProfileLine"),
            self.src,
            self.dst,
            linewidth=self.linewidth,
            order=self.order,
            mode=self.mode,
        )

RANSAC

Bases: Operator

Robust model fitting via :func:skimage.measure.ransac.

Carrier-agnostic: the input is whatever data layout the chosen model class consumes (e.g. an (N, D) point array), and the output is the (model, inlier_mask) pair returned by ransac.

Parameters:

Name Type Description Default
model_class type[Any]

skimage model class to fit (e.g. skimage.measure.LineModelND). Not YAML-serialisable, so instances are forbidden in YAML.

required
min_samples int

Minimum number of samples per model estimate.

required
residual_threshold float

Maximum residual for a sample to count as an inlier.

required
**kwargs Any

Extra keyword arguments forwarded to :func:skimage.measure.ransac (e.g. max_trials, rng).

{}
Source code in packages/geotoolz-ops/src/geoops/measure/_src/operators.py
class RANSAC(Operator):
    """Robust model fitting via :func:`skimage.measure.ransac`.

    Carrier-agnostic: the input is whatever data layout the chosen model
    class consumes (e.g. an ``(N, D)`` point array), and the output is
    the ``(model, inlier_mask)`` pair returned by ``ransac``.

    Args:
        model_class: skimage model class to fit (e.g.
            ``skimage.measure.LineModelND``). Not YAML-serialisable, so
            instances are forbidden in YAML.
        min_samples: Minimum number of samples per model estimate.
        residual_threshold: Maximum residual for a sample to count as an
            inlier.
        **kwargs: Extra keyword arguments forwarded to
            :func:`skimage.measure.ransac` (e.g. ``max_trials``, ``rng``).
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    coupling: ClassVar[Coupling] = Coupling(kind="conversion")

    _terminal: ClassVar[bool] = True

    forbid_in_yaml: ClassVar[bool] = True

    def __init__(
        self,
        *,
        model_class: type[Any],
        min_samples: int,
        residual_threshold: float,
        **kwargs: Any,
    ) -> None:
        self.model_class = model_class
        self.min_samples = min_samples
        self.residual_threshold = residual_threshold
        self.kwargs = kwargs

    def _apply(self, data: Any) -> Any:
        ransac = optional_name(
            "skimage.measure",
            "ransac",
            "morph",
            feature="geoops.measure.RANSAC",
        )
        return ransac(
            data,
            self.model_class,
            min_samples=self.min_samples,
            residual_threshold=self.residual_threshold,
            **self.kwargs,
        )

    def get_config(self) -> dict[str, Any]:
        return {
            "model_class": getattr(
                self.model_class,
                "__name__",
                repr(self.model_class),
            ),
            "min_samples": self.min_samples,
            "residual_threshold": self.residual_threshold,
            **self.kwargs,
        }

RegionProps

Bases: Operator

Extract a GeoDataFrame of per-region statistics from a label map.

Wraps :func:skimage.measure.regionprops_table over a single-band (H, W) or (1, H, W) integer label map. When the centroid property is requested (the default), each row carries a Point geometry at the region centroid in world coordinates. Geo-dependent: the output geometry needs the carrier's transform/CRS, so the input must be a georeferenced GeoArray (plain arrays raise TypeError).

Units: the geometry column is in CRS units. The property columns are in pixel units by default -- areas in pixels, lengths (perimeter, major_axis_length, ...) in pixel widths, second moments (inertia_tensor*) in squared pixel widths, positions (centroid-*, bbox-*) as (row, col) indices. With scale_to_crs=True areas, lengths and second moments are converted to CRS units (m^2 / m / m^2 for a projected metric CRS); positions, angles and dimensionless ratios are unchanged.

Called as op(labels, intensity_image=None). The optional intensity_image is a single-band carrier on the label map's pixel grid (ValueError otherwise) and enables intensity-based properties.

Parameters:

Name Type Description Default
properties Sequence[str] | None

Property names passed to regionprops_table; defaults to :data:DEFAULT_REGIONPROPS.

None
extra_properties Sequence[Callable[..., Any]] | None

Optional callables computing custom per-region properties (see skimage docs). Not YAML-serialisable, so instances are forbidden in YAML. Their outputs are never rescaled.

None
scale_to_crs bool

Convert area / length / second-moment columns from pixel to CRS units using the carrier's transform.

False

Raises:

Type Description
TypeError

If the input is not a georeferenced GeoArray.

ValueError

If intensity_image is on another pixel grid, or if scale_to_crs=True and a length or moment column is requested on non-square (anisotropic or sheared) pixels, where no single pixel length exists.

Source code in packages/geotoolz-ops/src/geoops/measure/_src/operators.py
class RegionProps(Operator):
    """Extract a GeoDataFrame of per-region statistics from a label map.

    Wraps :func:`skimage.measure.regionprops_table` over a single-band
    ``(H, W)`` or ``(1, H, W)`` integer label map. When the ``centroid``
    property is requested (the default), each row carries a ``Point``
    geometry at the region centroid in world coordinates. Geo-dependent:
    the output geometry needs the carrier's transform/CRS, so the input
    must be a georeferenced ``GeoArray`` (plain arrays raise
    ``TypeError``).

    Units: the ``geometry`` column is in CRS units. The property columns
    are in **pixel units** by default -- areas in pixels, lengths
    (``perimeter``, ``major_axis_length``, ...) in pixel widths, second
    moments (``inertia_tensor*``) in squared pixel widths, positions
    (``centroid-*``, ``bbox-*``) as ``(row, col)`` indices. With
    ``scale_to_crs=True`` areas, lengths and second moments are converted
    to CRS units (m^2 / m / m^2 for a projected metric CRS); positions,
    angles and dimensionless ratios are unchanged.

    Called as ``op(labels, intensity_image=None)``. The optional
    ``intensity_image`` is a single-band carrier on the label map's pixel
    grid (``ValueError`` otherwise) and enables intensity-based
    properties.

    Args:
        properties: Property names passed to ``regionprops_table``;
            defaults to :data:`DEFAULT_REGIONPROPS`.
        extra_properties: Optional callables computing custom per-region
            properties (see skimage docs). Not YAML-serialisable, so
            instances are forbidden in YAML. Their outputs are never
            rescaled.
        scale_to_crs: Convert area / length / second-moment columns from
            pixel to CRS units using the carrier's transform.

    Raises:
        TypeError: If the input is not a georeferenced GeoArray.
        ValueError: If ``intensity_image`` is on another pixel grid, or
            if ``scale_to_crs=True`` and a length or moment
            column is requested on non-square (anisotropic or sheared)
            pixels, where no single pixel length exists.
    """

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

    _terminal: ClassVar[bool] = True

    forbid_in_yaml: ClassVar[bool] = True

    def __init__(
        self,
        *,
        properties: Sequence[str] | None = None,
        extra_properties: Sequence[Callable[..., Any]] | None = None,
        scale_to_crs: bool = False,
    ) -> None:
        self.properties = tuple(
            DEFAULT_REGIONPROPS if properties is None else properties
        )
        self.extra_properties = (
            None if extra_properties is None else tuple(extra_properties)
        )
        self.scale_to_crs = scale_to_crs

    def _apply(
        self, gt: GeoArray, intensity_image: GeoArray | np.ndarray | None = None
    ) -> gpd.GeoDataFrame:
        gpd = optional_module(
            "geopandas", "vector", feature="geoops.measure.RegionProps"
        )
        require_geoarray(gt, "RegionProps")
        if intensity_image is not None:
            require_grid_match(
                gt, intensity_image, "RegionProps", names=("labels", "intensity_image")
            )
        labels = single_band(np.asarray(gt), name="RegionProps").astype(
            np.int32, copy=False
        )
        intensity = (
            None
            if intensity_image is None
            else single_band(intensity_image, name="RegionProps intensity_image")
        )
        frame = regionprops_frame(
            labels,
            intensity_image=intensity,
            properties=self.properties,
            extra_properties=self.extra_properties,
        )
        if self.scale_to_crs:
            frame = regionprops_to_crs_units(frame, affine_of(gt))
        if frame.empty:
            return gpd.GeoDataFrame(frame, geometry=[], crs=gt.crs)
        if {"centroid-0", "centroid-1"}.issubset(frame.columns):
            xs, ys = pixel_xy(gt.transform, frame["centroid-0"], frame["centroid-1"])
            geometry = gpd.points_from_xy(xs, ys)
            return gpd.GeoDataFrame(frame, geometry=geometry, crs=gt.crs)
        # Caller omitted centroid: still return a valid GeoDataFrame with an
        # empty (None-valued) geometry column rather than raising in the
        # ``GeoDataFrame`` constructor for missing geometry.
        return gpd.GeoDataFrame(frame, geometry=[None] * len(frame), crs=gt.crs)

    def get_config(self) -> dict[str, Any]:
        return {
            "properties": list(self.properties),
            "extra_properties": None
            if self.extra_properties is None
            else [
                getattr(func, "__name__", repr(func)) for func in self.extra_properties
            ],
            "scale_to_crs": self.scale_to_crs,
        }

ShannonEntropy

Bases: Operator

Compute Shannon entropy of the input image.

Wraps :func:skimage.measure.shannon_entropy over a single-band (H, W) or (1, H, W) image. The result is a plain float, so both GeoArray and plain-array carriers are accepted.

Parameters:

Name Type Description Default
base float

Logarithm base for the entropy (2.0 gives bits).

2.0
Source code in packages/geotoolz-ops/src/geoops/measure/_src/operators.py
class ShannonEntropy(Operator):
    """Compute Shannon entropy of the input image.

    Wraps :func:`skimage.measure.shannon_entropy` over a single-band
    ``(H, W)`` or ``(1, H, W)`` image. The result is a plain float, so
    both ``GeoArray`` and plain-array carriers are accepted.

    Args:
        base: Logarithm base for the entropy (``2.0`` gives bits).
    """

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

    _terminal: ClassVar[bool] = True

    def __init__(self, *, base: float = 2.0) -> None:
        self.base = base

    def _apply(self, gt: GeoArray | np.ndarray) -> float:
        shannon_entropy = optional_name(
            "skimage.measure",
            "shannon_entropy",
            "morph",
            feature="geoops.measure.ShannonEntropy",
        )
        reject_geotensor(gt, type(self).__name__)
        return float(
            shannon_entropy(
                single_band(np.asarray(gt), name="ShannonEntropy"), base=self.base
            )
        )

SkeletonLength

Bases: Operator

Longest path through the skeleton of a binary mask.

Delegates to :func:geoops.measure.skeleton_length: the mask is skeletonised with :func:skimage.morphology.skeletonize and the longest geodesic path through the 8-connected skeleton is measured between pixel centres, each step weighted by its Euclidean length (a diagonal step counts sqrt(2)). This is the geodesic "fiber length" of Pérez Carrasco et al. (2026) with Euclidean rather than unit step weights.

Units: pixel widths by default, so both GeoArray and plain-array carriers are accepted. With scale_to_crs=True steps are measured through the carrier's transform (anisotropic and rotated grids included) and the result is in CRS units (m for a projected metric CRS); the input must then be a georeferenced GeoArray.

Returns 0.0 for empty masks or skeletons that collapse to a single pixel.

Parameters:

Name Type Description Default
scale_to_crs bool

Measure in CRS units via the carrier's transform instead of pixel widths.

False

Raises:

Type Description
TypeError

If scale_to_crs=True and the input is not a georeferenced GeoArray.

Source code in packages/geotoolz-ops/src/geoops/measure/_src/operators.py
class SkeletonLength(Operator):
    """Longest path through the skeleton of a binary mask.

    Delegates to :func:`geoops.measure.skeleton_length`: the mask is
    skeletonised with :func:`skimage.morphology.skeletonize` and the
    longest geodesic path through the 8-connected skeleton is measured
    between pixel centres, each step weighted by its Euclidean length
    (a diagonal step counts ``sqrt(2)``). This is the geodesic "fiber
    length" of Pérez Carrasco et al. (2026) with Euclidean rather than
    unit step weights.

    Units: pixel widths by default, so both ``GeoArray`` and plain-array
    carriers are accepted. With ``scale_to_crs=True`` steps are measured
    through the carrier's transform (anisotropic and rotated grids
    included) and the result is in CRS units (m for a projected metric
    CRS); the input must then be a georeferenced ``GeoArray``.

    Returns ``0.0`` for empty masks or skeletons that collapse to a single
    pixel.

    Args:
        scale_to_crs: Measure in CRS units via the carrier's transform
            instead of pixel widths.

    Raises:
        TypeError: If ``scale_to_crs=True`` and the input is not a
            georeferenced GeoArray.
    """

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

    _terminal: ClassVar[bool] = True

    def __init__(self, *, scale_to_crs: bool = False) -> None:
        self.scale_to_crs = scale_to_crs

    def _apply(self, gt: GeoArray | np.ndarray) -> float:
        reject_geotensor(gt, type(self).__name__)
        step: Any = (1.0, 1.0)
        if self.scale_to_crs:
            step = affine_of(require_geoarray(gt, "SkeletonLength(scale_to_crs=True)"))
        return skeleton_length(
            single_band(np.asarray(gt), name="SkeletonLength"), step=step
        )

label_components(mask, *, connectivity=8, min_area_px=0)

Label connected True regions and drop components below min_area_px.

Uses :func:scipy.ndimage.label (raster-order labels, identical to :func:skimage.measure.label on a boolean mask), then renumbers the surviving components contiguously (1..K) without a second labelling pass -- dropping pixels from a labelled image cannot merge distinct components.

Parameters:

Name Type Description Default
mask Bool[ndarray, 'h w']

2-D mask; any array-like is coerced with np.asarray(mask, dtype=bool).

required
connectivity Connectivity

4 or 8 neighbourhood for component membership.

8
min_area_px int

Minimum component size in pixels; smaller components become background. 0 and 1 keep every component.

0

Returns:

Type Description
Int[ndarray, 'h w']

An int32 label image with contiguous labels 1..K for the

Int[ndarray, 'h w']

surviving components and 0 for background.

Raises:

Type Description
ValueError

If min_area_px is negative or connectivity is not 4 or 8.

Source code in packages/geotoolz-ops/src/geoops/_src/labels.py
def label_components(
    mask: Bool[np.ndarray, "h w"],
    *,
    connectivity: Connectivity = 8,
    min_area_px: int = 0,
) -> Int[np.ndarray, "h w"]:
    """Label connected True regions and drop components below ``min_area_px``.

    Uses :func:`scipy.ndimage.label` (raster-order labels, identical to
    :func:`skimage.measure.label` on a boolean mask), then renumbers the
    surviving components contiguously (``1..K``) without a second
    labelling pass -- dropping pixels from a labelled image cannot merge
    distinct components.

    Args:
        mask: 2-D mask; any array-like is coerced with
            ``np.asarray(mask, dtype=bool)``.
        connectivity: ``4`` or ``8`` neighbourhood for component
            membership.
        min_area_px: Minimum component size in pixels; smaller components
            become background. ``0`` and ``1`` keep every component.

    Returns:
        An ``int32`` label image with contiguous labels ``1..K`` for the
        surviving components and ``0`` for background.

    Raises:
        ValueError: If ``min_area_px`` is negative or ``connectivity`` is
            not 4 or 8.
    """
    if min_area_px < 0:
        raise ValueError(f"min_area_px must be non-negative, got {min_area_px}")
    labels, n_labels = ndimage.label(
        np.asarray(mask, dtype=bool), structure=connectivity_structure(connectivity)
    )
    if n_labels == 0 or min_area_px <= 1:
        return labels.astype(np.int32, copy=False)
    counts = np.bincount(labels.ravel())
    keep = counts >= min_area_px
    keep[0] = False
    # 0..K renumbering LUT so labels stay contiguous after dropping.
    lut = np.zeros_like(counts, dtype=np.int32)
    lut[keep] = np.arange(1, int(keep.sum()) + 1, dtype=np.int32)
    return lut[labels]

regionprops_frame(labels, *, intensity_image=None, properties=DEFAULT_REGIONPROPS, extra_properties=None)

Per-region property table of an integer label image.

Thin wrapper around :func:skimage.measure.regionprops_table; every value is in pixel units (see :data:DEFAULT_REGIONPROPS).

Parameters:

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

2-D integer label image; 0 is background.

required
intensity_image Shaped[ndarray, 'h w'] | None

Optional 2-D intensity image aligned with labels for the intensity-based properties.

None
properties Sequence[str]

Property names to compute.

DEFAULT_REGIONPROPS
extra_properties Sequence[Callable[..., Any]] | None

Optional custom per-region callables.

None

Returns:

Type Description
DataFrame

One row per label, columns named as skimage names them

DataFrame

("centroid-0", "bbox-3", ...).

Source code in packages/geotoolz-ops/src/geoops/_src/labels.py
def regionprops_frame(
    labels: Int[np.ndarray, "h w"],
    *,
    intensity_image: Shaped[np.ndarray, "h w"] | None = None,
    properties: Sequence[str] = DEFAULT_REGIONPROPS,
    extra_properties: Sequence[Callable[..., Any]] | None = None,
) -> pd.DataFrame:
    """Per-region property table of an integer label image.

    Thin wrapper around :func:`skimage.measure.regionprops_table`; every
    value is in pixel units (see :data:`DEFAULT_REGIONPROPS`).

    Args:
        labels: 2-D integer label image; ``0`` is background.
        intensity_image: Optional 2-D intensity image aligned with
            ``labels`` for the intensity-based properties.
        properties: Property names to compute.
        extra_properties: Optional custom per-region callables.

    Returns:
        One row per label, columns named as skimage names them
        (``"centroid-0"``, ``"bbox-3"``, ...).
    """
    regionprops_table = optional_name(
        "skimage.measure",
        "regionprops_table",
        "morph",
        feature="geoops",
    )
    return pd.DataFrame(
        regionprops_table(
            np.asarray(labels).astype(np.int32, copy=False),
            intensity_image=intensity_image,
            properties=tuple(properties),
            extra_properties=extra_properties,
        )
    )

regionprops_to_crs_units(frame, transform)

Convert pixel-unit region-property columns to CRS units.

With A = |a·e - b·d| the pixel area and s the pixel side:

area → area · A,   length → length · s,   moment → moment · s²

Columns are matched by their base name (inertia_tensor-0-1 → inertia_tensor); unlisted columns are copied unchanged.

Parameters:

Name Type Description Default
frame DataFrame

A :func:regionprops_frame table in pixel units.

required
transform Any

Affine-like object exposing a, b, d, e.

required

Returns:

Type Description
DataFrame

A converted copy of frame.

Raises:

Type Description
ValueError

If a length or moment column is present and the pixels are not square (anisotropic or sheared), where no single pixel length exists.

Examples:

>>> from affine import Affine
>>> frame = pd.DataFrame({"label": [1], "area": [4.0], "perimeter": [8.0]})
>>> regionprops_to_crs_units(frame, Affine(10, 0, 0, 0, -10, 0))
   label   area  perimeter
0      1  400.0       80.0
Source code in packages/geotoolz-ops/src/geoops/measure/_src/array.py
def regionprops_to_crs_units(frame: pd.DataFrame, transform: Any) -> pd.DataFrame:
    """Convert pixel-unit region-property columns to CRS units.

    With ``A = |a·e - b·d|`` the pixel area and ``s`` the pixel side:

        area → area · A,   length → length · s,   moment → moment · s²

    Columns are matched by their base name (``inertia_tensor-0-1`` →
    ``inertia_tensor``); unlisted columns are copied unchanged.

    Args:
        frame: A :func:`regionprops_frame` table in pixel units.
        transform: Affine-like object exposing ``a, b, d, e``.

    Returns:
        A converted copy of ``frame``.

    Raises:
        ValueError: If a length or moment column is present and the
            pixels are not square (anisotropic or sheared), where no
            single pixel length exists.

    Examples:
        >>> from affine import Affine
        >>> frame = pd.DataFrame({"label": [1], "area": [4.0], "perimeter": [8.0]})
        >>> regionprops_to_crs_units(frame, Affine(10, 0, 0, 0, -10, 0))
           label   area  perimeter
        0      1  400.0       80.0
    """
    a, b = float(transform.a), float(transform.b)
    d, e = float(transform.d), float(transform.e)
    pixel_area = abs(a * e - b * d)
    # Transform columns: the CRS step of one pixel column / row.
    col_step, row_step = float(np.hypot(a, d)), float(np.hypot(b, e))
    square = bool(
        np.isclose(col_step, row_step)
        and np.isclose(a * b + d * e, 0.0, atol=1e-12 * max(pixel_area, 1.0))
    )
    out = frame.copy()
    for column in frame.columns:
        base = str(column).split("-")[0]
        if base in AREA_PROPS:
            out[column] = frame[column] * pixel_area
        elif base in LENGTH_PROPS or base in MOMENT_PROPS:
            if not square:
                raise ValueError(
                    f"RegionProps(scale_to_crs=True): {base!r} has no CRS-unit "
                    f"equivalent on non-square pixels (transform a={a}, b={b}, "
                    f"d={d}, e={e}); request area properties only, or resample "
                    "to square pixels first."
                )
            power = 1 if base in LENGTH_PROPS else 2
            out[column] = frame[column] * col_step**power
    return out

skeleton_length(mask, *, step=(1.0, 1.0), connectivity=8)

Longest geodesic path through the skeleton of a binary mask.

The mask is skeletonised with :func:skimage.morphology.skeletonize and each step between neighbouring skeleton pixels is weighted by its Euclidean length, so a diagonal step on square unit pixels counts sqrt(2) and anisotropic / rotated grids are measured correctly. The path runs between skeleton pixel centres: a straight line of n pixels measures n - 1 steps.

The result is the exact graph diameter of each connected skeleton component (the longest of its shortest paths), maximised over components. A tree-shaped component uses a double Dijkstra sweep (farthest pixel from a seed, then farthest from that), which is exact for trees; a component with a loop -- where that sweep can under-estimate -- runs Dijkstra from every pixel. The sweep seed is the lexicographically smallest (row, col), so the result is deterministic.

Parameters:

Name Type Description Default
mask Shaped[ndarray, 'h w']

2-D mask. Boolean input is used as is; other dtypes are foreground where > 0 (NaN is background).

required
step tuple[float, float] | Any

Pixel size, either a (dy, dx) pair (row step, column step) or an affine geotransform with a, b, d, e coefficients. The default (1.0, 1.0) returns the length in pixel widths; a geotransform returns it in CRS units (m for a projected metric CRS).

(1.0, 1.0)
connectivity Connectivity

8 (default) walks diagonal steps too; 4 walks only edge steps.

8

Returns:

Type Description
float

The longest path length in the units of step; 0.0 for an

float

empty mask or when every skeleton component is a single pixel.

Raises:

Type Description
ValueError

If connectivity is not 4 or 8.

Source code in packages/geotoolz-ops/src/geoops/_src/labels.py
def skeleton_length(
    mask: Shaped[np.ndarray, "h w"],
    *,
    step: tuple[float, float] | Any = (1.0, 1.0),
    connectivity: Connectivity = 8,
) -> float:
    """Longest geodesic path through the skeleton of a binary mask.

    The mask is skeletonised with :func:`skimage.morphology.skeletonize`
    and each step between neighbouring skeleton pixels is weighted by its
    Euclidean length, so a diagonal step on square unit pixels counts
    ``sqrt(2)`` and anisotropic / rotated grids are measured correctly.
    The path runs between skeleton pixel *centres*: a straight line of
    ``n`` pixels measures ``n - 1`` steps.

    The result is the exact graph diameter of each connected skeleton
    component (the longest of its shortest paths), maximised over
    components. A tree-shaped component uses a double Dijkstra sweep
    (farthest pixel from a seed, then farthest from that), which is exact
    for trees; a component with a loop -- where that sweep can
    under-estimate -- runs Dijkstra from every pixel. The sweep seed is
    the lexicographically smallest ``(row, col)``, so the result is
    deterministic.

    Args:
        mask: 2-D mask. Boolean input is used as is; other dtypes are
            foreground where ``> 0`` (``NaN`` is background).
        step: Pixel size, either a ``(dy, dx)`` pair (row step, column
            step) or an affine geotransform with ``a``, ``b``, ``d``,
            ``e`` coefficients. The default ``(1.0, 1.0)`` returns the
            length in pixel widths; a geotransform returns it in CRS
            units (m for a projected metric CRS).
        connectivity: ``8`` (default) walks diagonal steps too; ``4``
            walks only edge steps.

    Returns:
        The longest path length in the units of ``step``; ``0.0`` for an
        empty mask or when every skeleton component is a single pixel.

    Raises:
        ValueError: If ``connectivity`` is not 4 or 8.
    """
    skeletonize = optional_name(
        "skimage.morphology",
        "skeletonize",
        "morph",
        feature="geoops",
    )
    arr = np.asarray(mask)
    binary = arr if arr.dtype == bool else np.nan_to_num(arr, nan=0.0) > 0
    if connectivity not in (4, 8):
        raise ValueError(f"connectivity must be 4 or 8, got {connectivity!r}")
    if not binary.any():
        return 0.0
    if hasattr(step, "a"):
        a, b, d, e = float(step.a), float(step.b), float(step.d), float(step.e)
    else:
        dy, dx = (float(s) for s in step)
        a, b, d, e = dx, 0.0, 0.0, dy
    # Step length for each (drow, dcol) offset: the transform maps a
    # (dcol, drow) pixel step to (step_x, step_y).
    offsets = _NEIGHBOURS_8 if connectivity == 8 else _NEIGHBOURS_4
    step_length = {
        (drow, dcol): float(np.hypot(a * dcol + b * drow, d * dcol + e * drow))
        for drow, dcol in offsets
    }
    return _longest_path(skeletonize(binary), step_length)