Skip to content

Viz

Display-time helpers: composites, stretches, colormaps, hillshade overlays. Outputs are typically uint8 RGB(A) for direct rendering.

  • Composites: Composite, TrueColor, FalseColor, SWIRComposite (spectral.SelectBands presets: the selected bands' band_names / wavelengths travel with the output), and RGBRecipe — three band expressions with fixed vmin / vmax stretches and per-channel gamma, the form of the operational satellite RGBs (day cloud phase, fire temperature, …)
  • Stretches: StretchToUint8 (= radiometry.PercentileClip + a rounded byte cast; same lower / upper / reduce_axes arguments), GammaCorrect (radiometry's gamma on the display range)
  • Colormaps: ApplyColormap, ApplyDiscreteColormap
  • Terrain: Hillshade, ShadedRelief
  • Overlays: AnnotatePoints, AnnotatePolygons, Overlay
  • Tier-A primitives: stretch_to_uint8, gamma_correct_display, rgb_recipe, rgba_from_scalar, rgba_from_categories, ensure_rgba, blend_rgba

geoops.viz

Visualization Operators for RGB composites, display stretching, and overlays.

AnnotatePoints

Bases: Operator

Draw circular point markers into a display GeoArray.

Renders disk-shaped markers at the supplied points into the RGBA carrier. Accepts either an (N, 2) array of (x, y) map coordinates or a GeoDataFrame (which is reprojected when it carries a CRS). Flagged forbid_in_yaml = True because the points are runtime objects. Geo-dependent: locating the markers needs the carrier's transform / crs, so a georeferenced GeoArray input is required. A (T, C, H, W) stack is annotated frame by frame.

Parameters:

Name Type Description Default
points Any

(N, 2) array of map coords or a GeoDataFrame of Point geometries.

required
radius int

Marker radius in pixels. 0 paints a single pixel. Default 3.

3
color Color

RGBA tuple in [0, 1]. Default opaque yellow.

(1.0, 1.0, 0.0, 1.0)

Examples:

>>> import geoops as gz
>>> import numpy as np
>>> annotated = gz.viz.AnnotatePoints(
...     points=np.array([[12.5, 41.9]]), radius=4
... )(rgb_gt)
Source code in packages/geotoolz-ops/src/geoops/viz/_src/operators.py
class AnnotatePoints(Operator):
    """Draw circular point markers into a display GeoArray.

    Renders disk-shaped markers at the supplied points into the RGBA
    carrier. Accepts either an ``(N, 2)`` array of ``(x, y)`` map
    coordinates or a GeoDataFrame (which is reprojected when it carries
    a CRS). Flagged ``forbid_in_yaml = True`` because the points are
    runtime objects. Geo-dependent: locating the markers needs the
    carrier's ``transform`` / ``crs``, so a georeferenced GeoArray
    input is required. A ``(T, C, H, W)`` stack is annotated frame by
    frame.

    Args:
        points: ``(N, 2)`` array of map coords or a GeoDataFrame of
            Point geometries.
        radius: Marker radius in pixels. ``0`` paints a single pixel.
            Default ``3``.
        color: RGBA tuple in ``[0, 1]``. Default opaque yellow.

    Examples:
        >>> import geoops as gz
        >>> import numpy as np
        >>> annotated = gz.viz.AnnotatePoints(
        ...     points=np.array([[12.5, 41.9]]), radius=4
        ... )(rgb_gt)
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # drawn, then the bands scaled together over the scene for display
    coupling: ClassVar[Coupling] = Coupling(
        couples={"band", "space"}, effects={"band": "expand"}, reach=None
    )

    forbid_in_yaml: ClassVar[bool] = True

    def __init__(
        self,
        *,
        points: Any,
        radius: int = 3,
        color: Color = (1.0, 1.0, 0.0, 1.0),
    ) -> None:
        self.points = points
        self.radius = radius
        self.color = color

    @over_frames
    def _apply(self, gt: GeoArray) -> GeoArray:
        rowcol = optional_name(
            "rasterio.transform",
            "rowcol",
            "raster",
            feature="geoops.viz.AnnotatePoints",
        )

        require_geoarray(gt, "AnnotatePoints")
        rgba = ensure_rgba(np.asarray(gt), name="AnnotatePoints")
        coords = _point_coords(self.points, dst_crs=gt.crs)
        if coords.size == 0:
            return wrap_like(gt, rgba, fill_value=0)
        rows, cols = rowcol(affine_of(gt), coords[:, 0], coords[:, 1])
        yy, xx = np.ogrid[: rgba.shape[-2], : rgba.shape[-1]]
        marker = np.zeros(rgba.shape[-2:], dtype=bool)
        radius = max(int(self.radius), 0)
        for row, col in zip(rows, cols, strict=True):
            marker |= (yy - row) ** 2 + (xx - col) ** 2 <= radius**2
        rgba[:, marker] = _color_to_uint8(self.color)[:, None]
        return wrap_like(gt, rgba, fill_value=0)

    def get_config(self) -> dict[str, Any]:
        return {
            "points": repr(self.points),
            "radius": self.radius,
            "color": list(self.color),
        }

AnnotatePolygons

Bases: Operator

Rasterize polygon outlines into a display GeoArray.

Burn polygon boundaries (buffered by width pixels) into the RGBA carrier. The geometries are reprojected into the carrier's CRS when they ship as a GeoDataFrame with a CRS set. Flagged forbid_in_yaml = True because the geometries themselves are runtime objects and don't round-trip through YAML. Geo-dependent: rasterisation needs the carrier's transform / crs, so a georeferenced GeoArray input is required. A (T, C, H, W) stack is annotated frame by frame.

Parameters:

Name Type Description Default
geometries Any

Iterable of Shapely geometries or a GeoDataFrame.

required
color Color

RGBA tuple in [0, 1]. Default red opaque.

(1.0, 0.0, 0.0, 1.0)
width int

Outline width in pixels. 0 is a no-op. Default 2.

2

Examples:

>>> import geoops as gz
>>> from shapely.geometry import Polygon
>>> field = Polygon([(0, 0), (10, 0), (10, 10), (0, 10)])
>>> annotated = gz.viz.AnnotatePolygons(geometries=[field])(rgb_gt)
Source code in packages/geotoolz-ops/src/geoops/viz/_src/operators.py
class AnnotatePolygons(Operator):
    """Rasterize polygon outlines into a display GeoArray.

    Burn polygon boundaries (buffered by ``width`` pixels) into the
    RGBA carrier. The geometries are reprojected into the carrier's
    CRS when they ship as a GeoDataFrame with a CRS set. Flagged
    ``forbid_in_yaml = True`` because the geometries themselves are
    runtime objects and don't round-trip through YAML. Geo-dependent:
    rasterisation needs the carrier's ``transform`` / ``crs``, so a
    georeferenced GeoArray input is required. A ``(T, C, H, W)`` stack
    is annotated frame by frame.

    Args:
        geometries: Iterable of Shapely geometries or a GeoDataFrame.
        color: RGBA tuple in ``[0, 1]``. Default red opaque.
        width: Outline width in pixels. ``0`` is a no-op. Default ``2``.

    Examples:
        >>> import geoops as gz
        >>> from shapely.geometry import Polygon
        >>> field = Polygon([(0, 0), (10, 0), (10, 10), (0, 10)])
        >>> annotated = gz.viz.AnnotatePolygons(geometries=[field])(rgb_gt)
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # drawn, then the bands scaled together over the scene for display
    coupling: ClassVar[Coupling] = Coupling(
        couples={"band", "space"}, effects={"band": "expand"}, reach=None
    )

    forbid_in_yaml: ClassVar[bool] = True

    def __init__(
        self,
        *,
        geometries: Any,
        color: Color = (1.0, 0.0, 0.0, 1.0),
        width: int = 2,
    ) -> None:
        self.geometries = geometries
        self.color = color
        self.width = width

    @over_frames
    def _apply(self, gt: GeoArray) -> GeoArray:
        feature = "geoops.viz.AnnotatePolygons"
        gpd = optional_module("geopandas", "vector", feature=feature)
        rasterize_geopandas_like = optional_name(
            "georeader.rasterize",
            "rasterize_geopandas_like",
            "sensors",
            feature=feature,
        )

        require_geoarray(gt, "AnnotatePolygons")
        rgba = ensure_rgba(np.asarray(gt), name="AnnotatePolygons")
        geometries = _iter_geometries(self.geometries, dst_crs=gt.crs)
        if not geometries or self.width <= 0:
            return wrap_like(gt, rgba, fill_value=0)
        transform = affine_of(gt)
        pixel_size = max(abs(float(transform.a)), abs(float(transform.e)))
        half_width = self.width * pixel_size / 2.0
        # Buffer in the carrier's CRS (pixel-width outlines), then burn
        # through georeader onto the carrier's grid.
        outlines = gpd.GeoDataFrame(
            {"burn": np.ones(len(geometries), dtype=np.uint8)},
            geometry=[geom.boundary.buffer(half_width) for geom in geometries],
            crs=gt.crs,
        )
        mask = np.asarray(
            rasterize_geopandas_like(
                outlines,
                to_engine(gt),
                "burn",
                fill=0,
                all_touched=True,
                return_only_data=True,
            )
        ).astype(bool)
        rgba[:, mask] = _color_to_uint8(self.color)[:, None]
        return wrap_like(gt, rgba, fill_value=0)

    def get_config(self) -> dict[str, Any]:
        return {
            "geometries": repr(self.geometries),
            "color": list(self.color),
            "width": self.width,
        }

ApplyColormap

Bases: Operator

Map a single-band raster to a four-band RGBA GeoArray.

Looks up name in matplotlib's registry (or in cmocean if the name is prefixed with "cmocean."). The colormap is referenced by string name, not by the live Colormap object — so get_config() round-trips through JSON / YAML cleanly. Geo-metadata (transform / crs) is preserved. Metadata-independent: plain np.ndarray carriers pass through as plain arrays.

Parameters:

Name Type Description Default
name str

Colormap registry name (e.g. "viridis", "terrain", "cmocean.balance").

'viridis'
vmin float | None

Optional explicit lower bound. None auto-detects.

None
vmax float | None

Optional explicit upper bound. None auto-detects.

None
nan_color Color

RGBA tuple in [0, 1] to paint nodata pixels (non-finite, or equal to the carrier's fill_value). Default fully transparent, i.e. the output fill 0. Nodata pixels never enter the auto-detected vmin / vmax.

(0.0, 0.0, 0.0, 0.0)

Examples:

>>> import geoops as gz
>>> # Render an NDVI raster as a viridis RGBA overlay.
>>> rgba = gz.viz.ApplyColormap(name="viridis", vmin=-1, vmax=1)(ndvi_gt)
>>> # Use a cmocean ocean colourmap with the prefix.
>>> rgba = gz.viz.ApplyColormap(name="cmocean.thermal")(sst_gt)
Source code in packages/geotoolz-ops/src/geoops/viz/_src/operators.py
class ApplyColormap(Operator):
    """Map a single-band raster to a four-band RGBA GeoArray.

    Looks up ``name`` in matplotlib's registry (or in cmocean if the
    name is prefixed with ``"cmocean."``). The colormap is referenced
    by *string name*, not by the live `Colormap` object — so
    ``get_config()`` round-trips through JSON / YAML cleanly.
    Geo-metadata (``transform`` / ``crs``) is preserved.
    Metadata-independent: plain ``np.ndarray`` carriers pass through
    as plain arrays.

    Args:
        name: Colormap registry name (e.g. ``"viridis"``, ``"terrain"``,
            ``"cmocean.balance"``).
        vmin: Optional explicit lower bound. ``None`` auto-detects.
        vmax: Optional explicit upper bound. ``None`` auto-detects.
        nan_color: RGBA tuple in ``[0, 1]`` to paint nodata pixels
            (non-finite, or equal to the carrier's
            ``fill_value``). Default fully transparent, i.e. the
            output fill ``0``. Nodata pixels never enter the auto-detected
            ``vmin`` / ``vmax``.

    Examples:
        >>> import geoops as gz
        >>> # Render an NDVI raster as a viridis RGBA overlay.
        >>> rgba = gz.viz.ApplyColormap(name="viridis", vmin=-1, vmax=1)(ndvi_gt)
        >>> # Use a cmocean ocean colourmap with the prefix.
        >>> rgba = gz.viz.ApplyColormap(name="cmocean.thermal")(sst_gt)
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # vmin and vmax from the scene when not given
    coupling: ClassVar[Coupling] = Coupling(couples={"space"}, reach=None)

    def __init__(
        self,
        *,
        name: str = "viridis",
        vmin: float | None = None,
        vmax: float | None = None,
        nan_color: Color = (0.0, 0.0, 0.0, 0.0),
    ) -> None:
        self.name = name
        self.vmin = vmin
        self.vmax = vmax
        self.nan_color = nan_color

    @over_frames
    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        cmap = _get_colormap(self.name)
        valid = valid_pixels(gt)
        out = rgba_from_scalar(
            np.asarray(gt) if valid.all() else mask_invalid_to_nan(gt, valid=valid),
            cmap,
            vmin=self.vmin,
            vmax=self.vmax,
            nan_color=self.nan_color,
        )
        return wrap_like(gt, out, fill_value=0)

    def get_config(self) -> dict[str, Any]:
        return {
            "name": self.name,
            "vmin": self.vmin,
            "vmax": self.vmax,
            "nan_color": list(self.nan_color),
        }

ApplyDiscreteColormap

Bases: Operator

Map integer categories to a four-band RGBA GeoArray.

Classic categorical-label visualisation (land-cover classes, cloud masks, etc). Unmapped pixels render fully transparent. Pixels not in the mapping fall back to that default colour. Nodata pixels (equal to the carrier's fill_value) render fully transparent (0) even if the fill value appears in mapping. Metadata-independent: plain np.ndarray carriers pass through as plain arrays.

Parameters:

Name Type Description Default
mapping Mapping[int, Color] | Sequence[Sequence[Any]]

{class_id: (r, g, b, a)} lookup table. The class IDs are integers; the RGBA components are floats in [0, 1]. Also accepts the [[class_id, rgba], ...] pairs that get_config() emits.

required

Examples:

>>> import geoops as gz
>>> # Render a 3-class land-cover mask.
>>> cmap = {
...     0: (0.0, 0.0, 0.0, 0.0),  # nodata -> transparent
...     1: (0.1, 0.5, 0.1, 1.0),  # forest
...     2: (0.7, 0.7, 0.2, 1.0),  # cropland
... }
>>> rgba = gz.viz.ApplyDiscreteColormap(mapping=cmap)(lulc_gt)
Source code in packages/geotoolz-ops/src/geoops/viz/_src/operators.py
class ApplyDiscreteColormap(Operator):
    """Map integer categories to a four-band RGBA GeoArray.

    Classic categorical-label visualisation (land-cover classes, cloud
    masks, etc). Unmapped pixels render fully transparent. Pixels not
    in the mapping fall back to that default colour. Nodata pixels
    (equal to the carrier's ``fill_value``) render fully
    transparent (``0``) even if the fill value appears in ``mapping``.
    Metadata-independent: plain ``np.ndarray`` carriers pass through
    as plain arrays.

    Args:
        mapping: ``{class_id: (r, g, b, a)}`` lookup table. The class
            IDs are integers; the RGBA components are floats in
            ``[0, 1]``. Also accepts the ``[[class_id, rgba], ...]``
            pairs that ``get_config()`` emits.

    Examples:
        >>> import geoops as gz
        >>> # Render a 3-class land-cover mask.
        >>> cmap = {
        ...     0: (0.0, 0.0, 0.0, 0.0),  # nodata -> transparent
        ...     1: (0.1, 0.5, 0.1, 1.0),  # forest
        ...     2: (0.7, 0.7, 0.2, 1.0),  # cropland
        ... }
        >>> rgba = gz.viz.ApplyDiscreteColormap(mapping=cmap)(lulc_gt)
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # one RGBA colour per class
    coupling: ClassVar[Coupling] = Coupling(effects={"band": "expand"})

    def __init__(
        self, *, mapping: Mapping[int, Color] | Sequence[Sequence[Any]]
    ) -> None:
        pairs = mapping_from_pairs(mapping) or {}
        self.mapping = {int(k): tuple(v) for k, v in pairs.items()}

    @over_frames
    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        out = rgba_from_categories(np.asarray(gt), self.mapping)
        out = restore_fill(out, valid_pixels(gt), 0)
        return wrap_like(gt, out, fill_value=0)

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

Composite

Bases: SelectBands

Build a multi-band composite by arbitrary band reference.

A thin :class:geoops.spectral.SelectBands subclass spelled with bands — the generic band-selection operator the named composites (TrueColor, FalseColor, SWIRComposite) wrap. Bands may be referenced by integer position along axis or by name, resolved against the carrier's attrs by the package-wide resolver (band_names, then descriptions, then bands). Output has len(bands) slices along axis and the same spatial footprint as the input — transform and crs round-trip unchanged. The selected bands' per-band attrs (band_names, wavelengths, ...) travel with the output in output order, in a fresh attrs dict. Plain np.ndarray carriers are supported with integer band references (returning a plain array); string names need a carrier with band names in attrs. Fill values pass through unchanged (pure band selection).

Parameters:

Name Type Description Default
bands Sequence[BandRef]

Sequence of band references. Each entry is either an integer position or a string name resolved against the carrier's attrs.

required
dim str

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

'band'
axis int | None

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

None

Examples:

>>> import geoops as gz
>>> # Sentinel-2 natural-colour composite by name.
>>> rgb = gz.viz.Composite(bands=["B04", "B03", "B02"])(s2_geotensor)
>>> # Or by integer position when the carrier has no band names.
>>> rgb = gz.viz.Composite(bands=[3, 2, 1])(s2_geotensor)
Source code in packages/geotoolz-ops/src/geoops/viz/_src/operators.py
class Composite(SelectBands):
    """Build a multi-band composite by arbitrary band reference.

    A thin :class:`geoops.spectral.SelectBands` subclass spelled with
    ``bands`` — the generic band-selection operator the named composites
    (`TrueColor`, `FalseColor`, `SWIRComposite`) wrap. Bands may be
    referenced by integer position along ``axis`` or by name, resolved
    against the carrier's ``attrs`` by the package-wide resolver
    (``band_names``, then ``descriptions``, then ``bands``). Output has
    ``len(bands)`` slices along ``axis`` and the same spatial footprint
    as the input — ``transform`` and ``crs`` round-trip unchanged. The
    selected bands' per-band attrs (``band_names``, ``wavelengths``, ...)
    travel with the output in output order, in a fresh ``attrs`` dict.
    Plain ``np.ndarray`` carriers are supported with integer band
    references (returning a plain array); string names need a carrier
    with band names in ``attrs``. Fill values pass through unchanged
    (pure band selection).

    Args:
        bands: Sequence of band references. Each entry is either an
            integer position or a string name resolved against the
            carrier's ``attrs``.
        dim: Name of the band dim (default ``"band"``); its position is read
            from the carrier's dims.
        axis: Deprecated: the band axis position. ``-3`` maps to
            ``dim="band"``; removed in the next minor release.

    Examples:
        >>> import geoops as gz
        >>> # Sentinel-2 natural-colour composite by name.
        >>> rgb = gz.viz.Composite(bands=["B04", "B03", "B02"])(s2_geotensor)
        >>> # Or by integer position when the carrier has no band names.
        >>> rgb = gz.viz.Composite(bands=[3, 2, 1])(s2_geotensor)
    """

    def __init__(
        self, *, bands: Sequence[BandRef], dim: str = "band", axis: int | None = None
    ) -> None:
        super().__init__(bands=list(bands), dim=dim, axis=axis)

FalseColor

Bases: Composite

Build a NIR-red-green false-colour composite.

Vegetation visualisation preset: healthy vegetation shows red because NIR reflectance is high. Equivalent to Composite(bands=[nir, red, green]) with self-documenting kwargs.

Parameters:

Name Type Description Default
nir BandRef

Near-infrared band reference (rendered as red).

required
red BandRef

Red band reference (rendered as green).

required
green BandRef

Green band reference (rendered as blue).

required
dim str

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

'band'
axis int | None

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

None

Examples:

>>> import geoops as gz
>>> # Sentinel-2 vegetation false colour (8/4/3).
>>> vis = gz.viz.FalseColor(nir="B08", red="B04", green="B03")(s2)
Source code in packages/geotoolz-ops/src/geoops/viz/_src/operators.py
class FalseColor(Composite):
    """Build a NIR-red-green false-colour composite.

    Vegetation visualisation preset: healthy vegetation shows red
    because NIR reflectance is high. Equivalent to
    ``Composite(bands=[nir, red, green])`` with self-documenting kwargs.

    Args:
        nir: Near-infrared band reference (rendered as red).
        red: Red band reference (rendered as green).
        green: Green band reference (rendered as blue).
        dim: Name of the band dim (default ``"band"``); its position is read
            from the carrier's dims.
        axis: Deprecated: the band axis position. ``-3`` maps to
            ``dim="band"``; removed in the next minor release.

    Examples:
        >>> import geoops as gz
        >>> # Sentinel-2 vegetation false colour (8/4/3).
        >>> vis = gz.viz.FalseColor(nir="B08", red="B04", green="B03")(s2)
    """

    def __init__(
        self,
        *,
        nir: BandRef,
        red: BandRef,
        green: BandRef,
        dim: str = "band",
        axis: int | None = None,
    ) -> None:
        super().__init__(bands=[nir, red, green], dim=dim, axis=axis)
        self.nir = nir
        self.red = red
        self.green = green

    def get_config(self) -> dict[str, Any]:
        return {
            "nir": self.nir,
            "red": self.red,
            "green": self.green,
            "dim": self.dim,
        }

GammaCorrect

Bases: Operator

Apply display gamma correction.

Power-law correction for display-range arrays — brightens midtones when gamma > 1. The exponent is :func:geoops.radiometry.gamma_correct (the math behind :class:geoops.radiometry.Gamma); this operator adds the display range handling: float carriers are clipped to [0, 1] before the exponent, and integer carriers are normalised to [0, 1] by their dtype maximum and rounded back so the transform is display-correct rather than a raw 256 ** (1 / gamma) = 16 on uint8. Metadata-independent: plain np.ndarray carriers pass through as plain arrays. Elementwise: fill (and non-finite) values are passed through unchanged rather than gamma-corrected.

Parameters:

Name Type Description Default
gamma float

Gamma factor (must be strictly positive). Default 1.0.

1.0
inplace_norm bool

Normalise integer inputs to [0, 1] before the exponent (default True). Set False only when the carrier has been pre-normalised upstream.

True

Examples:

>>> import geoops as gz
>>> # Brighten midtones on a percentile-stretched RGB.
>>> pipe = (
...     gz.viz.TrueColor(red="B04", green="B03", blue="B02")
...     | gz.viz.StretchToUint8()
...     | gz.viz.GammaCorrect(gamma=1.2)
... )
Source code in packages/geotoolz-ops/src/geoops/viz/_src/operators.py
class GammaCorrect(Operator):
    """Apply display gamma correction.

    Power-law correction for display-range arrays — brightens midtones
    when ``gamma > 1``. The exponent is
    :func:`geoops.radiometry.gamma_correct` (the math behind
    :class:`geoops.radiometry.Gamma`); this operator adds the display
    range handling: float carriers are clipped to ``[0, 1]`` before the
    exponent, and integer carriers are normalised to ``[0, 1]`` by their
    dtype maximum and rounded back so the transform is display-correct
    rather than a raw ``256 ** (1 / gamma) = 16`` on uint8.
    Metadata-independent: plain ``np.ndarray`` carriers pass through as
    plain arrays. Elementwise: fill (and non-finite) values are passed
    through unchanged rather than gamma-corrected.

    Args:
        gamma: Gamma factor (must be strictly positive). Default ``1.0``.
        inplace_norm: Normalise integer inputs to ``[0, 1]`` before the
            exponent (default ``True``). Set ``False`` only when the
            carrier has been pre-normalised upstream.

    Examples:
        >>> import geoops as gz
        >>> # Brighten midtones on a percentile-stretched RGB.
        >>> pipe = (
        ...     gz.viz.TrueColor(red="B04", green="B03", blue="B02")
        ...     | gz.viz.StretchToUint8()
        ...     | gz.viz.GammaCorrect(gamma=1.2)
        ... )
    """

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

    def __init__(self, *, gamma: float = 1.0, inplace_norm: bool = True) -> None:
        self.gamma = gamma
        self.inplace_norm = inplace_norm

    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        out = gamma_correct_display(
            np.asarray(gt), gamma=self.gamma, inplace_norm=self.inplace_norm
        )
        valid = ~invalid_values(gt)
        fill = carried_fill(gt, np.asarray(out).dtype)
        return wrap_like(gt, restore_fill(out, valid, fill), fill_value=fill)

Hillshade

Bases: Operator

Compute a single-band uint8 hillshade from a DEM.

GDAL-style hillshade: combines slope and aspect from the DEM with a sun position (azimuth + altitude). The output is a single-band (H, W) uint8 raster, ready to compose with a colour relief (see ShadedRelief). Pixel sizes come from the carrier's transform as ground step lengths (hypot(a, d) / hypot(b, e)), so units are correct in physical projections and on rotated grids (the azimuth is then relative to the grid's "up" direction); a sheared grid or a geographic CRS (degree pixel sizes against linear elevations) raises ValueError -- reproject first, or pass both resolutions explicitly. Geo-dependent by default: plain np.ndarray DEMs are accepted only when x_resolution and y_resolution are given explicitly; otherwise a TypeError is raised. Nodata DEM pixels (non-finite or equal to fill_value) do not leak into their neighbours' slope and are written as 0 (the output fill).

Parameters:

Name Type Description Default
azimuth_deg float

Sun azimuth in degrees clockwise from north. Default 315 (NW — the cartographic convention).

315.0
altitude_deg float

Sun elevation in degrees above horizon. Default 45. Values >= 90 short-circuit to flat 255.

45.0
z_factor float

Vertical exaggeration. Default 1.0.

1.0
x_resolution float | None

Explicit pixel width in map units. None (default) reads it from the carrier's transform.

None
y_resolution float | None

Explicit pixel height in map units. None (default) reads it from the carrier's transform.

None

Examples:

>>> import geoops as gz
>>> shade = gz.viz.Hillshade(azimuth_deg=315, altitude_deg=45)(dem_gt)
Source code in packages/geotoolz-ops/src/geoops/viz/_src/operators.py
class Hillshade(Operator):
    """Compute a single-band ``uint8`` hillshade from a DEM.

    GDAL-style hillshade: combines slope and aspect from the DEM with
    a sun position (azimuth + altitude). The output is a single-band
    ``(H, W)`` ``uint8`` raster, ready to compose with a colour relief
    (see `ShadedRelief`). Pixel sizes come from the carrier's
    ``transform`` as ground step lengths (``hypot(a, d)`` /
    ``hypot(b, e)``), so units are correct in physical projections and on
    rotated grids (the azimuth is then relative to the grid's "up"
    direction); a sheared grid or a geographic CRS (degree pixel sizes
    against linear elevations) raises ``ValueError`` -- reproject first,
    or pass both resolutions explicitly.
    Geo-dependent by default: plain ``np.ndarray`` DEMs are accepted
    only when ``x_resolution`` and ``y_resolution`` are given
    explicitly; otherwise a ``TypeError`` is raised. Nodata DEM pixels
    (non-finite or equal to ``fill_value``) do not leak into
    their neighbours' slope and are written as ``0`` (the output fill).

    Args:
        azimuth_deg: Sun azimuth in degrees clockwise from north.
            Default ``315`` (NW — the cartographic convention).
        altitude_deg: Sun elevation in degrees above horizon. Default
            ``45``. Values ``>= 90`` short-circuit to flat 255.
        z_factor: Vertical exaggeration. Default ``1.0``.
        x_resolution: Explicit pixel width in map units. ``None``
            (default) reads it from the carrier's ``transform``.
        y_resolution: Explicit pixel height in map units. ``None``
            (default) reads it from the carrier's ``transform``.

    Examples:
        >>> import geoops as gz
        >>> shade = gz.viz.Hillshade(azimuth_deg=315, altitude_deg=45)(dem_gt)
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # a 3 x 3 slope and aspect
    coupling: ClassVar[Coupling] = Coupling(couples={"space"}, reach=1)

    def __init__(
        self,
        *,
        azimuth_deg: float = 315.0,
        altitude_deg: float = 45.0,
        z_factor: float = 1.0,
        x_resolution: float | None = None,
        y_resolution: float | None = None,
    ) -> None:
        self.azimuth_deg = azimuth_deg
        self.altitude_deg = altitude_deg
        self.z_factor = z_factor
        self.x_resolution = x_resolution
        self.y_resolution = y_resolution

    @over_frames
    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        x_resolution = self.x_resolution
        y_resolution = self.y_resolution
        if x_resolution is None or y_resolution is None:
            transform = require_geoarray(
                gt,
                "Hillshade",
                hint="Pass x_resolution/y_resolution explicitly to hillshade "
                "plain arrays.",
            ).transform
            require_projected_crs(gt, "Hillshade", what="slopes", metres=False)
            row_step, col_step = ground_pixel_size(transform, "Hillshade")
            if x_resolution is None:
                x_resolution = col_step
            if y_resolution is None:
                y_resolution = row_step
        out = hillshade(
            np.asarray(gt),
            x_resolution=x_resolution,
            y_resolution=y_resolution,
            azimuth_deg=self.azimuth_deg,
            altitude_deg=self.altitude_deg,
            z_factor=self.z_factor,
            valid=valid_pixels(gt),
        )
        return wrap_like(gt, out, fill_value=0)

Overlay

Bases: Operator

Blend background and foreground GeoArrays on the same grid.

Two-input Operator: Overlay()(background, foreground). When both carriers are georeferenced they must share transform and crs (this is a viz primitive, not a reprojector); plain np.ndarray carriers skip the metadata check and blend on pixel grids alone, returning the background's carrier kind. Output is always 4-band uint8 RGBA — even when alpha=0 — so downstream code sees a consistent shape.

Parameters:

Name Type Description Default
alpha float

Foreground opacity in [0, 1]. Default 0.6.

0.6
mode str

Blend mode. One of "alpha", "multiply", or "screen". Default "alpha".

'alpha'

Examples:

>>> import geoops as gz
>>> # Overlay a cloud mask at 50 % opacity.
>>> blended = gz.viz.Overlay(alpha=0.5)(rgb_uint8, cloud_rgba)
Source code in packages/geotoolz-ops/src/geoops/viz/_src/operators.py
class Overlay(Operator):
    """Blend background and foreground GeoArrays on the same grid.

    Two-input Operator: ``Overlay()(background, foreground)``. When
    both carriers are georeferenced they must share ``transform`` and
    ``crs`` (this is a viz primitive, not a reprojector); plain
    ``np.ndarray`` carriers skip the metadata check and blend on pixel
    grids alone, returning the background's carrier kind. Output is
    always 4-band ``uint8`` RGBA — even when ``alpha=0`` — so
    downstream code sees a consistent shape.

    Args:
        alpha: Foreground opacity in ``[0, 1]``. Default ``0.6``.
        mode: Blend mode. One of ``"alpha"``, ``"multiply"``, or
            ``"screen"``. Default ``"alpha"``.

    Examples:
        >>> import geoops as gz
        >>> # Overlay a cloud mask at 50 % opacity.
        >>> blended = gz.viz.Overlay(alpha=0.5)(rgb_uint8, cloud_rgba)
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # two carriers blended per pixel
    coupling: ClassVar[Coupling] = Coupling()

    def __init__(self, *, alpha: float = 0.6, mode: str = "alpha") -> None:
        self.alpha = alpha
        self.mode = mode

    def _apply(
        self,
        background: GeoArray | np.ndarray,
        foreground: GeoArray | np.ndarray,
    ) -> GeoArray | np.ndarray:
        if (
            isinstance(background, GeoArray)
            and isinstance(foreground, GeoArray)
            and (
                not np.array_equal(
                    np.asarray(background.transform), np.asarray(foreground.transform)
                )
                or str(background.crs) != str(foreground.crs)
            )
        ):
            raise ValueError("background and foreground must share transform and CRS")
        if self.alpha == 0.0:
            # Consistency: always return RGBA, even when no blending occurs.
            return wrap_like(
                background, ensure_rgba(np.asarray(background)), fill_value=0
            )
        out = blend_rgba(
            np.asarray(background),
            np.asarray(foreground),
            alpha=self.alpha,
            mode=self.mode,
        )
        return wrap_like(background, out, fill_value=0)

RGBRecipe

Bases: Operator

Build a display RGB from three band expressions with fixed stretches.

The operational satellite RGB products (the CIRA / EUMETSAT "quick guide" composites: day cloud phase, fire temperature, natural colour, dust, air mass, ...) are all one recipe: each colour channel is a band or a small band expression, linearly stretched between a fixed vmin and vmax, clipped to [0, 1] and raised to 1 / gamma. This operator is that recipe; see :func:geoops.viz.rgb_recipe for the maths.

red / green / blue are each an integer band position, a band name resolved against the carrier's attrs (band_names, then descriptions, then bands), or an arithmetic expression over band names in :class:geoops.spectral.BandMath grammar ("0.45 * C02 + 0.10 * C03 + 0.45 * C01"). Invalid input pixels (non-finite or equal to the fill) become NaN per band, so a channel is NaN wherever one of its bands is. Output is (3, H, W) float32 in [0, 1] with band_names=("red", "green", "blue") and NaN fill; follow with StretchToUint8 or multiply by 255 for bytes.

Parameters:

Name Type Description Default
red BandRef

Red channel: band position, band name or expression.

required
green BandRef

Green channel.

required
blue BandRef

Blue channel.

required
vmin float | Sequence[float]

Value mapped to 0 — one for all channels or one per channel. Set above vmax to invert a channel. Default 0.0.

0.0
vmax float | Sequence[float]

Value mapped to 1. Default 1.0.

1.0
gamma float | Sequence[float]

Display gamma (> 0), one or per channel. Default 1.0.

1.0
dim str

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

'band'
axis int | None

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

None

Raises:

Type Description
ValueError

A vmin equals its vmax, a gamma is not positive, or a per-channel sequence does not have 3 entries.

Examples:

>>> import geoops as gz
>>> # CIRA day cloud phase distinction from ABI channels.
>>> dcp = gz.viz.RGBRecipe(
...     red="C13", green="C02", blue="C05",
...     vmin=(280.65, 0.0, 0.01), vmax=(219.65, 0.78, 0.59),
... )
>>> rgb = dcp(abi_stack)  # (3, H, W) float32 in [0, 1]
Source code in packages/geotoolz-ops/src/geoops/viz/_src/operators.py
class RGBRecipe(Operator):
    """Build a display RGB from three band expressions with fixed stretches.

    The operational satellite RGB products (the CIRA / EUMETSAT "quick
    guide" composites: day cloud phase, fire temperature, natural colour,
    dust, air mass, ...) are all one recipe: each colour channel is a band
    or a small band expression, linearly stretched between a fixed
    ``vmin`` and ``vmax``, clipped to ``[0, 1]`` and raised to
    ``1 / gamma``. This operator is that recipe; see
    :func:`geoops.viz.rgb_recipe` for the maths.

    ``red`` / ``green`` / ``blue`` are each an integer band position, a band
    name resolved against the carrier's ``attrs`` (``band_names``, then
    ``descriptions``, then ``bands``), or an arithmetic expression over band
    names in :class:`geoops.spectral.BandMath` grammar
    (``"0.45 * C02 + 0.10 * C03 + 0.45 * C01"``). Invalid input pixels
    (non-finite or equal to the fill) become ``NaN`` per band, so a channel
    is ``NaN`` wherever one of its bands is. Output is ``(3, H, W)``
    ``float32`` in ``[0, 1]`` with ``band_names=("red", "green", "blue")``
    and ``NaN`` fill; follow with ``StretchToUint8`` or multiply by 255 for
    bytes.

    Args:
        red: Red channel: band position, band name or expression.
        green: Green channel.
        blue: Blue channel.
        vmin: Value mapped to 0 — one for all channels or one per channel.
            Set above ``vmax`` to invert a channel. Default ``0.0``.
        vmax: Value mapped to 1. Default ``1.0``.
        gamma: Display gamma (``> 0``), one or per channel. Default ``1.0``.
        dim: Name of the band dim (default ``"band"``); its position is read
            from the carrier's dims.
        axis: Deprecated: the band axis position. ``-3`` maps to
            ``dim="band"``; removed in the next minor release.

    Raises:
        ValueError: A ``vmin`` equals its ``vmax``, a gamma is not
            positive, or a per-channel sequence does not have 3 entries.

    Examples:
        >>> import geoops as gz
        >>> # CIRA day cloud phase distinction from ABI channels.
        >>> dcp = gz.viz.RGBRecipe(
        ...     red="C13", green="C02", blue="C05",
        ...     vmin=(280.65, 0.0, 0.01), vmax=(219.65, 0.78, 0.59),
        ... )
        >>> rgb = dcp(abi_stack)  # (3, H, W) float32 in [0, 1]
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # three band expressions
    coupling: ClassVar[Coupling] = Coupling(couples={"band"}, effects={"band": "mix"})

    def __init__(
        self,
        *,
        red: BandRef,
        green: BandRef,
        blue: BandRef,
        vmin: float | Sequence[float] = 0.0,
        vmax: float | Sequence[float] = 1.0,
        gamma: float | Sequence[float] = 1.0,
        dim: str = "band",
        axis: int | None = None,
    ) -> None:
        self.red = red
        self.green = green
        self.blue = blue
        self.vmin = _per_channel(vmin, "vmin")
        self.vmax = _per_channel(vmax, "vmax")
        self.gamma = _per_channel(gamma, "gamma")
        self.dim = band_dim(dim, axis, "RGBRecipe")
        if any(lo == hi for lo, hi in zip(self.vmin, self.vmax, strict=True)):
            raise ValueError(
                f"vmin and vmax must differ per channel; got {self.vmin}, {self.vmax}."
            )
        if any(g <= 0 for g in self.gamma):
            raise ValueError(f"gamma must be positive; got {self.gamma}.")

    @over_frames
    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        axis = dim_axis(gt, self.dim, name="RGBRecipe")
        arr = np.asarray(gt)
        work = np.where(invalid_values(gt), np.nan, arr.astype(np.float32))
        names = band_names(gt) or []
        bands = {
            name: np.take(work, idx, axis=axis)
            for idx, name in enumerate(names)
            if name is not None
        }
        channels = np.stack(
            [
                self._channel(ref, work, names, bands, axis)
                for ref in (self.red, self.green, self.blue)
            ]
        )
        out = rgb_recipe(channels, vmin=self.vmin, vmax=self.vmax, gamma=self.gamma)
        return wrap_like(
            gt,
            np.moveaxis(out, 0, axis) if arr.ndim > 2 else out,
            fill_value=np.nan,
            attrs={"band_names": ("red", "green", "blue")},
        )

    def _channel(
        self,
        ref: BandRef,
        work: np.ndarray,
        names: list[str | None],
        bands: Mapping[str, np.ndarray],
        axis: int,
    ) -> np.ndarray:
        if isinstance(ref, int | np.integer):
            return np.take(work, int(ref), axis=axis)
        if ref in bands:
            return bands[ref]
        if not bands:
            raise ValueError(
                f"RGBRecipe: {ref!r} needs band names in the carrier's attrs."
            )
        value = np.asarray(evaluate_band_math(ref, bands), dtype=np.float32)
        return np.broadcast_to(value, next(iter(bands.values())).shape)

    def get_config(self) -> dict[str, Any]:
        return {
            "red": self.red,
            "green": self.green,
            "blue": self.blue,
            "vmin": list(self.vmin),
            "vmax": list(self.vmax),
            "gamma": list(self.gamma),
            "dim": self.dim,
        }

SWIRComposite

Bases: Composite

Build a SWIR2-NIR-red composite.

Burn-scar / urban / geology visualisation preset where SWIR2 is rendered as red. Equivalent to Composite(bands=[swir2, nir, red]).

Parameters:

Name Type Description Default
swir2 BandRef

SWIR2 band reference (rendered as red).

required
nir BandRef

NIR band reference (rendered as green).

required
red BandRef

Red band reference (rendered as blue).

required
dim str

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

'band'
axis int | None

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

None

Examples:

>>> import geoops as gz
>>> # Landsat-8 SWIR2/NIR/red burn-scar composite (7/5/4).
>>> vis = gz.viz.SWIRComposite(swir2="B7", nir="B5", red="B4")(l8)
Source code in packages/geotoolz-ops/src/geoops/viz/_src/operators.py
class SWIRComposite(Composite):
    """Build a SWIR2-NIR-red composite.

    Burn-scar / urban / geology visualisation preset where SWIR2 is
    rendered as red. Equivalent to ``Composite(bands=[swir2, nir, red])``.

    Args:
        swir2: SWIR2 band reference (rendered as red).
        nir: NIR band reference (rendered as green).
        red: Red band reference (rendered as blue).
        dim: Name of the band dim (default ``"band"``); its position is read
            from the carrier's dims.
        axis: Deprecated: the band axis position. ``-3`` maps to
            ``dim="band"``; removed in the next minor release.

    Examples:
        >>> import geoops as gz
        >>> # Landsat-8 SWIR2/NIR/red burn-scar composite (7/5/4).
        >>> vis = gz.viz.SWIRComposite(swir2="B7", nir="B5", red="B4")(l8)
    """

    def __init__(
        self,
        *,
        swir2: BandRef,
        nir: BandRef,
        red: BandRef,
        dim: str = "band",
        axis: int | None = None,
    ) -> None:
        super().__init__(bands=[swir2, nir, red], dim=dim, axis=axis)
        self.swir2 = swir2
        self.nir = nir
        self.red = red

    def get_config(self) -> dict[str, Any]:
        return {
            "swir2": self.swir2,
            "nir": self.nir,
            "red": self.red,
            "dim": self.dim,
        }

ShadedRelief

Bases: Operator

Apply an elevation colormap and modulate RGB with hillshade.

The composite terrain visualisation: run the DEM through ApplyColormap and modulate the RGB channels by a Hillshade so the result reads like a cartographer's shaded-relief map. Alpha channel is preserved from the colormap, so nodata DEM pixels stay fully transparent (see ApplyColormap / Hillshade). Geo-dependent: the hillshade pixel size comes from the carrier's transform, so a georeferenced GeoArray input in a projected CRS is required (a geographic CRS raises ValueError; see Hillshade).

Parameters:

Name Type Description Default
azimuth_deg float

Sun azimuth (degrees clockwise from north). Default 315.

315.0
altitude_deg float

Sun elevation (degrees). Default 45.

45.0
colormap str

Name of the elevation colormap. Default "terrain".

'terrain'
z_factor float

Vertical exaggeration for the hillshade. Default 1.0.

1.0

Examples:

>>> import geoops as gz
>>> shaded = gz.viz.ShadedRelief(colormap="terrain")(dem_gt)
Source code in packages/geotoolz-ops/src/geoops/viz/_src/operators.py
class ShadedRelief(Operator):
    """Apply an elevation colormap and modulate RGB with hillshade.

    The composite terrain visualisation: run the DEM through
    `ApplyColormap` and modulate the RGB channels by a `Hillshade`
    so the result reads like a cartographer's shaded-relief map.
    Alpha channel is preserved from the colormap, so nodata DEM pixels
    stay fully transparent (see `ApplyColormap` / `Hillshade`). Geo-dependent: the
    hillshade pixel size comes from the carrier's ``transform``, so a
    georeferenced GeoArray input in a projected CRS is required (a
    geographic CRS raises ``ValueError``; see `Hillshade`).

    Args:
        azimuth_deg: Sun azimuth (degrees clockwise from north).
            Default ``315``.
        altitude_deg: Sun elevation (degrees). Default ``45``.
        colormap: Name of the elevation colormap. Default ``"terrain"``.
        z_factor: Vertical exaggeration for the hillshade. Default
            ``1.0``.

    Examples:
        >>> import geoops as gz
        >>> shaded = gz.viz.ShadedRelief(colormap="terrain")(dem_gt)
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # hillshade, then a colour map scaled over the scene
    coupling: ClassVar[Coupling] = Coupling(couples={"space"}, reach=None)

    def __init__(
        self,
        *,
        azimuth_deg: float = 315.0,
        altitude_deg: float = 45.0,
        colormap: str = "terrain",
        z_factor: float = 1.0,
    ) -> None:
        self.azimuth_deg = azimuth_deg
        self.altitude_deg = altitude_deg
        self.colormap = colormap
        self.z_factor = z_factor

    @over_frames
    def _apply(self, gt: GeoArray) -> GeoArray:
        require_geoarray(gt, "ShadedRelief")
        rgba = np.asarray(ApplyColormap(name=self.colormap)(gt)).copy()
        shade = (
            np.asarray(
                Hillshade(
                    azimuth_deg=self.azimuth_deg,
                    altitude_deg=self.altitude_deg,
                    z_factor=self.z_factor,
                )(gt),
                dtype=np.float32,
            )
            / 255.0
        )
        rgba[:3] = np.rint(rgba[:3].astype(np.float32) * shade).astype(np.uint8)
        return wrap_like(gt, rgba, fill_value=0)

StretchToUint8

Bases: Operator

Percentile-stretch display data to uint8.

Exactly :class:geoops.radiometry.PercentileClip (same lower / upper / reduce_axes) followed by a rounded byte cast, so the result is ready for PIL / matplotlib. Use PercentileClip directly if you instead need the [0, 1] floats for further math. Metadata-independent: plain np.ndarray carriers pass through as plain arrays.

Nodata pixels (any band non-finite or equal to the carrier's fill_value) are excluded from the percentiles, so a -9999 fill cannot dominate the stretch, and are written as 0 -- the output's fill_value.

Parameters:

Name Type Description Default
lower float

Lower percentile. Default 2.0.

2.0
upper float

Upper percentile. Default 98.0; must exceed lower.

98.0
reduce_axes int | tuple[int, ...] | None

Axes the percentiles are computed over. Default (-2, -1) stretches each band (and frame) independently; None uses one global pair of thresholds.

(-2, -1)

Examples:

>>> import geoops as gz
>>> # Classic satellite display pipeline.
>>> pipe = (
...     gz.viz.TrueColor(red="B04", green="B03", blue="B02")
...     | gz.viz.StretchToUint8(lower=2.0, upper=98.0)
... )
>>> rgb_uint8 = pipe(s2_geotensor)
Source code in packages/geotoolz-ops/src/geoops/viz/_src/operators.py
class StretchToUint8(Operator):
    """Percentile-stretch display data to ``uint8``.

    Exactly :class:`geoops.radiometry.PercentileClip` (same ``lower`` /
    ``upper`` / ``reduce_axes``) followed by a rounded byte cast, so the result
    is ready for PIL / matplotlib. Use ``PercentileClip`` directly if you
    instead need the ``[0, 1]`` floats for further math.
    Metadata-independent: plain ``np.ndarray`` carriers pass through as
    plain arrays.

    Nodata pixels (any band non-finite or equal to the carrier's
    ``fill_value``) are excluded from the percentiles, so a
    ``-9999`` fill cannot dominate the stretch, and are written as ``0``
    -- the output's ``fill_value``.

    Args:
        lower: Lower percentile. Default ``2.0``.
        upper: Upper percentile. Default ``98.0``; must exceed ``lower``.
        reduce_axes: Axes the percentiles are computed over. Default
            ``(-2, -1)`` stretches each band (and frame) independently;
            ``None`` uses one global pair of thresholds.

    Examples:
        >>> import geoops as gz
        >>> # Classic satellite display pipeline.
        >>> pipe = (
        ...     gz.viz.TrueColor(red="B04", green="B03", blue="B02")
        ...     | gz.viz.StretchToUint8(lower=2.0, upper=98.0)
        ... )
        >>> rgb_uint8 = pipe(s2_geotensor)
    """

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

    def __init__(
        self,
        *,
        lower: float = 2.0,
        upper: float = 98.0,
        reduce_axes: int | tuple[int, ...] | None = (-2, -1),
    ) -> None:
        self.lower = lower
        self.upper = upper
        self.reduce_axes = as_tuple(reduce_axes)

    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        # Nodata comes back NaN from PercentileClip and casts to the 0 fill.
        stretched = PercentileClip(
            lower=self.lower, upper=self.upper, reduce_axes=self.reduce_axes
        )(gt)
        return wrap_like(gt, _unit_to_uint8(stretched), fill_value=0)

TrueColor

Bases: Composite

Build an RGB composite from explicit red, green, and blue band refs.

Convenience wrapper over Composite that keeps the band ordering self-documenting. Output is shaped (3, H, W) in (R, G, B) order — the matplotlib / PIL display convention. Geo-metadata is preserved.

Parameters:

Name Type Description Default
red BandRef

Red-band reference (int index or string name).

required
green BandRef

Green-band reference.

required
blue BandRef

Blue-band reference.

required
dim str

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

'band'
axis int | None

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

None

Examples:

>>> import geoops as gz
>>> # Named Sentinel-2 natural-colour RGB.
>>> rgb = gz.viz.TrueColor(red="B04", green="B03", blue="B02")(s2)
>>> # Stretched display-ready pipeline.
>>> display = (
...     gz.viz.TrueColor(red="B04", green="B03", blue="B02")
...     | gz.viz.StretchToUint8(lower=2.0, upper=98.0)
... )
>>> rgb_uint8 = display(s2)
Source code in packages/geotoolz-ops/src/geoops/viz/_src/operators.py
class TrueColor(Composite):
    """Build an RGB composite from explicit red, green, and blue band refs.

    Convenience wrapper over `Composite` that keeps the band ordering
    self-documenting. Output is shaped ``(3, H, W)`` in (R, G, B) order
    — the matplotlib / PIL display convention. Geo-metadata is
    preserved.

    Args:
        red: Red-band reference (int index or string name).
        green: Green-band reference.
        blue: Blue-band reference.
        dim: Name of the band dim (default ``"band"``); its position is read
            from the carrier's dims.
        axis: Deprecated: the band axis position. ``-3`` maps to
            ``dim="band"``; removed in the next minor release.

    Examples:
        >>> import geoops as gz
        >>> # Named Sentinel-2 natural-colour RGB.
        >>> rgb = gz.viz.TrueColor(red="B04", green="B03", blue="B02")(s2)
        >>> # Stretched display-ready pipeline.
        >>> display = (
        ...     gz.viz.TrueColor(red="B04", green="B03", blue="B02")
        ...     | gz.viz.StretchToUint8(lower=2.0, upper=98.0)
        ... )
        >>> rgb_uint8 = display(s2)
    """

    def __init__(
        self,
        *,
        red: BandRef,
        green: BandRef,
        blue: BandRef,
        dim: str = "band",
        axis: int | None = None,
    ) -> None:
        super().__init__(bands=[red, green, blue], dim=dim, axis=axis)
        self.red = red
        self.green = green
        self.blue = blue

    def get_config(self) -> dict[str, Any]:
        return {
            "red": self.red,
            "green": self.green,
            "blue": self.blue,
            "dim": self.dim,
        }

blend_rgba(background, foreground, *, alpha=0.6, mode='alpha')

Blend two display images and return uint8 RGBA.

Both inputs are first promoted through :func:ensure_rgba (2-D grayscale, 3-band RGB, or 4-band RGBA in). The foreground's alpha channel is scaled by alpha and composed over the background using source-over alpha composition, so partially transparent layers accumulate opacity correctly.

Parameters:

Name Type Description Default
background Num[ndarray, 'h w'] | Num[ndarray, 'c h w']

Bottom layer — (H, W), (3, H, W), or (4, H, W).

required
foreground Num[ndarray, 'h w'] | Num[ndarray, 'c h w']

Top layer on the same pixel grid.

required
alpha float

Global foreground opacity in [0, 1]. 0 returns the background (as RGBA) untouched. Default 0.6.

0.6
mode str

Blend mode for the RGB channels — "alpha" (normal source-over), "multiply", or "screen". Default "alpha".

'alpha'

Returns:

Type Description
UInt8[ndarray, '4 h w']

(4, H, W) uint8 RGBA composite.

Raises:

Type Description
ValueError

If alpha is outside [0, 1], the spatial grids differ, or mode is not a supported blend mode.

Source code in packages/geotoolz-ops/src/geoops/viz/_src/array.py
def blend_rgba(
    background: Num[np.ndarray, "h w"] | Num[np.ndarray, "c h w"],
    foreground: Num[np.ndarray, "h w"] | Num[np.ndarray, "c h w"],
    *,
    alpha: float = 0.6,
    mode: str = "alpha",
) -> UInt8[np.ndarray, "4 h w"]:
    """Blend two display images and return uint8 RGBA.

    Both inputs are first promoted through :func:`ensure_rgba` (2-D
    grayscale, 3-band RGB, or 4-band RGBA in). The foreground's alpha
    channel is scaled by ``alpha`` and composed over the background
    using source-over alpha composition, so partially transparent
    layers accumulate opacity correctly.

    Args:
        background: Bottom layer — ``(H, W)``, ``(3, H, W)``, or
            ``(4, H, W)``.
        foreground: Top layer on the same pixel grid.
        alpha: Global foreground opacity in ``[0, 1]``. ``0`` returns
            the background (as RGBA) untouched. Default ``0.6``.
        mode: Blend mode for the RGB channels — ``"alpha"`` (normal
            source-over), ``"multiply"``, or ``"screen"``. Default
            ``"alpha"``.

    Returns:
        ``(4, H, W)`` ``uint8`` RGBA composite.

    Raises:
        ValueError: If ``alpha`` is outside ``[0, 1]``, the spatial
            grids differ, or ``mode`` is not a supported blend mode.
    """
    if not 0.0 <= alpha <= 1.0:
        raise ValueError(f"blend_rgba requires alpha in [0, 1]; got {alpha}")
    bg = ensure_rgba(background)
    fg = ensure_rgba(foreground)
    if bg.shape[-2:] != fg.shape[-2:]:
        raise ValueError(
            f"background and foreground grids must match; got {bg.shape=} {fg.shape=}"
        )
    if alpha == 0.0:
        return bg

    bg_f = bg.astype(np.float32) / 255.0
    fg_f = fg.astype(np.float32) / 255.0
    fg_alpha = np.clip(fg_f[3:4] * alpha, 0.0, 1.0)
    if mode == "alpha":
        rgb = fg_f[:3] * fg_alpha + bg_f[:3] * (1.0 - fg_alpha)
    elif mode == "multiply":
        rgb = (bg_f[:3] * fg_f[:3]) * fg_alpha + bg_f[:3] * (1.0 - fg_alpha)
    elif mode == "screen":
        screened = 1.0 - (1.0 - bg_f[:3]) * (1.0 - fg_f[:3])
        rgb = screened * fg_alpha + bg_f[:3] * (1.0 - fg_alpha)
    else:
        expected = "'alpha', 'multiply', or 'screen'"
        raise ValueError(f"unsupported overlay mode {mode!r}; expected {expected}")
    # Source-over alpha composition (foreground on top of background):
    # out_alpha = fg_alpha + bg_alpha * (1 - fg_alpha). Equivalent to
    # max(fg_alpha, bg_alpha) only when one of them is 0 or 1; mixing
    # two partially transparent layers must accumulate opacity.
    out_alpha = fg_alpha + bg_f[3:4] * (1.0 - fg_alpha)
    return _unit_to_uint8(np.concatenate([rgb, out_alpha], axis=0))

ensure_rgba(arr, *, name='ensure_rgba')

Return arr as a four-band uint8 RGBA image.

Accepts (H, W) grayscale (replicated to RGB), (3, H, W) RGB, or (4, H, W) RGBA. Float (or boolean) inputs whose finite values are all <= 1 are treated as [0, 1] fractions and scaled to byte range; other numeric inputs are treated as already display-scaled and clipped into [0, 255]. The decision is made on the input values alone; RGB / grayscale inputs then get an opaque (255) alpha plane. NaNs map to 0.

Parameters:

Name Type Description Default
arr Num[ndarray, 'h w'] | Num[ndarray, 'c h w']

The display array.

required
name str

Caller name that prefixes the error message (an operator passes its own).

'ensure_rgba'

Raises:

Type Description
ValueError

If arr is not 2-D or a 3-/4-band cube.

Source code in packages/geotoolz-ops/src/geoops/viz/_src/array.py
def ensure_rgba(
    arr: Num[np.ndarray, "h w"] | Num[np.ndarray, "c h w"],
    *,
    name: str = "ensure_rgba",
) -> UInt8[np.ndarray, "4 h w"]:
    """Return ``arr`` as a four-band uint8 RGBA image.

    Accepts ``(H, W)`` grayscale (replicated to RGB), ``(3, H, W)`` RGB,
    or ``(4, H, W)`` RGBA. Float (or boolean) inputs whose finite values
    are all ``<= 1`` are treated as ``[0, 1]`` fractions and scaled to
    byte range; other numeric inputs are treated as already
    display-scaled and clipped into ``[0, 255]``. The decision is made on
    the input values alone; RGB / grayscale inputs then get an opaque
    (255) alpha plane. NaNs map to 0.

    Args:
        arr: The display array.
        name: Caller name that prefixes the error message (an operator
            passes its own).

    Raises:
        ValueError: If ``arr`` is not 2-D or a 3-/4-band cube.
    """
    values = np.asarray(arr)
    if values.ndim == 2:
        values = np.repeat(values[None, ...], 3, axis=0)
    if values.ndim != 3:
        raise ValueError(
            f"{name}: display arrays must be 2D, RGB, or RGBA; got shape {values.shape}"
        )
    if values.shape[0] not in (3, 4):
        raise ValueError(
            f"{name}: display arrays must have 3 or 4 bands; got {values.shape[0]}"
        )
    # Decide byte-vs-fraction scaling from the *input* values, before any
    # opaque alpha plane is added (a 255 alpha would otherwise make every
    # float [0, 1] RGB / grayscale input look byte-scaled -> black).
    if values.dtype == np.uint8:
        rgb_bytes = values
    else:
        is_fractional = values.dtype == np.bool_ or np.issubdtype(
            values.dtype, np.floating
        )
        finite = np.isfinite(values)
        max_value = float(np.max(values[finite])) if finite.any() else 0.0
        scaled = (
            values.astype(np.float64) * 255.0
            if is_fractional and max_value <= 1.0
            else values.astype(np.float64)
        )
        rgb_bytes = np.rint(np.nan_to_num(np.clip(scaled, 0.0, 255.0), nan=0.0)).astype(
            np.uint8
        )
    if rgb_bytes.shape[0] == 4:
        return rgb_bytes.copy()
    alpha = np.full((1, *rgb_bytes.shape[-2:]), 255, dtype=np.uint8)
    return np.concatenate([rgb_bytes, alpha], axis=0)

gamma_correct_display(arr, *, gamma=1.0, inplace_norm=True)

Apply power-law gamma correction to display-range arrays.

Gamma is a unit-interval operation: the math out = clip(arr, 0, 1) ** (1 / gamma) (via :func:geoops.radiometry.gamma_correct) is only meaningful when the input is normalised to [0, 1]. Display arrays, however, arrive in two flavours — float in [0, 1] or integer in [0, 255] (uint8) / [0, 65535] (uint16). Without normalisation, an integer input is raised to 1 / gamma directly, giving e.g. 256 ** 0.5 = 16 — not a display-correct gamma transform.

With inplace_norm=True (the default), integer inputs are scaled by their dtype maximum into [0, 1], the gamma exponent is applied, and the result is rounded back to the original integer dtype's full range. Floating-point inputs are clipped to [0, 1] (the display range) before the exponent; NaN stays NaN.

Parameters:

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

Display array. Integer (uint8 / uint16) or float.

required
gamma float

Strictly positive gamma factor. > 1 brightens midtones; < 1 darkens them.

1.0
inplace_norm bool

When True (default), normalise integer inputs to [0, 1] before the exponent and scale back. When False, integer inputs get arr ** (1 / gamma) directly (a float result) — only set this if you've already normalised upstream. Float inputs are unaffected.

True

Returns:

Type Description
Num[ndarray, '*dims']

Gamma-corrected array of the same shape; same dtype as arr

Num[ndarray, '*dims']

for float input and for integer input with inplace_norm.

Raises:

Type Description
ValueError

If gamma <= 0.

Source code in packages/geotoolz-ops/src/geoops/viz/_src/array.py
def gamma_correct_display(
    arr: Num[np.ndarray, "*dims"], *, gamma: float = 1.0, inplace_norm: bool = True
) -> Num[np.ndarray, "*dims"]:
    """Apply power-law gamma correction to display-range arrays.

    Gamma is a unit-interval operation: the math
    ``out = clip(arr, 0, 1) ** (1 / gamma)`` (via
    :func:`geoops.radiometry.gamma_correct`) is only meaningful when
    the input is normalised to ``[0, 1]``. Display arrays, however,
    arrive in two flavours — float in ``[0, 1]`` *or* integer in
    ``[0, 255]`` (uint8) / ``[0, 65535]`` (uint16). Without
    normalisation, an integer input is raised to ``1 / gamma`` directly,
    giving e.g. ``256 ** 0.5 = 16`` — not a display-correct gamma
    transform.

    With ``inplace_norm=True`` (the default), integer inputs are scaled
    by their dtype maximum into ``[0, 1]``, the gamma exponent is
    applied, and the result is rounded back to the original integer
    dtype's full range. Floating-point inputs are clipped to ``[0, 1]``
    (the display range) before the exponent; NaN stays NaN.

    Args:
        arr: Display array. Integer (``uint8`` / ``uint16``) or float.
        gamma: Strictly positive gamma factor. ``> 1`` brightens
            midtones; ``< 1`` darkens them.
        inplace_norm: When ``True`` (default), normalise integer inputs
            to ``[0, 1]`` before the exponent and scale back. When
            ``False``, integer inputs get ``arr ** (1 / gamma)`` directly
            (a float result) — only set this if you've already
            normalised upstream. Float inputs are unaffected.

    Returns:
        Gamma-corrected array of the same shape; same dtype as ``arr``
        for float input and for integer input with ``inplace_norm``.

    Raises:
        ValueError: If ``gamma <= 0``.
    """
    if not np.issubdtype(arr.dtype, np.integer):
        return gamma_correct(np.clip(arr, 0.0, 1.0), gamma=gamma)
    if not inplace_norm:
        return gamma_correct(arr, gamma=gamma)
    dtype_max = float(np.iinfo(arr.dtype).max)
    normed = np.clip(arr.astype(np.float64) / dtype_max, 0.0, 1.0)
    corrected = gamma_correct(normed, gamma=gamma)
    return np.rint(np.clip(corrected * dtype_max, 0.0, dtype_max)).astype(arr.dtype)

hillshade(dem, *, x_resolution=1.0, y_resolution=1.0, azimuth_deg=315.0, altitude_deg=45.0, z_factor=1.0, valid=None)

Compute GDAL-style hillshade as a single uint8 band.

Slope and aspect are derived from the DEM gradient (in map units, via x_resolution / y_resolution) and combined with a sun position to give the classic terrain-shading effect. Illumination is clipped to [0, 1] and scaled to byte range. The DEM is assumed north-up (row 0 is the northern edge, as in a standard geotransform), so for a planar DEM the result matches matplotlib.colors.LightSource(azimuth_deg, altitude_deg).hillshade (up to byte quantization; matplotlib additionally contrast-stretches non-constant outputs).

Parameters:

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

Elevation map, (H, W) or (1, H, W), in the same linear units as the resolutions (after z_factor).

required
x_resolution float

Pixel width in map units. Default 1.0.

1.0
y_resolution float

Pixel height in map units. Default 1.0.

1.0
azimuth_deg float

Sun azimuth in degrees clockwise from north. Default 315 (NW — the cartographic convention).

315.0
altitude_deg float

Sun elevation in degrees above the horizon. Default 45. Values >= 90 short-circuit to a flat fully lit (255) image.

45.0
z_factor float

Vertical exaggeration applied to the DEM before the gradient. Default 1.0.

1.0
valid Bool[ndarray, 'h w'] | None

Optional (H, W) mask of valid DEM pixels. Invalid pixels never enter a neighbour's gradient (a one-sided difference is used instead, or a flat 0 slope when both neighbours along an axis are invalid) and are written as 0 in the output. None (default) treats every pixel as valid.

None

Returns:

Type Description
UInt8[ndarray, 'h w']

(H, W) uint8 shading band (0 = fully shaded, 255 =

UInt8[ndarray, 'h w']

fully lit).

Raises:

Type Description
ValueError

If dem is not a single-band map.

Source code in packages/geotoolz-ops/src/geoops/viz/_src/array.py
def hillshade(
    dem: Num[np.ndarray, "h w"] | Num[np.ndarray, "1 h w"],
    *,
    x_resolution: float = 1.0,
    y_resolution: float = 1.0,
    azimuth_deg: float = 315.0,
    altitude_deg: float = 45.0,
    z_factor: float = 1.0,
    valid: Bool[np.ndarray, "h w"] | None = None,
) -> UInt8[np.ndarray, "h w"]:
    """Compute GDAL-style hillshade as a single ``uint8`` band.

    Slope and aspect are derived from the DEM gradient (in map units,
    via ``x_resolution`` / ``y_resolution``) and combined with a sun
    position to give the classic terrain-shading effect. Illumination
    is clipped to ``[0, 1]`` and scaled to byte range. The DEM is
    assumed north-up (row 0 is the northern edge, as in a standard
    geotransform), so for a planar DEM the result matches
    ``matplotlib.colors.LightSource(azimuth_deg, altitude_deg).hillshade``
    (up to byte quantization; matplotlib additionally contrast-stretches
    non-constant outputs).

    Args:
        dem: Elevation map, ``(H, W)`` or ``(1, H, W)``, in the same
            linear units as the resolutions (after ``z_factor``).
        x_resolution: Pixel width in map units. Default ``1.0``.
        y_resolution: Pixel height in map units. Default ``1.0``.
        azimuth_deg: Sun azimuth in degrees clockwise from north.
            Default ``315`` (NW — the cartographic convention).
        altitude_deg: Sun elevation in degrees above the horizon.
            Default ``45``. Values ``>= 90`` short-circuit to a flat
            fully lit (255) image.
        z_factor: Vertical exaggeration applied to the DEM before the
            gradient. Default ``1.0``.
        valid: Optional ``(H, W)`` mask of valid DEM pixels. Invalid
            pixels never enter a neighbour's gradient (a one-sided
            difference is used instead, or a flat ``0`` slope when both
            neighbours along an axis are invalid) and are written as
            ``0`` in the output. ``None`` (default) treats every pixel
            as valid.

    Returns:
        ``(H, W)`` ``uint8`` shading band (0 = fully shaded, 255 =
        fully lit).

    Raises:
        ValueError: If ``dem`` is not a single-band map.
    """
    band = single_band(dem, name="hillshade").astype(np.float64, copy=False)
    invalid = None if valid is None else ~np.asarray(valid, dtype=bool)
    if invalid is not None and not invalid.any():
        invalid = None
    if altitude_deg >= 90.0:
        out = np.full(band.shape, 255, dtype=np.uint8)
        if invalid is not None:
            out[invalid] = 0
        return out

    if invalid is None:
        dy, dx = np.gradient(band * z_factor, abs(y_resolution), abs(x_resolution))
    else:
        masked = np.where(invalid, np.nan, band * z_factor)
        dy = _nan_gradient(masked, abs(y_resolution), axis=0)
        dx = _nan_gradient(masked, abs(x_resolution), axis=1)
    slope = np.pi / 2.0 - np.arctan(np.hypot(dx, dy))
    # Aspect = math angle (CCW from east) of the surface normal's
    # horizontal part, (-dz/deast, -dz/dnorth). `dy` is the gradient
    # along rows, i.e. towards the *south* (row 0 is north), so
    # dz/dnorth = -dy and the normal points along (-dx, dy).
    aspect = np.arctan2(dy, -dx)
    # Convert geographic azimuth (clockwise from north) to the mathematical
    # angle expected by the aspect term (counter-clockwise from east).
    azimuth = np.deg2rad(360.0 - azimuth_deg + 90.0)
    altitude = np.deg2rad(altitude_deg)
    shaded = np.sin(altitude) * np.sin(slope) + np.cos(altitude) * np.cos(
        slope
    ) * np.cos(azimuth - aspect)
    out = _unit_to_uint8(np.clip(shaded, 0.0, 1.0))
    if invalid is not None:
        out[invalid] = 0
    return out

rgb_recipe(channels, *, vmin=0.0, vmax=1.0, gamma=1.0)

Stretch and gamma-correct three channels into a display RGB.

Each channel c is mapped through a fixed linear stretch and a power law — the "RGB recipe" form of the operational satellite RGB guides:

.. math::

y_c \;=\; \operatorname{clip}\!\Bigl(
    \frac{x_c - v_{\min,c}}{v_{\max,c} - v_{\min,c}}, 0, 1
\Bigr)^{1/\gamma_c}

A vmin above vmax inverts the channel (colder brightness temperatures brighter, for instance). NaN inputs stay NaN.

Parameters:

Name Type Description Default
channels Float[ndarray, '3 h w']

The red, green and blue inputs stacked on the first axis.

required
vmin float | tuple[float, float, float]

Value mapped to 0, per channel or one for all.

0.0
vmax float | tuple[float, float, float]

Value mapped to 1, per channel or one for all.

1.0
gamma float | tuple[float, float, float]

Gamma per channel or one for all (> 0; > 1 brightens midtones).

1.0

Returns:

Type Description
Float[ndarray, '3 h w']

float32 array of the same shape, in [0, 1] (NaN kept).

Raises:

Type Description
ValueError

channels does not have 3 entries on its first axis, a vmin equals its vmax, or a gamma is not positive.

Source code in packages/geotoolz-ops/src/geoops/viz/_src/array.py
def rgb_recipe(
    channels: Float[np.ndarray, "3 h w"],
    *,
    vmin: float | tuple[float, float, float] = 0.0,
    vmax: float | tuple[float, float, float] = 1.0,
    gamma: float | tuple[float, float, float] = 1.0,
) -> Float[np.ndarray, "3 h w"]:
    r"""Stretch and gamma-correct three channels into a display RGB.

    Each channel ``c`` is mapped through a fixed linear stretch and a power
    law — the "RGB recipe" form of the operational satellite RGB guides:

    .. math::

        y_c \;=\; \operatorname{clip}\!\Bigl(
            \frac{x_c - v_{\min,c}}{v_{\max,c} - v_{\min,c}}, 0, 1
        \Bigr)^{1/\gamma_c}

    A ``vmin`` above ``vmax`` inverts the channel (colder brightness
    temperatures brighter, for instance). ``NaN`` inputs stay ``NaN``.

    Args:
        channels: The red, green and blue inputs stacked on the first axis.
        vmin: Value mapped to 0, per channel or one for all.
        vmax: Value mapped to 1, per channel or one for all.
        gamma: Gamma per channel or one for all (``> 0``; ``> 1``
            brightens midtones).

    Returns:
        ``float32`` array of the same shape, in ``[0, 1]`` (``NaN`` kept).

    Raises:
        ValueError: ``channels`` does not have 3 entries on its first axis,
            a ``vmin`` equals its ``vmax``, or a gamma is not positive.
    """
    arr = np.asarray(channels, dtype=np.float32)
    if arr.shape[0] != 3:
        raise ValueError(f"rgb_recipe needs 3 channels; got shape {arr.shape}.")
    lo, hi, g = (
        np.broadcast_to(np.asarray(v, dtype=np.float64), (3,))
        for v in (vmin, vmax, gamma)
    )
    if np.any(lo == hi):
        raise ValueError(f"vmin and vmax must differ per channel; got {lo}, {hi}.")
    if np.any(g <= 0):
        raise ValueError(f"gamma must be positive; got {g}.")
    out = np.empty_like(arr)
    for c in range(3):
        unit = np.clip((arr[c] - lo[c]) / (hi[c] - lo[c]), 0.0, 1.0)
        out[c] = unit ** (1.0 / g[c])
    return out

rgba_from_categories(arr, mapping, *, default=(0.0, 0.0, 0.0, 0.0))

Map integer classes to a four-band uint8 RGBA image.

Categorical-label rendering: each class ID in mapping paints its pixels with the associated colour; pixels whose value is not in the mapping fall back to default.

Parameters:

Name Type Description Default
arr Int[ndarray, 'h w'] | Int[ndarray, '1 h w']

Single-band label map, (H, W) or (1, H, W).

required
mapping Mapping[int, Color]

{class_id: (r, g, b, a)} lookup table with float components in [0, 1].

required
default Color

RGBA colour for unmapped classes. Default fully transparent.

(0.0, 0.0, 0.0, 0.0)

Returns:

Type Description
UInt8[ndarray, '4 h w']

Channel-first (4, H, W) uint8 RGBA image.

Raises:

Type Description
ValueError

If arr is not a single-band map.

Source code in packages/geotoolz-ops/src/geoops/viz/_src/array.py
def rgba_from_categories(
    arr: Int[np.ndarray, "h w"] | Int[np.ndarray, "1 h w"],
    mapping: Mapping[int, Color],
    *,
    default: Color = (0.0, 0.0, 0.0, 0.0),
) -> UInt8[np.ndarray, "4 h w"]:
    """Map integer classes to a four-band uint8 RGBA image.

    Categorical-label rendering: each class ID in ``mapping`` paints its
    pixels with the associated colour; pixels whose value is not in the
    mapping fall back to ``default``.

    Args:
        arr: Single-band label map, ``(H, W)`` or ``(1, H, W)``.
        mapping: ``{class_id: (r, g, b, a)}`` lookup table with float
            components in ``[0, 1]``.
        default: RGBA colour for unmapped classes. Default fully
            transparent.

    Returns:
        Channel-first ``(4, H, W)`` ``uint8`` RGBA image.

    Raises:
        ValueError: If ``arr`` is not a single-band map.
    """
    band = single_band(arr, name="rgba_from_categories")
    rgba = np.zeros((*band.shape, 4), dtype=np.float32)
    rgba[...] = np.asarray(default, dtype=np.float32)
    for value, color in mapping.items():
        rgba[band == value] = np.asarray(color, dtype=np.float32)
    return _float_rgba_to_uint8(rgba)

rgba_from_scalar(arr, cmap, *, vmin=None, vmax=None, nan_color=(0.0, 0.0, 0.0, 0.0))

Map a single-band array to a four-band uint8 RGBA image.

Values are linearly normalised into [0, 1] between vmin and vmax (auto-detected from the finite values when omitted), then looked up through cmap. Non-finite pixels are painted with nan_color rather than whatever the colormap does at 0.

Parameters:

Name Type Description Default
arr Num[ndarray, 'h w'] | Num[ndarray, '1 h w']

Single-band map, (H, W) or (1, H, W).

required
cmap Callable[[ndarray], ndarray]

Matplotlib-style callable mapping unit-interval floats to (..., 4) RGBA floats in [0, 1].

required
vmin float | None

Lower normalisation bound. None uses the finite minimum of arr.

None
vmax float | None

Upper normalisation bound. None uses the finite maximum of arr.

None
nan_color Color

RGBA tuple in [0, 1] painted over non-finite pixels. Default fully transparent.

(0.0, 0.0, 0.0, 0.0)

Returns:

Type Description
UInt8[ndarray, '4 h w']

Channel-first (4, H, W) uint8 RGBA image.

Raises:

Type Description
ValueError

If arr is not a single-band map.

Source code in packages/geotoolz-ops/src/geoops/viz/_src/array.py
def rgba_from_scalar(
    arr: Num[np.ndarray, "h w"] | Num[np.ndarray, "1 h w"],
    cmap: Callable[[np.ndarray], np.ndarray],
    *,
    vmin: float | None = None,
    vmax: float | None = None,
    nan_color: Color = (0.0, 0.0, 0.0, 0.0),
) -> UInt8[np.ndarray, "4 h w"]:
    """Map a single-band array to a four-band uint8 RGBA image.

    Values are linearly normalised into ``[0, 1]`` between ``vmin`` and
    ``vmax`` (auto-detected from the finite values when omitted), then
    looked up through ``cmap``. Non-finite pixels are painted with
    ``nan_color`` rather than whatever the colormap does at 0.

    Args:
        arr: Single-band map, ``(H, W)`` or ``(1, H, W)``.
        cmap: Matplotlib-style callable mapping unit-interval floats to
            ``(..., 4)`` RGBA floats in ``[0, 1]``.
        vmin: Lower normalisation bound. ``None`` uses the finite
            minimum of ``arr``.
        vmax: Upper normalisation bound. ``None`` uses the finite
            maximum of ``arr``.
        nan_color: RGBA tuple in ``[0, 1]`` painted over non-finite
            pixels. Default fully transparent.

    Returns:
        Channel-first ``(4, H, W)`` ``uint8`` RGBA image.

    Raises:
        ValueError: If ``arr`` is not a single-band map.
    """
    band = single_band(arr, name="rgba_from_scalar")
    valid = np.isfinite(band)
    if vmin is None:
        vmin = float(np.nanmin(band)) if valid.any() else 0.0
    if vmax is None:
        vmax = float(np.nanmax(band)) if valid.any() else 1.0
    denom = vmax - vmin
    if denom <= 0:
        denom = 1.0
    normed = np.clip((band - vmin) / denom, 0.0, 1.0)
    rgba = np.asarray(cmap(normed), dtype=np.float32)
    rgba[~valid] = np.asarray(nan_color, dtype=np.float32)
    return _float_rgba_to_uint8(rgba)

stretch_to_uint8(arr, *, lower=2.0, upper=98.0, reduce_axes=(-2, -1))

Percentile stretch an array into display-ready uint8 values.

Exactly :func:geoops.radiometry.percentile_clip (NaN-safe: percentiles via np.nanpercentile) followed by a rounded byte cast; NaN pixels map to 0. Use percentile_clip directly if you need the intermediate [0, 1] floats for further math.

Parameters:

Name Type Description Default
arr Num[ndarray, '*batch y x']

Input array, typically (C, H, W).

required
lower float

Lower percentile. Default 2.0.

2.0
upper float

Upper percentile. Default 98.0; must exceed lower.

98.0
reduce_axes int | tuple[int, ...] | None

Axes the percentiles are computed over. Default (-2, -1) stretches each band (and frame) independently; None uses one global pair of thresholds.

(-2, -1)

Returns:

Type Description
UInt8[ndarray, '*batch y x']

uint8 array of the same shape.

Raises:

Type Description
ValueError

If upper <= lower.

Source code in packages/geotoolz-ops/src/geoops/viz/_src/array.py
def stretch_to_uint8(
    arr: Num[np.ndarray, "*batch y x"],
    *,
    lower: float = 2.0,
    upper: float = 98.0,
    reduce_axes: int | tuple[int, ...] | None = (-2, -1),
) -> UInt8[np.ndarray, "*batch y x"]:
    """Percentile stretch an array into display-ready ``uint8`` values.

    Exactly :func:`geoops.radiometry.percentile_clip` (NaN-safe:
    percentiles via ``np.nanpercentile``) followed by a rounded byte
    cast; NaN pixels map to ``0``. Use ``percentile_clip`` directly if
    you need the intermediate ``[0, 1]`` floats for further math.

    Args:
        arr: Input array, typically ``(C, H, W)``.
        lower: Lower percentile. Default ``2.0``.
        upper: Upper percentile. Default ``98.0``; must exceed ``lower``.
        reduce_axes: Axes the percentiles are computed over. Default
            ``(-2, -1)`` stretches each band (and frame) independently;
            ``None`` uses one global pair of thresholds.

    Returns:
        ``uint8`` array of the same shape.

    Raises:
        ValueError: If ``upper <= lower``.
    """
    return _unit_to_uint8(percentile_clip(arr, lower, upper, reduce_axes=reduce_axes))