Skip to content

Mask

Geometry-based masks, morphological mask ops, and boolean mask algebra. Convention: True means "mask this pixel out" (consistent with geoops.qa; see Mask polarity).

  • Geometry / DEM masks: PolygonMask, BBoxMask, DistanceMask, LandMask, OceanMask, CountryMask, AltitudeMask, SlopeMask — keep="inside" (default) keeps the region and masks everything else; keep="outside" drops the region. LandMask / OceanMask / CountryMask load Natural Earth lazily on their first call (never in the constructor, so building or hydrating a pipeline does no network I/O); the GeoDataFrames are then cached for the process lifetime — mask.clear_natural_earth_cache() releases them. AltitudeMask / SlopeMask take the DEM as a second positional carrier on the scene's grid: SlopeMask(max_slope_deg=10.0)(scene, dem).
  • Morphology: DilateMask, ErodeMask, OpenMask, CloseMask, BufferMask, RemoveSmallObjects, RemoveSmallHoles, CleanMask
  • Algebra: CombineMasks(op="or" | "and" | "xor")(m1, m2, ...) (masks on one pixel grid), InvertMask
  • Apply: ApplyMask (fill values where mask is True): ApplyMask()(gt, mask) with a mask carrier, or ApplyMask(mask=BBoxMask(...))(gt) with a mask-producing operator
  • Tier-A primitives: apply_mask, dilate_mask, erode_mask, open_mask, close_mask, buffer_mask, clean_mask, remove_small_objects, remove_small_holes, combine_masks, invert_mask, distance_mask, altitude_mask, slope_mask, slope_degrees

geoops.mask

Geometry masks, morphological cleanup, mask algebra, and mask application.

AltitudeMask

Bases: Operator

Build a boolean mask from DEM elevation bounds.

Follows the package polarity (True = drop): with the default keep="inside" the mask is True where the DEM falls outside the requested elevation interval. Either bound may be None for an open-ended interval.

Called as op(scene, dem): the output mask is wrapped like scene (a GeoArray or plain ndarray), and dem is a single-band carrier on the scene's pixel grid -- same spatial shape and, when both are georeferenced, the same transform / CRS (ValueError otherwise).

Parameters:

Name Type Description Default
min_elev float | None

Inclusive lower bound (units of the DEM).

None
max_elev float | None

Inclusive upper bound.

None
keep Keep

"inside" (default) keeps cells inside the interval; "outside" keeps cells outside it.

'inside'

Examples:

>>> AltitudeMask(min_elev=500.0)(scene, dem)
Source code in packages/geotoolz-ops/src/geoops/mask/_src/operators.py
class AltitudeMask(Operator):
    """Build a boolean mask from DEM elevation bounds.

    Follows the package polarity (True = drop): with the default
    ``keep="inside"`` the mask is True where the DEM falls *outside* the
    requested elevation interval. Either bound may be ``None`` for an
    open-ended interval.

    Called as ``op(scene, dem)``: the output mask is wrapped like
    ``scene`` (a GeoArray or plain ndarray), and ``dem`` is a single-band
    carrier on the scene's pixel grid -- same spatial shape and, when both
    are georeferenced, the same transform / CRS (``ValueError``
    otherwise).

    Args:
        min_elev: Inclusive lower bound (units of the DEM).
        max_elev: Inclusive upper bound.
        keep: ``"inside"`` (default) keeps cells inside the interval;
            ``"outside"`` keeps cells outside it.

    Examples:
        >>> AltitudeMask(min_elev=500.0)(scene, dem)  # doctest: +SKIP
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # the DEM at each pixel; the input gives only the grid
    coupling: ClassVar[Coupling] = Coupling(reads_values=False)

    def __init__(
        self,
        *,
        min_elev: float | None = None,
        max_elev: float | None = None,
        keep: Keep = "inside",
    ) -> None:
        self.min_elev = min_elev
        self.max_elev = max_elev
        self.keep = _check_keep(keep, "AltitudeMask")

    def _apply(
        self, gt: GeoArray | np.ndarray, dem: GeoArray | np.ndarray
    ) -> GeoArray | np.ndarray:
        require_grid_match(gt, dem, "AltitudeMask", names=("scene", "dem"))
        mask = altitude_mask(
            np.asarray(dem),
            min_elev=self.min_elev,
            max_elev=self.max_elev,
            keep=self.keep,
        )
        return wrap_like(gt, mask, fill_value=False)

ApplyMask

Bases: Operator

Apply a boolean mask to the carrier, filling True pixels.

Accepts a GeoArray or a plain ndarray and returns the same carrier kind. This is the canonical mask-application operator. Delegates the actual masking to :func:geoops.mask._src.array.apply_mask so the broadcasting + dtype-preservation rules stay in one place.

Convention: the mask is True where pixels should be masked out — the polarity every geoops.mask and geoops.qa producer returns, so geometry masks keep their area of interest by default. Flip a keep-polarity mask (e.g. valid_mask()) with :class:InvertMask / :func:~geoops.mask.invert_mask first.

Called as op(gt, mask) with the boolean mask carrier (GeoArray or ndarray) on gt's pixel grid (ValueError otherwise), so it wires into a pipekit_ops.Graph as ApplyMask()(Input("x"), Input("mask")). Alternatively configure a mask operator (e.g. a geometry mask) that builds the mask from gt and call op(gt).

Parameters:

Name Type Description Default
mask Operator | None

Optional Operator producing the mask when called on the input. Mask arrays are passed at call time, not here.

None
fill_value float | None

Value substituted where the mask says "drop". The default None uses the carrier's fill_value when it has one that the carrier's dtype can hold (so an integer carrier is not upcast), and NaN otherwise. The output declares this value as its fill_value, and the input's own nodata pixels are rewritten to it, so valid_mask() marks every dropped and nodata pixel. Note that the fill value marks nodata even when it is 0.

None

Examples:

>>> import geoops as gz, numpy as np
>>> aoi = gz.mask.BBoxMask(bounds=(1.0, 1.0, 3.0, 3.0))
>>> keep_aoi = gz.mask.ApplyMask(mask=aoi)  # fills outside the box
>>> out = keep_aoi(scene)
>>> out = gz.mask.ApplyMask()(scene, cloud_mask)
Source code in packages/geotoolz-ops/src/geoops/mask/_src/operators.py
class ApplyMask(Operator):
    """Apply a boolean mask to the carrier, filling True pixels.

    Accepts a GeoArray or a plain ndarray and returns the same
    carrier kind. This is the canonical mask-application operator.
    Delegates the actual masking to
    :func:`geoops.mask._src.array.apply_mask` so the broadcasting +
    dtype-preservation rules stay in one place.

    Convention: the mask is True where pixels should be *masked out* —
    the polarity every ``geoops.mask`` and ``geoops.qa`` producer
    returns, so geometry masks keep their area of interest by default.
    Flip a keep-polarity mask (e.g. ``valid_mask()``) with
    :class:`InvertMask` / :func:`~geoops.mask.invert_mask` first.

    Called as ``op(gt, mask)`` with the boolean mask carrier (GeoArray
    or ndarray) on ``gt``'s pixel grid (``ValueError`` otherwise), so it
    wires into a ``pipekit_ops.Graph`` as ``ApplyMask()(Input("x"),
    Input("mask"))``. Alternatively configure a mask *operator* (e.g. a
    geometry mask) that builds the mask from ``gt`` and call ``op(gt)``.

    Args:
        mask: Optional ``Operator`` producing the mask when called on the
            input. Mask arrays are passed at call time, not here.
        fill_value: Value substituted where the mask says "drop". The
            default ``None`` uses the carrier's ``fill_value``
            when it has one that the carrier's dtype can hold (so an
            integer carrier is not upcast), and ``NaN`` otherwise. The
            output declares this value as its ``fill_value``, and
            the input's own nodata pixels are rewritten to it, so
            ``valid_mask()`` marks every dropped and nodata pixel.
            Note that the fill value marks nodata even when it is ``0``.

    Examples:
        >>> import geoops as gz, numpy as np
        >>> aoi = gz.mask.BBoxMask(bounds=(1.0, 1.0, 3.0, 3.0))
        >>> keep_aoi = gz.mask.ApplyMask(mask=aoi)  # fills outside the box
        >>> out = keep_aoi(scene)  # doctest: +SKIP
        >>> out = gz.mask.ApplyMask()(scene, cloud_mask)  # doctest: +SKIP
    """

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

    def __init__(
        self,
        *,
        mask: Operator | None = None,
        fill_value: float | None = None,
    ) -> None:
        if mask is not None and not isinstance(mask, Operator):
            raise TypeError(
                "ApplyMask(mask=...) takes a mask-producing Operator; pass a "
                "mask array or GeoArray at call time instead: "
                "ApplyMask()(gt, mask)"
            )
        self.mask = mask
        self.fill_value = fill_value

    def _apply(
        self, gt: GeoArray | np.ndarray, mask: GeoArray | np.ndarray | None = None
    ) -> GeoArray | np.ndarray:
        if (mask is None) == (self.mask is None):
            raise ValueError(
                "ApplyMask needs exactly one mask: a mask carrier at call time, "
                "ApplyMask()(gt, mask), or a mask operator, ApplyMask(mask=op)(gt)"
            )
        if mask is not None:
            require_grid_match(gt, mask, "ApplyMask", names=("input", "mask"))
        elif self.mask is not None:
            mask = self.mask(gt)
        mask_arr = np.asarray(mask)
        fill = self._resolve_fill(gt)
        out = apply_mask(np.asarray(gt), mask_arr, fill_value=fill)
        if np.ndim(out) < 2:
            return wrap_like(gt, out, fill_value=fill)
        return wrap_filled(gt, out, fill_value=fill)

    def _resolve_fill(self, gt: GeoArray | np.ndarray) -> Any:
        """The fill to write: explicit, else a usable carrier fill, else NaN."""
        if self.fill_value is not None:
            return self.fill_value
        fill = carrier_fill_value(gt)
        dtype = np.asarray(gt).dtype
        if np.issubdtype(dtype, np.bool_):
            usable = isinstance(fill, bool | np.bool_)
        else:
            # ``carried_fill`` is None when an integer dtype cannot hold it.
            usable = carried_fill(gt, dtype) is not None
        return fill if usable else np.nan

    def get_config(self) -> dict[str, Any]:
        return {
            "mask": None if self.mask is None else nested_config(self.mask),
            "fill_value": self.fill_value,
        }

BBoxMask

Bases: PolygonMask

Rasterize an axis-aligned bounding box into a boolean mask.

Geo-dependent: requires a georeferenced GeoArray input (see :class:PolygonMask).

Parameters:

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

(minx, miny, maxx, maxy) box in crs coordinates.

required
crs str | None

CRS of bounds; defaults to the carrier's CRS.

None
keep Keep

"inside" (default) keeps the box (mask True outside it); "outside" drops the box.

'inside'

Examples:

>>> aoi = BBoxMask(bounds=(1.0, 1.0, 3.0, 3.0))
>>> ApplyMask(mask=aoi)(scene)  # keeps the box
Source code in packages/geotoolz-ops/src/geoops/mask/_src/operators.py
class BBoxMask(PolygonMask):
    """Rasterize an axis-aligned bounding box into a boolean mask.

    Geo-dependent: requires a georeferenced ``GeoArray`` input (see
    :class:`PolygonMask`).

    Args:
        bounds: ``(minx, miny, maxx, maxy)`` box in ``crs`` coordinates.
        crs: CRS of ``bounds``; defaults to the carrier's CRS.
        keep: ``"inside"`` (default) keeps the box (mask True outside
            it); ``"outside"`` drops the box.

    Examples:
        >>> aoi = BBoxMask(bounds=(1.0, 1.0, 3.0, 3.0))  # doctest: +SKIP
        >>> ApplyMask(mask=aoi)(scene)  # keeps the box  # doctest: +SKIP
    """

    forbid_in_yaml: ClassVar[bool] = False

    def __init__(
        self,
        *,
        bounds: tuple[float, float, float, float],
        crs: str | None = None,
        keep: Keep = "inside",
    ) -> None:
        shapely = optional_root(
            "shapely.geometry.base",
            "vector",
            feature="geoops.mask.BBoxMask",
        )
        self.bounds = tuple(bounds)
        if len(self.bounds) != 4:
            raise ValueError("BBoxMask: `bounds` must contain exactly four values")
        super().__init__(
            geometry=shapely.geometry.box(*self.bounds), crs=crs, keep=keep
        )

    def get_config(self) -> dict[str, Any]:
        return {"bounds": self.bounds, "crs": self.crs, "keep": self.keep}

BufferMask

Bases: Operator

Radially expand True pixels in a mask by a Euclidean buffer.

Wraps :func:geoops.mask.buffer_mask. With unit="pixels" (default) the op is metadata-free and accepts a GeoArray or a plain ndarray, returning the same carrier kind. With unit="meters" the op is geo-dependent: the input must be a georeferenced GeoArray whose transform supplies the ground pixel steps (rotated grids are measured correctly, sheared grids raise ValueError), and radius is measured in CRS units.

Parameters:

Name Type Description Default
radius float

Buffer distance, in pixels or CRS units per unit.

required
unit str

"pixels" (default), "meters", or "meter".

'pixels'

Examples:

>>> BufferMask(radius=2.0)(mask)
Source code in packages/geotoolz-ops/src/geoops/mask/_src/operators.py
class BufferMask(Operator):
    """Radially expand True pixels in a mask by a Euclidean buffer.

    Wraps :func:`geoops.mask.buffer_mask`. With ``unit="pixels"``
    (default) the op is metadata-free and accepts a GeoArray or a
    plain ndarray, returning the same carrier kind. With
    ``unit="meters"`` the op is geo-dependent: the input must be a
    georeferenced ``GeoArray`` whose transform supplies the ground
    pixel steps (rotated grids are measured correctly, sheared grids
    raise ``ValueError``), and ``radius`` is measured in CRS units.

    Args:
        radius: Buffer distance, in pixels or CRS units per ``unit``.
        unit: ``"pixels"`` (default), ``"meters"``, or ``"meter"``.

    Examples:
        >>> BufferMask(radius=2.0)(mask)  # doctest: +SKIP
    """

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

    def spatial_reach(self) -> int | None:
        """Spatial reach in pixels: ⌈radius⌉; None for a radius in map units."""
        return int(np.ceil(self.radius)) if self.unit == "pixels" else None

    def __init__(self, *, radius: float, unit: str = "pixels") -> None:
        self.radius = radius
        self.unit = unit

    def _apply(self, mask: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        if self.unit in {"meter", "meters"}:
            if not isinstance(mask, GeoArray):
                raise ValueError(
                    "BufferMask(unit='meters') requires a GeoArray with a "
                    f"transform; got {type(mask).__name__}."
                )
            pixel_size = ground_pixel_size(mask.transform, "BufferMask")
        else:
            pixel_size = (1.0, 1.0)
        out = buffer_mask(
            np.asarray(mask), self.radius, unit=self.unit, pixel_size=pixel_size
        )
        return wrap_like(mask, out, fill_value=False)

spatial_reach()

Spatial reach in pixels: ⌈radius⌉; None for a radius in map units.

Source code in packages/geotoolz-ops/src/geoops/mask/_src/operators.py
def spatial_reach(self) -> int | None:
    """Spatial reach in pixels: ⌈radius⌉; None for a radius in map units."""
    return int(np.ceil(self.radius)) if self.unit == "pixels" else None

CleanMask

Bases: Operator

Remove small objects, fill small holes, then close the mask.

Convenience composition of :class:RemoveSmallObjects, :class:RemoveSmallHoles, and :class:CloseMask, in that order. Accepts a GeoArray or a plain ndarray and returns the same carrier kind.

Parameters:

Name Type Description Default
min_area_px int

Components smaller than this are removed.

25
max_hole_area_px int

Enclosed holes up to this size are filled.

25
close_iter int

Binary-closing iterations applied last; 0 skips the closing step.

1
Source code in packages/geotoolz-ops/src/geoops/mask/_src/operators.py
class CleanMask(Operator):
    """Remove small objects, fill small holes, then close the mask.

    Convenience composition of :class:`RemoveSmallObjects`,
    :class:`RemoveSmallHoles`, and :class:`CloseMask`, in that order.
    Accepts a GeoArray or a plain ndarray and returns the same carrier
    kind.

    Args:
        min_area_px: Components smaller than this are removed.
        max_hole_area_px: Enclosed holes up to this size are filled.
        close_iter: Binary-closing iterations applied last; ``0`` skips
            the closing step.
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # connected components, then a closing
    coupling: ClassVar[Coupling] = Coupling(couples={"space"}, reach=None)

    def __init__(
        self,
        *,
        min_area_px: int = 25,
        max_hole_area_px: int = 25,
        close_iter: int = 1,
    ) -> None:
        self.min_area_px = min_area_px
        self.max_hole_area_px = max_hole_area_px
        self.close_iter = close_iter

    def _apply(self, mask: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        out = clean_mask(
            np.asarray(mask),
            min_area_px=self.min_area_px,
            max_hole_area_px=self.max_hole_area_px,
            close_iter=self.close_iter,
        )
        return wrap_like(mask, out, fill_value=False)

CloseMask

Bases: Operator

Close (dilate then erode) a boolean mask.

Wraps :func:scipy.ndimage.binary_closing. Useful for filling pin-holes (pepper) inside otherwise solid True regions. Accepts a GeoArray or a plain ndarray and returns the same carrier kind.

Parameters:

Name Type Description Default
iterations int

Number of closing passes. 0 is a no-op copy.

1

Examples:

>>> CloseMask(iterations=1)(mask)
Source code in packages/geotoolz-ops/src/geoops/mask/_src/operators.py
class CloseMask(Operator):
    """Close (dilate then erode) a boolean mask.

    Wraps :func:`scipy.ndimage.binary_closing`. Useful for filling
    pin-holes (pepper) inside otherwise solid True regions. Accepts a
    GeoArray or a plain ndarray and returns the same carrier kind.

    Args:
        iterations: Number of closing passes. ``0`` is a no-op copy.

    Examples:
        >>> CloseMask(iterations=1)(mask)  # doctest: +SKIP
    """

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

    def spatial_reach(self) -> int:
        """Spatial reach in pixels: a 3 x 3 dilation and erosion per iteration."""
        return 2 * self.iterations

    def __init__(self, *, iterations: int = 1) -> None:
        self.iterations = iterations

    def _apply(self, mask: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        out = close_mask(np.asarray(mask), self.iterations)
        return wrap_like(mask, out, fill_value=False)

spatial_reach()

Spatial reach in pixels: a 3 x 3 dilation and erosion per iteration.

Source code in packages/geotoolz-ops/src/geoops/mask/_src/operators.py
def spatial_reach(self) -> int:
    """Spatial reach in pixels: a 3 x 3 dilation and erosion per iteration."""
    return 2 * self.iterations

CombineMasks

Bases: Operator

Combine boolean masks on one pixel grid with or, and or xor.

Called with the masks as positional arguments, op(m1, m2, ...) (GeoArrays or plain ndarrays) -- so it wires straight into a pipekit_ops.Graph as CombineMasks()(Input("a"), Input("b")) -- or with one sequence of them, op([m1, m2]), or one (T, C, H, W) stack whose frames are the masks. Every mask must sit on the first mask's pixel grid (ValueError otherwise, see :func:geoops._src.geo.grid_matches). The output takes its carrier kind -- and, for GeoArrays, its metadata -- from the first mask. Every input must use the package polarity (True = drop), so op="or" drops a pixel that any mask drops. Use :class:InvertMask for the complement.

Parameters:

Name Type Description Default
op str

"or" (default), "and" or "xor".

'or'
Source code in packages/geotoolz-ops/src/geoops/mask/_src/operators.py
class CombineMasks(Operator):
    """Combine boolean masks on one pixel grid with ``or``, ``and`` or ``xor``.

    Called with the masks as positional arguments, ``op(m1, m2, ...)``
    (GeoArrays or plain ndarrays) -- so it wires straight into a
    ``pipekit_ops.Graph`` as ``CombineMasks()(Input("a"), Input("b"))`` -- or
    with one sequence of them, ``op([m1, m2])``, or one ``(T, C, H, W)``
    stack whose frames are the masks. Every mask must sit on the first
    mask's pixel grid (``ValueError`` otherwise, see
    :func:`geoops._src.geo.grid_matches`). The output takes its carrier
    kind -- and, for GeoArrays, its metadata -- from the first mask.
    Every input must use the package polarity (True = drop), so
    ``op="or"`` drops a pixel that *any* mask drops. Use :class:`InvertMask`
    for the complement.

    Args:
        op: ``"or"`` (default), ``"and"`` or ``"xor"``.
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # or / and / xor over the N masks (time is the N-ary axis, OC-Q5)
    coupling: ClassVar[Coupling] = Coupling(
        couples={"time"}, effects={"time": "reduce"}
    )

    def __init__(self, *, op: str = "or") -> None:
        self.op = op

    def _apply(self, *masks: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        masks = gather_inputs(masks, "CombineMasks", split_stack=True)
        for idx, mask in enumerate(masks[1:], start=1):
            require_grid_match(
                masks[0], mask, "CombineMasks", names=("mask 0", f"mask {idx}")
            )
        out = combine_masks([np.asarray(mask) for mask in masks], self.op)
        return wrap_like(masks[0], out, fill_value=False)

CountryMask

Bases: _NaturalEarthMask

Rasterize Natural Earth country polygons selected by ISO A3 code.

Geo-dependent: requires a georeferenced GeoArray input (see :class:PolygonMask). The polygons are loaded on the first call, never in the constructor.

Parameters:

Name Type Description Default
iso_a3 str | Sequence[str]

One ISO A3 country code or a sequence of them (e.g. "ESP" or ("ESP", "PRT")).

required
source str

"natural_earth_10m" (default) downloads and caches the Natural Earth 1:10m admin-0 countries on first use; any other value is a local vector file path with an ISO_A3 column.

'natural_earth_10m'
keep Keep

"inside" (default) keeps the selected countries (mask True elsewhere); "outside" drops them.

'inside'

Raises:

Type Description
ValueError

On the first call, if none of the requested codes are found (codes are checked only once the polygons load).

Source code in packages/geotoolz-ops/src/geoops/mask/_src/operators.py
class CountryMask(_NaturalEarthMask):
    """Rasterize Natural Earth country polygons selected by ISO A3 code.

    Geo-dependent: requires a georeferenced ``GeoArray`` input (see
    :class:`PolygonMask`). The polygons are loaded on the first call,
    never in the constructor.

    Args:
        iso_a3: One ISO A3 country code or a sequence of them (e.g.
            ``"ESP"`` or ``("ESP", "PRT")``).
        source: ``"natural_earth_10m"`` (default) downloads and caches
            the Natural Earth 1:10m admin-0 countries on first use; any
            other value is a local vector file path with an ``ISO_A3``
            column.
        keep: ``"inside"`` (default) keeps the selected countries (mask
            True elsewhere); ``"outside"`` drops them.

    Raises:
        ValueError: On the first call, if none of the requested codes are
            found (codes are checked only once the polygons load).
    """

    def __init__(
        self,
        *,
        iso_a3: str | Sequence[str],
        source: str = "natural_earth_10m",
        keep: Keep = "inside",
    ) -> None:
        self.iso_a3 = (iso_a3,) if isinstance(iso_a3, str) else tuple(iso_a3)
        super().__init__(source=source, keep=keep)

    def _load_geometry(self) -> gpd.GeoDataFrame:
        countries = _load_natural_earth("countries", self.source)
        selected = countries[countries["ISO_A3"].isin(self.iso_a3)]
        if selected.empty:
            raise ValueError(f"CountryMask: no countries found for {list(self.iso_a3)}")
        return selected

    def get_config(self) -> dict[str, Any]:
        iso_a3: str | list[str]
        iso_a3 = self.iso_a3[0] if len(self.iso_a3) == 1 else list(self.iso_a3)
        return {"iso_a3": iso_a3, "source": self.source, "keep": self.keep}

DilateMask

Bases: Operator

Dilate a boolean mask over its trailing spatial axes.

Wraps :func:scipy.ndimage.binary_dilation. The structuring element defaults to a 3x3 box (8-connectivity). Stacks of masks of shape (C, H, W) are processed per channel. Accepts a GeoArray or a plain ndarray and returns the same carrier kind.

Parameters:

Name Type Description Default
iterations int

Number of dilation passes. 0 is a no-op copy.

1
structure ndarray | None

Optional 2-D structuring element.

None

Examples:

>>> DilateMask(iterations=2)(mask)
Source code in packages/geotoolz-ops/src/geoops/mask/_src/operators.py
class DilateMask(Operator):
    """Dilate a boolean mask over its trailing spatial axes.

    Wraps :func:`scipy.ndimage.binary_dilation`. The structuring element
    defaults to a 3x3 box (8-connectivity). Stacks of masks of shape
    ``(C, H, W)`` are processed per channel. Accepts a GeoArray or a
    plain ndarray and returns the same carrier kind.

    Args:
        iterations: Number of dilation passes. ``0`` is a no-op copy.
        structure: Optional 2-D structuring element.

    Examples:
        >>> DilateMask(iterations=2)(mask)  # doctest: +SKIP
    """

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

    def spatial_reach(self) -> int:
        """Spatial reach in pixels: a structuring half-width per iteration."""
        return self.iterations * _structure_half_width(self.structure)

    def __init__(
        self, *, iterations: int = 1, structure: np.ndarray | None = None
    ) -> None:
        self.iterations = iterations
        self.structure = structure

    def _apply(self, mask: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        out = dilate_mask(np.asarray(mask), self.iterations, self.structure)
        return wrap_like(mask, out, fill_value=False)

    def get_config(self) -> dict[str, Any]:
        return _morph_config(self.iterations, self.structure)

spatial_reach()

Spatial reach in pixels: a structuring half-width per iteration.

Source code in packages/geotoolz-ops/src/geoops/mask/_src/operators.py
def spatial_reach(self) -> int:
    """Spatial reach in pixels: a structuring half-width per iteration."""
    return self.iterations * _structure_half_width(self.structure)

DistanceMask

Bases: PolygonMask

Mask pixels by their distance from a geometry (True = drop).

Rasterizes the geometry onto the carrier grid, then buffers it by distance (CRS units, using the carrier's ground pixel steps hypot(a, d) / hypot(b, e) so rotated grids measure true distances; sheared grids raise ValueError; see :func:geoops.mask.distance_mask). Geo-dependent: requires a georeferenced GeoArray input. Like :class:PolygonMask, it returns one boolean (H, W) mask whatever the carrier's rank.

Parameters:

Name Type Description Default
geometry BaseGeometry | GeoDataFrame

Shapely geometry or GeoDataFrame.

required
distance float

Maximum distance from the geometry, in CRS units.

required
keep Keep

"inside" (default) keeps pixels within distance of the geometry (mask True beyond it); "outside" drops the zone within distance.

'inside'
crs str | None

CRS of geometry when it doesn't carry one itself.

None
all_touched bool

Rasterization rule; see :class:PolygonMask. Default True so thin geometries are not lost.

True
Source code in packages/geotoolz-ops/src/geoops/mask/_src/operators.py
class DistanceMask(PolygonMask):
    """Mask pixels by their distance from a geometry (True = drop).

    Rasterizes the geometry onto the carrier grid, then buffers it by
    ``distance`` (CRS units, using the carrier's ground pixel steps
    ``hypot(a, d)`` / ``hypot(b, e)`` so rotated grids measure true
    distances; sheared grids raise ``ValueError``; see
    :func:`geoops.mask.distance_mask`). Geo-dependent: requires a
    georeferenced ``GeoArray`` input. Like :class:`PolygonMask`, it
    returns one boolean ``(H, W)`` mask whatever the carrier's rank.

    Args:
        geometry: Shapely geometry or ``GeoDataFrame``.
        distance: Maximum distance from the geometry, in CRS units.
        keep: ``"inside"`` (default) keeps pixels within ``distance`` of
            the geometry (mask True beyond it); ``"outside"`` drops the
            zone within ``distance``.
        crs: CRS of ``geometry`` when it doesn't carry one itself.
        all_touched: Rasterization rule; see :class:`PolygonMask`.
            Default True so thin geometries are not lost.
    """

    def __init__(
        self,
        *,
        geometry: shapely.geometry.base.BaseGeometry | gpd.GeoDataFrame,
        distance: float,
        keep: Keep = "inside",
        crs: str | None = None,
        all_touched: bool = True,
    ) -> None:
        self.distance = distance
        super().__init__(geometry=geometry, crs=crs, all_touched=all_touched, keep=keep)

    def _apply(self, gt: GeoArray) -> GeoArray:
        burned = _rasterize_geometry_like(
            self.geometry,
            gt,
            crs=self.crs,
            all_touched=self.all_touched,
        )
        mask = distance_mask(
            burned,
            self.distance,
            keep=self.keep,
            pixel_size=ground_pixel_size(gt.transform, type(self).__name__),
        )
        return wrap_like(gt, mask, fill_value=False)

    def get_config(self) -> dict[str, Any]:
        return {
            "geometry": _geometry_config(self.geometry),
            "distance": self.distance,
            "keep": self.keep,
            "crs": self.crs,
            "all_touched": self.all_touched,
        }

ErodeMask

Bases: Operator

Erode a boolean mask over its trailing spatial axes.

Wraps :func:scipy.ndimage.binary_erosion; see :class:DilateMask for the structuring-element and carrier conventions.

Parameters:

Name Type Description Default
iterations int

Number of erosion passes. 0 is a no-op copy.

1
structure ndarray | None

Optional 2-D structuring element.

None

Examples:

>>> ErodeMask(iterations=1)(mask)
Source code in packages/geotoolz-ops/src/geoops/mask/_src/operators.py
class ErodeMask(Operator):
    """Erode a boolean mask over its trailing spatial axes.

    Wraps :func:`scipy.ndimage.binary_erosion`; see :class:`DilateMask`
    for the structuring-element and carrier conventions.

    Args:
        iterations: Number of erosion passes. ``0`` is a no-op copy.
        structure: Optional 2-D structuring element.

    Examples:
        >>> ErodeMask(iterations=1)(mask)  # doctest: +SKIP
    """

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

    def spatial_reach(self) -> int:
        """Spatial reach in pixels: a structuring half-width per iteration."""
        return self.iterations * _structure_half_width(self.structure)

    def __init__(
        self, *, iterations: int = 1, structure: np.ndarray | None = None
    ) -> None:
        self.iterations = iterations
        self.structure = structure

    def _apply(self, mask: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        out = erode_mask(np.asarray(mask), self.iterations, self.structure)
        return wrap_like(mask, out, fill_value=False)

    def get_config(self) -> dict[str, Any]:
        return _morph_config(self.iterations, self.structure)

spatial_reach()

Spatial reach in pixels: a structuring half-width per iteration.

Source code in packages/geotoolz-ops/src/geoops/mask/_src/operators.py
def spatial_reach(self) -> int:
    """Spatial reach in pixels: a structuring half-width per iteration."""
    return self.iterations * _structure_half_width(self.structure)

InvertMask

Bases: Operator

Invert a boolean mask element-wise.

The one complement operator (wraps :func:geoops.mask.invert_mask): turns a keep-polarity mask (True = keep, e.g. valid_mask()) into the package's drop polarity, and back. Accepts a GeoArray or a plain ndarray and returns the same carrier kind. Takes no parameters.

Source code in packages/geotoolz-ops/src/geoops/mask/_src/operators.py
class InvertMask(Operator):
    """Invert a boolean mask element-wise.

    The one complement operator (wraps :func:`geoops.mask.invert_mask`):
    turns a keep-polarity mask (True = keep, e.g. ``valid_mask()``) into
    the package's drop polarity, and back. Accepts a GeoArray or a
    plain ndarray and returns the same carrier kind. Takes no parameters.
    """

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

    def _apply(self, mask: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        out = invert_mask(np.asarray(mask))
        return wrap_like(mask, out, fill_value=False)

LandMask

Bases: _NaturalEarthMask

Rasterize Natural Earth land polygons into a boolean mask.

Geo-dependent: requires a georeferenced GeoArray input (see :class:PolygonMask). The polygons are loaded on the first call, never in the constructor.

Parameters:

Name Type Description Default
source str

"natural_earth_10m" (default) downloads and caches the Natural Earth 1:10m land polygons on first use; any other value is a local vector file path passed to geopandas.read_file.

'natural_earth_10m'
keep Keep

"inside" (default) keeps land pixels (mask True elsewhere); "outside" drops them.

'inside'
Source code in packages/geotoolz-ops/src/geoops/mask/_src/operators.py
class LandMask(_NaturalEarthMask):
    """Rasterize Natural Earth land polygons into a boolean mask.

    Geo-dependent: requires a georeferenced ``GeoArray`` input (see
    :class:`PolygonMask`). The polygons are loaded on the first call,
    never in the constructor.

    Args:
        source: ``"natural_earth_10m"`` (default) downloads and caches
            the Natural Earth 1:10m land polygons on first use; any other
            value is a local vector file path passed to
            ``geopandas.read_file``.
        keep: ``"inside"`` (default) keeps land pixels (mask True
            elsewhere); ``"outside"`` drops them.
    """

    def __init__(
        self, *, source: str = "natural_earth_10m", keep: Keep = "inside"
    ) -> None:
        super().__init__(source=source, keep=keep)

    def _load_geometry(self) -> gpd.GeoDataFrame:
        return _load_natural_earth("land", self.source)

    def get_config(self) -> dict[str, Any]:
        return {"source": self.source, "keep": self.keep}

OceanMask

Bases: _NaturalEarthMask

Rasterize Natural Earth ocean polygons into a boolean mask.

Geo-dependent: requires a georeferenced GeoArray input (see :class:PolygonMask). The polygons are loaded on the first call, never in the constructor.

Parameters:

Name Type Description Default
source str

"natural_earth_10m" (default) downloads and caches the Natural Earth 1:10m ocean polygons on first use; any other value is a local vector file path passed to geopandas.read_file.

'natural_earth_10m'
keep Keep

"inside" (default) keeps ocean pixels (mask True elsewhere); "outside" drops them.

'inside'
Source code in packages/geotoolz-ops/src/geoops/mask/_src/operators.py
class OceanMask(_NaturalEarthMask):
    """Rasterize Natural Earth ocean polygons into a boolean mask.

    Geo-dependent: requires a georeferenced ``GeoArray`` input (see
    :class:`PolygonMask`). The polygons are loaded on the first call,
    never in the constructor.

    Args:
        source: ``"natural_earth_10m"`` (default) downloads and caches
            the Natural Earth 1:10m ocean polygons on first use; any
            other value is a local vector file path passed to
            ``geopandas.read_file``.
        keep: ``"inside"`` (default) keeps ocean pixels (mask True
            elsewhere); ``"outside"`` drops them.
    """

    def __init__(
        self, *, source: str = "natural_earth_10m", keep: Keep = "inside"
    ) -> None:
        super().__init__(source=source, keep=keep)

    def _load_geometry(self) -> gpd.GeoDataFrame:
        return _load_natural_earth("ocean", self.source)

    def get_config(self) -> dict[str, Any]:
        return {"source": self.source, "keep": self.keep}

OpenMask

Bases: Operator

Open (erode then dilate) a boolean mask.

Wraps :func:scipy.ndimage.binary_opening. Useful for removing isolated True pixels (salt) while preserving large True components. Accepts a GeoArray or a plain ndarray and returns the same carrier kind.

Parameters:

Name Type Description Default
iterations int

Number of opening passes. 0 is a no-op copy.

1

Examples:

>>> OpenMask(iterations=1)(mask)
Source code in packages/geotoolz-ops/src/geoops/mask/_src/operators.py
class OpenMask(Operator):
    """Open (erode then dilate) a boolean mask.

    Wraps :func:`scipy.ndimage.binary_opening`. Useful for removing
    isolated True pixels (salt) while preserving large True components.
    Accepts a GeoArray or a plain ndarray and returns the same carrier
    kind.

    Args:
        iterations: Number of opening passes. ``0`` is a no-op copy.

    Examples:
        >>> OpenMask(iterations=1)(mask)  # doctest: +SKIP
    """

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

    def spatial_reach(self) -> int:
        """Spatial reach in pixels: a 3 x 3 erosion and dilation per iteration."""
        return 2 * self.iterations

    def __init__(self, *, iterations: int = 1) -> None:
        self.iterations = iterations

    def _apply(self, mask: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        out = open_mask(np.asarray(mask), self.iterations)
        return wrap_like(mask, out, fill_value=False)

spatial_reach()

Spatial reach in pixels: a 3 x 3 erosion and dilation per iteration.

Source code in packages/geotoolz-ops/src/geoops/mask/_src/operators.py
def spatial_reach(self) -> int:
    """Spatial reach in pixels: a 3 x 3 erosion and dilation per iteration."""
    return 2 * self.iterations

PolygonMask

Bases: Operator

Rasterize a shapely geometry or GeoDataFrame into a boolean mask.

Follows the package polarity (True = drop): with the default keep="inside" the mask is True outside the geometry, so ApplyMask(mask=PolygonMask(...)) keeps the area of interest.

Geo-dependent: rasterization needs the carrier's transform/CRS, so the input must be a georeferenced GeoArray. The mask matches the carrier's spatial grid and is returned as a boolean (H, W) GeoArray with fill_value=False whatever the carrier's rank: every band and every frame of a (T, C, H, W) stack share the same grid, so one mask serves them all (it broadcasts in :class:ApplyMask).

Parameters:

Name Type Description Default
geometry BaseGeometry | GeoDataFrame

Shapely geometry or GeoDataFrame to burn in.

required
crs str | None

CRS of geometry when it doesn't carry one itself (required for a CRS-less GeoDataFrame).

None
all_touched bool

Burn every pixel touched by the geometry instead of only pixels whose center is inside.

False
keep Keep

"inside" (default) keeps the geometry's interior (mask True outside it); "outside" keeps the exterior (mask True inside the geometry).

'inside'

Examples:

>>> PolygonMask(geometry=box(1.0, 1.0, 3.0, 3.0))(scene)
Source code in packages/geotoolz-ops/src/geoops/mask/_src/operators.py
class PolygonMask(Operator):
    """Rasterize a shapely geometry or GeoDataFrame into a boolean mask.

    Follows the package polarity (True = drop): with the default
    ``keep="inside"`` the mask is True *outside* the geometry, so
    ``ApplyMask(mask=PolygonMask(...))`` keeps the area of interest.

    Geo-dependent: rasterization needs the carrier's transform/CRS, so
    the input must be a georeferenced ``GeoArray``. The mask matches
    the carrier's spatial grid and is returned as a boolean ``(H, W)``
    GeoArray with ``fill_value=False`` whatever the carrier's
    rank: every band and every frame of a ``(T, C, H, W)`` stack share
    the same grid, so one mask serves them all (it broadcasts in
    :class:`ApplyMask`).

    Args:
        geometry: Shapely geometry or ``GeoDataFrame`` to burn in.
        crs: CRS of ``geometry`` when it doesn't carry one itself
            (required for a CRS-less GeoDataFrame).
        all_touched: Burn every pixel touched by the geometry instead
            of only pixels whose center is inside.
        keep: ``"inside"`` (default) keeps the geometry's interior (mask
            True outside it); ``"outside"`` keeps the exterior (mask True
            inside the geometry).

    Examples:
        >>> PolygonMask(geometry=box(1.0, 1.0, 3.0, 3.0))(scene)  # doctest: +SKIP
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # depends only on the grid and the geometry
    coupling: ClassVar[Coupling] = Coupling(reads_values=False)

    forbid_in_yaml: ClassVar[bool] = True

    def __init__(
        self,
        *,
        geometry: shapely.geometry.base.BaseGeometry | gpd.GeoDataFrame,
        crs: str | None = None,
        all_touched: bool = False,
        keep: Keep = "inside",
    ) -> None:
        self.geometry = geometry
        self.crs = crs
        self.all_touched = all_touched
        self.keep = _check_keep(keep, type(self).__name__)

    def _apply(self, gt: GeoArray) -> GeoArray:
        burned = _rasterize_geometry_like(
            self.geometry,
            gt,
            crs=self.crs,
            all_touched=self.all_touched,
        )
        mask = _drop_polarity(burned, self.keep, type(self).__name__)
        return wrap_like(gt, mask, fill_value=False)

    def get_config(self) -> dict[str, Any]:
        return {
            "geometry": _geometry_config(self.geometry),
            "crs": self.crs,
            "all_touched": self.all_touched,
            "keep": self.keep,
        }

RemoveSmallHoles

Bases: Operator

Fill enclosed False components up to max_hole_area_px pixels.

Wraps :func:geoops.mask.remove_small_holes; holes touching the image border are never filled. Accepts a GeoArray or a plain ndarray and returns the same carrier kind.

Parameters:

Name Type Description Default
max_hole_area_px int

Maximum hole area, in pixels, to fill.

required
Source code in packages/geotoolz-ops/src/geoops/mask/_src/operators.py
class RemoveSmallHoles(Operator):
    """Fill enclosed False components up to ``max_hole_area_px`` pixels.

    Wraps :func:`geoops.mask.remove_small_holes`; holes touching the
    image border are never filled. Accepts a GeoArray or a plain
    ndarray and returns the same carrier kind.

    Args:
        max_hole_area_px: Maximum hole area, in pixels, to fill.
    """

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

    def __init__(self, *, max_hole_area_px: int) -> None:
        self.max_hole_area_px = max_hole_area_px

    def _apply(self, mask: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        out = remove_small_holes(np.asarray(mask), self.max_hole_area_px)
        return wrap_like(mask, out, fill_value=False)

RemoveSmallObjects

Bases: Operator

Remove connected True components smaller than min_area_px pixels.

Wraps :func:geoops.mask.remove_small_objects (4-connectivity). Accepts a GeoArray or a plain ndarray and returns the same carrier kind.

Parameters:

Name Type Description Default
min_area_px int

Minimum component area, in pixels, to keep.

required
Source code in packages/geotoolz-ops/src/geoops/mask/_src/operators.py
class RemoveSmallObjects(Operator):
    """Remove connected True components smaller than ``min_area_px`` pixels.

    Wraps :func:`geoops.mask.remove_small_objects` (4-connectivity).
    Accepts a GeoArray or a plain ndarray and returns the same carrier
    kind.

    Args:
        min_area_px: Minimum component area, in pixels, to keep.
    """

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

    def __init__(self, *, min_area_px: int) -> None:
        self.min_area_px = min_area_px

    def _apply(self, mask: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        out = remove_small_objects(np.asarray(mask), self.min_area_px)
        return wrap_like(mask, out, fill_value=False)

SlopeMask

Bases: Operator

Build a boolean mask from DEM slope bounds in degrees.

Slope is computed from the DEM with central differences scaled by the DEM's ground pixel steps (hypot(a, d) / hypot(b, e), so rotated grids measure true distances; sheared grids are rejected). The DEM must be in a projected CRS: a geographic DEM's pixel size is in degrees and raises ValueError. Follows the package polarity (True = drop): with the default keep="inside" the mask is True where the slope (degrees) falls outside the requested interval.

Called as op(scene, dem). Geo-dependent on the DEM side: dem must be a single-band georeferenced GeoArray (its transform supplies the pixel size, in the same units as the elevation values) on the scene's pixel grid. The scene may be a GeoArray or plain ndarray; when both are georeferenced, their transform / CRS must match (ValueError otherwise).

Parameters:

Name Type Description Default
min_slope_deg float | None

Inclusive lower bound, degrees.

None
max_slope_deg float | None

Inclusive upper bound, degrees.

None
keep Keep

"inside" (default) keeps cells inside the interval; "outside" keeps cells outside it.

'inside'

Examples:

>>> SlopeMask(max_slope_deg=10.0)(scene, dem)
Source code in packages/geotoolz-ops/src/geoops/mask/_src/operators.py
class SlopeMask(Operator):
    """Build a boolean mask from DEM slope bounds in degrees.

    Slope is computed from the DEM with central differences scaled by
    the DEM's ground pixel steps (``hypot(a, d)`` / ``hypot(b, e)``, so
    rotated grids measure true distances; sheared grids are rejected).
    The DEM must be in a projected CRS: a geographic DEM's pixel size is
    in degrees and raises ``ValueError``. Follows the package polarity
    (True = drop): with the default ``keep="inside"`` the mask is True
    where the slope (degrees) falls *outside* the requested interval.

    Called as ``op(scene, dem)``. Geo-dependent on the DEM side: ``dem``
    must be a single-band georeferenced ``GeoArray`` (its transform
    supplies the pixel size, in the same units as the elevation values)
    on the scene's pixel grid. The scene may be a GeoArray or plain
    ndarray; when both are georeferenced, their transform / CRS must
    match (``ValueError`` otherwise).

    Args:
        min_slope_deg: Inclusive lower bound, degrees.
        max_slope_deg: Inclusive upper bound, degrees.
        keep: ``"inside"`` (default) keeps cells inside the interval;
            ``"outside"`` keeps cells outside it.

    Examples:
        >>> SlopeMask(max_slope_deg=10.0)(scene, dem)  # doctest: +SKIP
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # slope from the DEM's 3 x 3 neighbourhood; the input gives only the grid
    coupling: ClassVar[Coupling] = Coupling(
        couples={"space"}, reach=1, reads_values=False
    )

    def __init__(
        self,
        *,
        min_slope_deg: float | None = None,
        max_slope_deg: float | None = None,
        keep: Keep = "inside",
    ) -> None:
        self.min_slope_deg = min_slope_deg
        self.max_slope_deg = max_slope_deg
        self.keep = _check_keep(keep, "SlopeMask")

    def _apply(self, gt: GeoArray | np.ndarray, dem: GeoArray) -> GeoArray | np.ndarray:
        dem = require_geoarray(dem, "SlopeMask", arg="dem")
        require_projected_crs(dem, "SlopeMask", what="slopes", metres=False)
        require_grid_match(gt, dem, "SlopeMask", names=("scene", "dem"))
        mask = slope_mask(
            np.asarray(dem),
            ground_pixel_size(dem.transform, "SlopeMask"),
            min_slope_deg=self.min_slope_deg,
            max_slope_deg=self.max_slope_deg,
            keep=self.keep,
        )
        return wrap_like(gt, mask, fill_value=False)

altitude_mask(dem, *, min_elev=None, max_elev=None, keep='inside')

Mask DEM cells by an elevation interval (True = drop).

Parameters:

Name Type Description Default
dem Float[ndarray, 'h w'] | Float[ndarray, '1 h w']

Single-band elevation raster, (H, W) or (1, H, W).

required
min_elev float | None

Inclusive lower elevation bound (DEM units). None leaves the interval open below.

None
max_elev float | None

Inclusive upper elevation bound. None leaves the interval open above.

None
keep Keep

"inside" (default) keeps cells inside [min_elev, max_elev] — the mask is True outside it; "outside" keeps cells outside the interval.

'inside'

Returns:

Type Description
Bool[ndarray, 'h w']

Boolean (H, W) mask, True where the cell should be dropped.

Raises:

Type Description
ValueError

If both bounds are None, keep is unknown, or dem is not a single-band map.

Source code in packages/geotoolz-ops/src/geoops/mask/_src/array.py
def altitude_mask(
    dem: Float[np.ndarray, "h w"] | Float[np.ndarray, "1 h w"],
    *,
    min_elev: float | None = None,
    max_elev: float | None = None,
    keep: Keep = "inside",
) -> Bool[np.ndarray, "h w"]:
    """Mask DEM cells by an elevation interval (True = drop).

    Args:
        dem: Single-band elevation raster, ``(H, W)`` or ``(1, H, W)``.
        min_elev: Inclusive lower elevation bound (DEM units). ``None``
            leaves the interval open below.
        max_elev: Inclusive upper elevation bound. ``None`` leaves the
            interval open above.
        keep: ``"inside"`` (default) keeps cells inside
            ``[min_elev, max_elev]`` — the mask is True outside it;
            ``"outside"`` keeps cells outside the interval.

    Returns:
        Boolean ``(H, W)`` mask, True where the cell should be dropped.

    Raises:
        ValueError: If both bounds are ``None``, ``keep`` is unknown, or
            ``dem`` is not a single-band map.
    """
    if min_elev is None and max_elev is None:
        raise ValueError("altitude_mask: at least one elevation bound is required")
    arr = single_band(dem, name="altitude_mask")
    mask = np.ones(arr.shape, dtype=bool)
    if min_elev is not None:
        mask &= arr >= min_elev
    if max_elev is not None:
        mask &= arr <= max_elev
    return _drop_polarity(mask, keep, "altitude_mask")

apply_mask(arr, mask, fill_value=np.nan)

Apply a boolean mask to a multi-band array, filling masked pixels.

The mask follows the package polarity: True where pixels should be masked out (dropped) — see "Mask polarity" in docs/operators/concepts.md. The result is arr with fill_value substituted wherever mask is True. Flip a keep-polarity mask with :func:invert_mask first.

The mask broadcasts against the spatial trailing axes of arr, so a (H, W) mask applies to every band of a (C, H, W) raster automatically.

Parameters:

Name Type Description Default
arr Shaped[ndarray, '*dims']

Input array, any shape.

required
mask Bool[ndarray, '*mask_dims']

Boolean mask. Must broadcast against the spatial (trailing two) axes of arr.

required
fill_value float

Value substituted where the mask says "drop". Default np.nan (the right choice for float arrays; switch to a sentinel like 0 for integer inputs).

nan

Returns:

Type Description
Shaped[ndarray, '*dims']

Array of the same shape as arr, masked pixels replaced

Shaped[ndarray, '*dims']

with fill_value.

Source code in packages/geotoolz-ops/src/geoops/mask/_src/array.py
def apply_mask(
    arr: Shaped[np.ndarray, "*dims"],
    mask: Bool[np.ndarray, "*mask_dims"],
    fill_value: float = np.nan,
) -> Shaped[np.ndarray, "*dims"]:
    """Apply a boolean mask to a multi-band array, filling masked pixels.

    The mask follows the package polarity: True where pixels should be
    *masked out* (dropped) — see "Mask polarity" in ``docs/operators/concepts.md``.
    The result is ``arr`` with ``fill_value`` substituted wherever
    ``mask`` is True. Flip a keep-polarity mask with :func:`invert_mask`
    first.

    The mask broadcasts against the spatial trailing axes of ``arr``,
    so a ``(H, W)`` mask applies to every band of a ``(C, H, W)``
    raster automatically.

    Args:
        arr: Input array, any shape.
        mask: Boolean mask. Must broadcast against the spatial
            (trailing two) axes of ``arr``.
        fill_value: Value substituted where the mask says "drop".
            Default ``np.nan`` (the right choice for float arrays;
            switch to a sentinel like ``0`` for integer inputs).

    Returns:
        Array of the same shape as ``arr``, masked pixels replaced
        with ``fill_value``.
    """
    bool_mask = np.asarray(mask, dtype=bool)
    # `np.where` upcasts to the wider dtype of (fill_value, arr). For
    # floating arrays we want to preserve `arr.dtype` — otherwise
    # `fill_value=np.nan` (float64) silently doubles memory on float32
    # inputs and undoes any upstream `ToFloat32()` stage. Cast the fill
    # to arr's dtype when arr is floating; integer arrays keep numpy's
    # native promotion (so `fill_value=np.nan` on int input still
    # upcasts, which is the only sensible behaviour).
    if np.issubdtype(arr.dtype, np.floating):
        fill_typed = np.asarray(fill_value, dtype=arr.dtype)
        return np.where(bool_mask, fill_typed, arr)
    return np.where(bool_mask, fill_value, arr)

buffer_mask(mask, radius, *, unit='pixels', pixel_size=(1.0, 1.0))

Radially expand True pixels by a Euclidean-distance buffer.

A pixel is True in the output when its Euclidean distance to the nearest originally-True pixel is at most radius (so the original True pixels are always kept). Each leading (batch / band) slice is buffered independently.

Unit contract:

  • unit="pixels" (default): radius is measured in pixels on the unit grid — every pixel is treated as 1 x 1 and pixel_size is ignored.
  • unit="meters" (or "meter"): radius is measured in the same linear units as pixel_size (metres for a projected CRS). pixel_size must then be the per-axis pixel extent (row_height, col_width) — i.e. (abs(yres), abs(xres)) from the geotransform — and is passed as the sampling of the distance transform so anisotropic pixels buffer correctly.

Parameters:

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

Boolean mask, at least 2-D; trailing axes are (H, W).

required
radius float

Buffer distance, in the units selected by unit. 0 returns a copy of the input.

required
unit str

"pixels", "meters", or "meter".

'pixels'
pixel_size tuple[float, float]

(row_height, col_width) pixel extent in CRS units; only used when unit is metres. Default (1.0, 1.0).

(1.0, 1.0)

Returns:

Type Description
Bool[ndarray, '*batch h w']

The buffered boolean mask, same shape as mask.

Raises:

Type Description
ValueError

If radius is negative, unit is unknown, or mask has fewer than two dimensions.

Source code in packages/geotoolz-ops/src/geoops/mask/_src/array.py
def buffer_mask(
    mask: Bool[np.ndarray, "*batch h w"],
    radius: float,
    *,
    unit: str = "pixels",
    pixel_size: tuple[float, float] = (1.0, 1.0),
) -> Bool[np.ndarray, "*batch h w"]:
    """Radially expand True pixels by a Euclidean-distance buffer.

    A pixel is True in the output when its Euclidean distance to the
    nearest originally-True pixel is at most ``radius`` (so the original
    True pixels are always kept). Each leading (batch / band) slice is
    buffered independently.

    Unit contract:

    - ``unit="pixels"`` (default): ``radius`` is measured in pixels on
      the unit grid — every pixel is treated as 1 x 1 and ``pixel_size``
      is **ignored**.
    - ``unit="meters"`` (or ``"meter"``): ``radius`` is measured in the
      same linear units as ``pixel_size`` (metres for a projected CRS).
      ``pixel_size`` must then be the per-axis pixel extent
      ``(row_height, col_width)`` — i.e. ``(abs(yres), abs(xres))`` from
      the geotransform — and is passed as the ``sampling`` of the
      distance transform so anisotropic pixels buffer correctly.

    Args:
        mask: Boolean mask, at least 2-D; trailing axes are ``(H, W)``.
        radius: Buffer distance, in the units selected by ``unit``.
            ``0`` returns a copy of the input.
        unit: ``"pixels"``, ``"meters"``, or ``"meter"``.
        pixel_size: ``(row_height, col_width)`` pixel extent in CRS
            units; only used when ``unit`` is metres. Default
            ``(1.0, 1.0)``.

    Returns:
        The buffered boolean mask, same shape as ``mask``.

    Raises:
        ValueError: If ``radius`` is negative, ``unit`` is unknown, or
            ``mask`` has fewer than two dimensions.
    """
    if radius < 0:
        raise ValueError("buffer_mask: `radius` must be non-negative")
    if unit not in {"pixels", "meters", "meter"}:
        raise ValueError("buffer_mask: `unit` must be 'pixels', 'meter', or 'meters'")
    if radius == 0:
        return np.asarray(mask, dtype=bool).copy()

    sampling = (1.0, 1.0) if unit == "pixels" else pixel_size
    return _apply_spatial(mask, _buffer_2d, radius=radius, sampling=sampling)

clean_mask(mask, *, min_area_px=25, max_hole_area_px=25, close_iter=1)

Remove small objects, fill small holes, then close the mask.

Convenience composition of :func:remove_small_objects, :func:remove_small_holes, and :func:close_mask, in that order.

Parameters:

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

Boolean mask, at least 2-D; trailing axes are (H, W).

required
min_area_px int

Components smaller than this many pixels are removed.

25
max_hole_area_px int

Enclosed holes up to this many pixels are filled.

25
close_iter int

Binary-closing iterations applied last. 0 skips the closing step.

1

Returns:

Type Description
Bool[ndarray, '*batch h w']

The cleaned boolean mask, same shape as mask.

Raises:

Type Description
ValueError

If any size/iteration argument is negative or mask has fewer than two dimensions.

Source code in packages/geotoolz-ops/src/geoops/mask/_src/array.py
def clean_mask(
    mask: Bool[np.ndarray, "*batch h w"],
    *,
    min_area_px: int = 25,
    max_hole_area_px: int = 25,
    close_iter: int = 1,
) -> Bool[np.ndarray, "*batch h w"]:
    """Remove small objects, fill small holes, then close the mask.

    Convenience composition of :func:`remove_small_objects`,
    :func:`remove_small_holes`, and :func:`close_mask`, in that order.

    Args:
        mask: Boolean mask, at least 2-D; trailing axes are ``(H, W)``.
        min_area_px: Components smaller than this many pixels are
            removed.
        max_hole_area_px: Enclosed holes up to this many pixels are filled.
        close_iter: Binary-closing iterations applied last. ``0`` skips
            the closing step.

    Returns:
        The cleaned boolean mask, same shape as ``mask``.

    Raises:
        ValueError: If any size/iteration argument is negative or
            ``mask`` has fewer than two dimensions.
    """
    out = remove_small_objects(mask, min_area_px)
    out = remove_small_holes(out, max_hole_area_px)
    return close_mask(out, close_iter)

clear_natural_earth_cache()

Release the in-process Natural Earth GeoDataFrames.

LandMask / OceanMask / CountryMask share one process-lifetime cache keyed on (kind, source), so each layer is read at most once per session. Call this to free that memory, or to re-read a local source file that changed on disk. Mask instances that already loaded their polygons keep them; the on-disk download cache is untouched.

Source code in packages/geotoolz-ops/src/geoops/mask/_src/operators.py
def clear_natural_earth_cache() -> None:
    """Release the in-process Natural Earth GeoDataFrames.

    `LandMask` / `OceanMask` / `CountryMask` share one process-lifetime
    cache keyed on ``(kind, source)``, so each layer is read at most once
    per session. Call this to free that memory, or to re-read a local
    ``source`` file that changed on disk. Mask instances that already
    loaded their polygons keep them; the on-disk download cache is
    untouched.
    """
    _load_natural_earth.cache_clear()

close_mask(mask, iterations=1)

Apply binary closing (dilation then erosion) over the spatial axes.

Wraps :func:scipy.ndimage.binary_closing with a 3x3 box structuring element. Fills pin-holes (pepper) inside otherwise solid True regions.

Parameters:

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

Boolean mask, at least 2-D; trailing axes are (H, W).

required
iterations int

Number of closing passes. 0 returns a copy.

1

Returns:

Type Description
Bool[ndarray, '*batch h w']

The closed boolean mask, same shape as mask.

Raises:

Type Description
ValueError

If iterations is negative or mask has fewer than two dimensions.

Source code in packages/geotoolz-ops/src/geoops/mask/_src/array.py
def close_mask(
    mask: Bool[np.ndarray, "*batch h w"], iterations: int = 1
) -> Bool[np.ndarray, "*batch h w"]:
    """Apply binary closing (dilation then erosion) over the spatial axes.

    Wraps :func:`scipy.ndimage.binary_closing` with a 3x3 box structuring
    element. Fills pin-holes (pepper) inside otherwise solid True regions.

    Args:
        mask: Boolean mask, at least 2-D; trailing axes are ``(H, W)``.
        iterations: Number of closing passes. ``0`` returns a copy.

    Returns:
        The closed boolean mask, same shape as ``mask``.

    Raises:
        ValueError: If ``iterations`` is negative or ``mask`` has fewer
            than two dimensions.
    """
    return _apply_binary_morphology(mask, ndi.binary_closing, iterations=iterations)

combine_masks(masks, op='or')

Combine boolean masks element-wise with an n-ary logical operator.

All masks must have the same shape — they are not broadcast (a (H, W) mask cannot be combined with a (C, H, W) stack; index or np.broadcast_to it first). Non-boolean inputs are coerced with np.asarray(mask, dtype=bool). Use :func:invert_mask for the unary complement.

Parameters:

Name Type Description Default
masks Sequence[Bool[ndarray, '*batch h w']]

Non-empty sequence of equally shaped boolean masks.

required
op str

One of "or", "and", "xor" (reductions over the sequence). Case-insensitive.

'or'

Returns:

Type Description
Bool[ndarray, '*batch h w']

The combined boolean mask.

Raises:

Type Description
ValueError

If masks is empty, the shapes differ, or op is unknown.

Source code in packages/geotoolz-ops/src/geoops/mask/_src/array.py
def combine_masks(
    masks: Sequence[Bool[np.ndarray, "*batch h w"]], op: str = "or"
) -> Bool[np.ndarray, "*batch h w"]:
    """Combine boolean masks element-wise with an n-ary logical operator.

    All masks must have the *same* shape — they are not broadcast (a
    ``(H, W)`` mask cannot be combined with a ``(C, H, W)`` stack; index
    or ``np.broadcast_to`` it first). Non-boolean inputs are coerced with
    ``np.asarray(mask, dtype=bool)``. Use :func:`invert_mask` for the
    unary complement.

    Args:
        masks: Non-empty sequence of equally shaped boolean masks.
        op: One of ``"or"``, ``"and"``, ``"xor"`` (reductions over the
            sequence). Case-insensitive.

    Returns:
        The combined boolean mask.

    Raises:
        ValueError: If ``masks`` is empty, the shapes differ, or ``op``
            is unknown.
    """
    if len(masks) == 0:
        raise ValueError("combine_masks: `masks` must not be empty")

    bool_masks = [np.asarray(mask, dtype=bool) for mask in masks]
    shapes = {mask.shape for mask in bool_masks}
    if len(shapes) > 1:
        raise ValueError(
            f"combine_masks: all masks must share one shape; got {sorted(shapes)}"
        )
    reducers = {
        "or": np.logical_or,
        "and": np.logical_and,
        "xor": np.logical_xor,
    }
    try:
        reducer = reducers[op.lower()]
    except KeyError:
        raise ValueError(
            "combine_masks: `op` must be one of 'or', 'and', 'xor'"
        ) from None
    return reducer.reduce(bool_masks)

dilate_mask(mask, iterations=1, structure=None)

Dilate a mask over its trailing two (spatial) axes.

Wraps :func:scipy.ndimage.binary_dilation. Leading (batch / band) axes are processed independently, slice by slice.

Parameters:

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

Boolean mask, at least 2-D; trailing axes are (H, W).

required
iterations int

Number of dilation passes. 0 returns a copy.

1
structure Bool[ndarray, 'sh sw'] | None

2-D structuring element. Defaults to a 3x3 box (8-connectivity).

None

Returns:

Type Description
Bool[ndarray, '*batch h w']

The dilated boolean mask, same shape as mask.

Raises:

Type Description
ValueError

If iterations is negative, structure is not 2-D, or mask has fewer than two dimensions.

Source code in packages/geotoolz-ops/src/geoops/mask/_src/array.py
def dilate_mask(
    mask: Bool[np.ndarray, "*batch h w"],
    iterations: int = 1,
    structure: Bool[np.ndarray, "sh sw"] | None = None,
) -> Bool[np.ndarray, "*batch h w"]:
    """Dilate a mask over its trailing two (spatial) axes.

    Wraps :func:`scipy.ndimage.binary_dilation`. Leading (batch / band)
    axes are processed independently, slice by slice.

    Args:
        mask: Boolean mask, at least 2-D; trailing axes are ``(H, W)``.
        iterations: Number of dilation passes. ``0`` returns a copy.
        structure: 2-D structuring element. Defaults to a 3x3 box
            (8-connectivity).

    Returns:
        The dilated boolean mask, same shape as ``mask``.

    Raises:
        ValueError: If ``iterations`` is negative, ``structure`` is not
            2-D, or ``mask`` has fewer than two dimensions.
    """
    return _apply_binary_morphology(
        mask, ndi.binary_dilation, iterations=iterations, structure=structure
    )

distance_mask(geometry_mask, distance, *, keep='inside', pixel_size=(1.0, 1.0))

Mask pixels by their distance to an already-rasterized geometry.

The zone within distance of the geometry is :func:buffer_mask of geometry_mask in pixel_size units — leave the default (1.0, 1.0) for pixel units, or pass (abs(yres), abs(xres)) for CRS units. The result follows the package polarity (True = drop).

Parameters:

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

Boolean (H, W) mask, True on the geometry.

required
distance float

Maximum distance from the geometry. Pixels on the geometry itself are at distance 0.

required
keep Keep

"inside" (default) keeps pixels within distance — the mask is True beyond it; "outside" keeps pixels beyond distance and drops the zone around the geometry.

'inside'
pixel_size tuple[float, float]

(row_height, col_width) distance sampling.

(1.0, 1.0)

Returns:

Type Description
Bool[ndarray, 'h w']

Boolean (H, W) mask, True where the pixel should be dropped.

Raises:

Type Description
ValueError

If distance is negative or keep is unknown.

Source code in packages/geotoolz-ops/src/geoops/mask/_src/array.py
def distance_mask(
    geometry_mask: Bool[np.ndarray, "h w"],
    distance: float,
    *,
    keep: Keep = "inside",
    pixel_size: tuple[float, float] = (1.0, 1.0),
) -> Bool[np.ndarray, "h w"]:
    """Mask pixels by their distance to an already-rasterized geometry.

    The zone within ``distance`` of the geometry is
    :func:`buffer_mask` of ``geometry_mask`` in ``pixel_size`` units —
    leave the default ``(1.0, 1.0)`` for pixel units, or pass
    ``(abs(yres), abs(xres))`` for CRS units. The result follows the
    package polarity (True = drop).

    Args:
        geometry_mask: Boolean ``(H, W)`` mask, True on the geometry.
        distance: Maximum distance from the geometry. Pixels on the
            geometry itself are at distance ``0``.
        keep: ``"inside"`` (default) keeps pixels within ``distance`` —
            the mask is True beyond it; ``"outside"`` keeps pixels beyond
            ``distance`` and drops the zone around the geometry.
        pixel_size: ``(row_height, col_width)`` distance sampling.

    Returns:
        Boolean ``(H, W)`` mask, True where the pixel should be dropped.

    Raises:
        ValueError: If ``distance`` is negative or ``keep`` is unknown.
    """
    if distance < 0:
        raise ValueError("distance_mask: `distance` must be non-negative")
    _check_keep(keep, "distance_mask")
    within = buffer_mask(
        np.asarray(geometry_mask, dtype=bool),
        distance,
        unit="meters",
        pixel_size=pixel_size,
    )
    return _drop_polarity(within, keep, "distance_mask")

erode_mask(mask, iterations=1, structure=None)

Erode a mask over its trailing two (spatial) axes.

Wraps :func:scipy.ndimage.binary_erosion; see :func:dilate_mask for the batching and structuring-element conventions.

Parameters:

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

Boolean mask, at least 2-D; trailing axes are (H, W).

required
iterations int

Number of erosion passes. 0 returns a copy.

1
structure Bool[ndarray, 'sh sw'] | None

2-D structuring element. Defaults to a 3x3 box (8-connectivity).

None

Returns:

Type Description
Bool[ndarray, '*batch h w']

The eroded boolean mask, same shape as mask.

Raises:

Type Description
ValueError

If iterations is negative, structure is not 2-D, or mask has fewer than two dimensions.

Source code in packages/geotoolz-ops/src/geoops/mask/_src/array.py
def erode_mask(
    mask: Bool[np.ndarray, "*batch h w"],
    iterations: int = 1,
    structure: Bool[np.ndarray, "sh sw"] | None = None,
) -> Bool[np.ndarray, "*batch h w"]:
    """Erode a mask over its trailing two (spatial) axes.

    Wraps :func:`scipy.ndimage.binary_erosion`; see :func:`dilate_mask`
    for the batching and structuring-element conventions.

    Args:
        mask: Boolean mask, at least 2-D; trailing axes are ``(H, W)``.
        iterations: Number of erosion passes. ``0`` returns a copy.
        structure: 2-D structuring element. Defaults to a 3x3 box
            (8-connectivity).

    Returns:
        The eroded boolean mask, same shape as ``mask``.

    Raises:
        ValueError: If ``iterations`` is negative, ``structure`` is not
            2-D, or ``mask`` has fewer than two dimensions.
    """
    return _apply_binary_morphology(
        mask, ndi.binary_erosion, iterations=iterations, structure=structure
    )

invert_mask(mask)

Invert a boolean mask.

Parameters:

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

Boolean mask (non-boolean input is coerced to bool first).

required

Returns:

Type Description
Bool[ndarray, '*batch h w']

The element-wise complement ~mask.

Source code in packages/geotoolz-ops/src/geoops/mask/_src/array.py
def invert_mask(mask: Bool[np.ndarray, "*batch h w"]) -> Bool[np.ndarray, "*batch h w"]:
    """Invert a boolean mask.

    Args:
        mask: Boolean mask (non-boolean input is coerced to bool first).

    Returns:
        The element-wise complement ``~mask``.
    """
    return ~np.asarray(mask, dtype=bool)

open_mask(mask, iterations=1)

Apply binary opening (erosion then dilation) over the spatial axes.

Wraps :func:scipy.ndimage.binary_opening with a 3x3 box structuring element. Removes isolated True pixels (salt) while preserving the extent of large True components.

Parameters:

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

Boolean mask, at least 2-D; trailing axes are (H, W).

required
iterations int

Number of opening passes. 0 returns a copy.

1

Returns:

Type Description
Bool[ndarray, '*batch h w']

The opened boolean mask, same shape as mask.

Raises:

Type Description
ValueError

If iterations is negative or mask has fewer than two dimensions.

Source code in packages/geotoolz-ops/src/geoops/mask/_src/array.py
def open_mask(
    mask: Bool[np.ndarray, "*batch h w"], iterations: int = 1
) -> Bool[np.ndarray, "*batch h w"]:
    """Apply binary opening (erosion then dilation) over the spatial axes.

    Wraps :func:`scipy.ndimage.binary_opening` with a 3x3 box structuring
    element. Removes isolated True pixels (salt) while preserving the
    extent of large True components.

    Args:
        mask: Boolean mask, at least 2-D; trailing axes are ``(H, W)``.
        iterations: Number of opening passes. ``0`` returns a copy.

    Returns:
        The opened boolean mask, same shape as ``mask``.

    Raises:
        ValueError: If ``iterations`` is negative or ``mask`` has fewer
            than two dimensions.
    """
    return _apply_binary_morphology(mask, ndi.binary_opening, iterations=iterations)

remove_small_holes(mask, max_hole_area_px, *, connectivity=4)

Fill enclosed False components up to max_hole_area_px pixels.

A hole is a False component that does not touch the image border. Each leading (batch / band) slice is processed independently.

Parameters:

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

Boolean mask, at least 2-D; trailing axes are (H, W).

required
max_hole_area_px int

Maximum hole area, in pixels, to fill. 0 fills nothing.

required
connectivity Connectivity

4 (default) or 8 neighbourhood used to group background pixels into holes.

4

Returns:

Type Description
Bool[ndarray, '*batch h w']

The filled boolean mask, same shape as mask.

Raises:

Type Description
ValueError

If max_hole_area_px is negative or mask has fewer than two dimensions.

Source code in packages/geotoolz-ops/src/geoops/mask/_src/array.py
def remove_small_holes(
    mask: Bool[np.ndarray, "*batch h w"],
    max_hole_area_px: int,
    *,
    connectivity: Connectivity = 4,
) -> Bool[np.ndarray, "*batch h w"]:
    """Fill enclosed False components up to ``max_hole_area_px`` pixels.

    A hole is a False component that does not touch the image border.
    Each leading (batch / band) slice is processed independently.

    Args:
        mask: Boolean mask, at least 2-D; trailing axes are ``(H, W)``.
        max_hole_area_px: Maximum hole area, in pixels, to fill. ``0``
            fills nothing.
        connectivity: ``4`` (default) or ``8`` neighbourhood used to
            group background pixels into holes.

    Returns:
        The filled boolean mask, same shape as ``mask``.

    Raises:
        ValueError: If ``max_hole_area_px`` is negative or ``mask`` has
            fewer than two dimensions.
    """
    if max_hole_area_px < 0:
        raise ValueError("remove_small_holes: `max_hole_area_px` must be non-negative")
    return _apply_spatial(
        mask,
        _remove_small_holes_2d,
        max_area=max_hole_area_px,
        connectivity=connectivity,
        exclude_border=True,
    )

remove_small_objects(mask, min_area_px, *, connectivity=4)

Remove connected True components smaller than min_area_px pixels.

Delegates to :func:geoops.measure.label_components. Each leading (batch / band) slice is cleaned independently.

Parameters:

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

Boolean mask, at least 2-D; trailing axes are (H, W).

required
min_area_px int

Minimum component area, in pixels, for a component to be kept. 0 keeps everything.

required
connectivity Connectivity

4 (default) or 8 neighbourhood.

4

Returns:

Type Description
Bool[ndarray, '*batch h w']

The cleaned boolean mask, same shape as mask.

Raises:

Type Description
ValueError

If min_area_px is negative or mask has fewer than two dimensions.

Source code in packages/geotoolz-ops/src/geoops/mask/_src/array.py
def remove_small_objects(
    mask: Bool[np.ndarray, "*batch h w"],
    min_area_px: int,
    *,
    connectivity: Connectivity = 4,
) -> Bool[np.ndarray, "*batch h w"]:
    """Remove connected True components smaller than ``min_area_px`` pixels.

    Delegates to :func:`geoops.measure.label_components`. Each leading
    (batch / band) slice is cleaned independently.

    Args:
        mask: Boolean mask, at least 2-D; trailing axes are ``(H, W)``.
        min_area_px: Minimum component area, in pixels, for a component to
            be kept. ``0`` keeps everything.
        connectivity: ``4`` (default) or ``8`` neighbourhood.

    Returns:
        The cleaned boolean mask, same shape as ``mask``.

    Raises:
        ValueError: If ``min_area_px`` is negative or ``mask`` has fewer
            than two dimensions.
    """
    if min_area_px < 0:
        raise ValueError("remove_small_objects: `min_area_px` must be non-negative")
    return _apply_spatial(
        mask,
        _remove_small_objects_2d,
        min_area_px=min_area_px,
        connectivity=connectivity,
    )

slope_degrees(dem, pixel_size)

Compute slope in degrees from a single-band DEM.

The gradient is estimated with central differences (:func:numpy.gradient) scaled by the pixel size; the slope is degrees(arctan(hypot(dz/dx, dz/dy))). Elevation and pixel size must be in the same linear units for the angles to be meaningful.

Parameters:

Name Type Description Default
dem Float[ndarray, 'h w'] | Float[ndarray, '1 h w']

Single-band elevation raster, (H, W) or (1, H, W).

required
pixel_size tuple[float, float]

(row_height, col_width) pixel extent in the same units as the elevation values.

required

Returns:

Type Description
Float[ndarray, 'h w']

Float (H, W) slope map in degrees, in [0, 90).

Raises:

Type Description
ValueError

If dem is not a single-band map.

Source code in packages/geotoolz-ops/src/geoops/mask/_src/array.py
def slope_degrees(
    dem: Float[np.ndarray, "h w"] | Float[np.ndarray, "1 h w"],
    pixel_size: tuple[float, float],
) -> Float[np.ndarray, "h w"]:
    """Compute slope in degrees from a single-band DEM.

    The gradient is estimated with central differences
    (:func:`numpy.gradient`) scaled by the pixel size; the slope is
    ``degrees(arctan(hypot(dz/dx, dz/dy)))``. Elevation and pixel size
    must be in the same linear units for the angles to be meaningful.

    Args:
        dem: Single-band elevation raster, ``(H, W)`` or ``(1, H, W)``.
        pixel_size: ``(row_height, col_width)`` pixel extent in the same
            units as the elevation values.

    Returns:
        Float ``(H, W)`` slope map in degrees, in ``[0, 90)``.

    Raises:
        ValueError: If ``dem`` is not a single-band map.
    """
    arr = single_band(dem, name="slope_degrees").astype(float, copy=False)
    yres, xres = pixel_size
    grad_y, grad_x = np.gradient(arr, yres, xres)
    return np.degrees(np.arctan(np.hypot(grad_x, grad_y)))

slope_mask(dem, pixel_size, *, min_slope_deg=None, max_slope_deg=None, keep='inside')

Mask DEM cells by a slope interval (True = drop).

Slope is computed with :func:slope_degrees; see there for the pixel-size / unit contract.

Parameters:

Name Type Description Default
dem Float[ndarray, 'h w'] | Float[ndarray, '1 h w']

Single-band elevation raster, (H, W) or (1, H, W).

required
pixel_size tuple[float, float]

(row_height, col_width) pixel extent in the same units as the elevation values.

required
min_slope_deg float | None

Inclusive lower slope bound in degrees. None leaves the interval open below.

None
max_slope_deg float | None

Inclusive upper slope bound in degrees. None leaves the interval open above.

None
keep Keep

"inside" (default) keeps cells whose slope lies inside [min_slope_deg, max_slope_deg] — the mask is True outside it; "outside" keeps cells outside the interval.

'inside'

Returns:

Type Description
Bool[ndarray, 'h w']

Boolean (H, W) mask, True where the cell should be dropped.

Raises:

Type Description
ValueError

If both bounds are None, keep is unknown, or dem is not a single-band map.

Source code in packages/geotoolz-ops/src/geoops/mask/_src/array.py
def slope_mask(
    dem: Float[np.ndarray, "h w"] | Float[np.ndarray, "1 h w"],
    pixel_size: tuple[float, float],
    *,
    min_slope_deg: float | None = None,
    max_slope_deg: float | None = None,
    keep: Keep = "inside",
) -> Bool[np.ndarray, "h w"]:
    """Mask DEM cells by a slope interval (True = drop).

    Slope is computed with :func:`slope_degrees`; see there for the
    pixel-size / unit contract.

    Args:
        dem: Single-band elevation raster, ``(H, W)`` or ``(1, H, W)``.
        pixel_size: ``(row_height, col_width)`` pixel extent in the same
            units as the elevation values.
        min_slope_deg: Inclusive lower slope bound in degrees. ``None``
            leaves the interval open below.
        max_slope_deg: Inclusive upper slope bound in degrees. ``None``
            leaves the interval open above.
        keep: ``"inside"`` (default) keeps cells whose slope lies inside
            ``[min_slope_deg, max_slope_deg]`` — the mask is True outside
            it; ``"outside"`` keeps cells outside the interval.

    Returns:
        Boolean ``(H, W)`` mask, True where the cell should be dropped.

    Raises:
        ValueError: If both bounds are ``None``, ``keep`` is unknown, or
            ``dem`` is not a single-band map.
    """
    if min_slope_deg is None and max_slope_deg is None:
        raise ValueError("slope_mask: at least one slope bound is required")
    slope = slope_degrees(dem, pixel_size)
    mask = np.ones(slope.shape, dtype=bool)
    if min_slope_deg is not None:
        mask &= slope >= min_slope_deg
    if max_slope_deg is not None:
        mask &= slope <= max_slope_deg
    return _drop_polarity(mask, keep, "slope_mask")