Spectral¶
Band-space operators — selection, math, spectral response, continuum removal — for hyperspectral and multispectral cubes.
- Band selection:
SelectBands,ReorderBands,SplitBands,StackBands— by index or name (StackBandsrequires every input on the same grid with the samefill_value) - Band math:
BandMath(restricted arithmetic expression over named bands),BandRatio - Spectral resampling:
SpectralBinning,SpectralSmoothing - Continuum removal:
ContinuumRemoval - Tier-A primitives:
select_bands,reorder_bands,band_ratio,evaluate_band_math,spectral_binning,spectral_smoothing,continuum_removal
The normalized difference is indices.NormalizedDifference and the Gaussian
spectral-response convolution is radiometry.ApplySRF; the former
spectral.NormalizedDifference, spectral.ApplySRF and spectral.GaussianSRF duplicates were
removed.
geoops.spectral
¶
Band-space operators for spectral remote-sensing workflows.
Band selection / reordering / stacking / splitting, band math and
ratios, spectral binning and smoothing, and continuum removal. The
normalized difference lives in :mod:geoops.indices
(:class:~geoops.indices.NormalizedDifference) and the Gaussian-SRF
convolution in :mod:geoops.radiometry
(:class:~geoops.radiometry.ApplySRF).
BandMath
¶
Bases: Operator
Evaluate a restricted arithmetic expression over named bands.
The expression is parsed with Python's ast module and only
permits constants, unary +/-, binary + - * / **, and the
whitelisted functions abs, sqrt, log, log10, exp, where, minimum,
maximum, clip. Band variables resolve to slices along the band
axis named by band_names (default: the carrier's band names from
gt.attrs — band_names, then descriptions, then bands —
or synthetic B0, B1, ... labels). Plain np.ndarray input is
supported (synthetic B0, B1, ... names apply unless
band_names is given) and returns a plain array.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
expression
|
str
|
Arithmetic expression over band names, e.g.
|
required |
band_names
|
list[str] | None
|
Override for the names used in |
None
|
dim
|
str
|
Name of the band dim (default |
'band'
|
axis
|
int | None
|
Deprecated: the band axis position. |
None
|
Examples:
>>> from geoops import spectral
>>> # NDVI by name (assumes gt.attrs["band_names"] contains B4/B8).
>>> ndvi = spectral.BandMath(expression="(B8 - B4) / (B8 + B4 + 1e-6)")
>>> ndvi_map = ndvi(reflectance_geoarray)
Source code in packages/geotoolz-ops/src/geoops/spectral/_src/operators.py
BandRatio
¶
Bases: Operator
Simple two-band ratio numerator / (denominator + eps).
Plain np.ndarray input is supported for integer keys and
returns a plain array; string names require carrier attrs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
numerator
|
BandRef
|
Index or name of the numerator band. |
required |
denominator
|
BandRef
|
Index or name of the denominator band. |
required |
eps
|
float
|
Denominator stabiliser. Default |
1e-10
|
dim
|
str
|
Name of the band dim (default |
'band'
|
axis
|
int | None
|
Deprecated: the band axis position. |
None
|
Examples:
>>> from geoops import spectral
>>> # Simple Ratio Vegetation Index (NIR / Red).
>>> srvi = spectral.BandRatio(numerator="B8", denominator="B4")
>>> ratio = srvi(reflectance_geoarray)
Source code in packages/geotoolz-ops/src/geoops/spectral/_src/operators.py
ContinuumRemoval
¶
Bases: Operator
Hull-quotient continuum removal along the band axis.
For each spectrum (each spatial pixel along the band axis), divides by an envelope:
method="convex_hull"— the upper convex hull of the spectrum vs wavelength. Output is the spectrum / hull, in(0, 1], with absorption features pulled to <1 and the hull itself at 1.method="linear"— a straight line between the first and last band. Cheaper but only valid when no spectral curvature lives outside the absorption band of interest.
Plain np.ndarray input is supported when wavelengths is
given explicitly and returns a plain array.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
str
|
|
'convex_hull'
|
wavelengths
|
ndarray | list[float] | None
|
Source wavelengths in strictly increasing order.
Default |
None
|
dim
|
str
|
Name of the band dim (default |
'band'
|
axis
|
int | None
|
Deprecated: the band axis position. |
None
|
Examples:
>>> from geoops import spectral
>>> # Continuum-remove a SWIR-2 mineral absorption window.
>>> cr = spectral.ContinuumRemoval(method="convex_hull")
>>> band_depth = cr(swir2_geoarray) # (B, H, W), values in (0, 1]
Source code in packages/geotoolz-ops/src/geoops/spectral/_src/operators.py
ReorderBands
¶
Bases: SelectBands
Reorder bands by integer index or band name.
Same semantics as :class:SelectBands but emphasises that the
output keeps every input band — just in a new order. Length of
order should equal the number of bands on the input.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
order
|
list[BandRef]
|
New band ordering. Items are integer positions or names. |
required |
dim
|
str
|
Name of the band dim (default |
'band'
|
axis
|
int | None
|
Deprecated: the band axis position. |
None
|
Examples:
>>> from geoops import spectral
>>> # Reorder a BGRN stack to RGBN.
>>> reorder = spectral.ReorderBands(order=[2, 1, 0, 3])
>>> rgbn = reorder(bgrn_geoarray)
Source code in packages/geotoolz-ops/src/geoops/spectral/_src/operators.py
SelectBands
¶
Bases: Operator
Select bands by integer index or band name along the band axis.
Resolves string keys with the package-wide band resolver
(gt.attrs band_names, then descriptions, then
bands). Selected
band_names and wavelengths attrs travel with the output.
Plain np.ndarray input is supported for integer positions (a
plain array comes back); string names require carrier attrs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bands
|
list[BandRef]
|
Bands to keep, in output order. Items are either
integer positions along |
required |
dim
|
str
|
Name of the band dim (default |
'band'
|
axis
|
int | None
|
Deprecated: the band axis position. |
None
|
Examples:
>>> from geoops import spectral
>>> # Sentinel-2 RGB stacked as (B2, B3, B4, B8) -> keep (B4, B3, B2).
>>> rgb = spectral.SelectBands(bands=["B4", "B3", "B2"])
>>> out = rgb(reflectance_geoarray)
Source code in packages/geotoolz-ops/src/geoops/spectral/_src/operators.py
SpectralBinning
¶
Bases: Operator
Aggregate source bands into wavelength-centered bins.
For each target_wavelength :math:\lambda_c with bin width
:math:w, aggregates source bands with
:math:|\lambda_s - \lambda_c| \le w/2. Aggregation modes:
"mean"— uniform average."median"— robust to outliers in narrow bins."weighted_mean"— Gaussian weights with :math:\sigma = w / (2 \sqrt{2 \ln 2})(FWHM equalswidth).
Plain np.ndarray input is supported when source_wavelengths
is given explicitly and returns a plain array.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target_wavelengths
|
ndarray | list[float]
|
Center wavelengths of the output bins. |
required |
width
|
float | ndarray | list[float]
|
Scalar or per-bin widths (same units as wavelengths). |
required |
method
|
str
|
|
'mean'
|
source_wavelengths
|
ndarray | list[float] | None
|
Source band wavelengths. Default |
None
|
axis
|
int | None
|
Position of the band axis. Default |
None
|
Examples:
>>> from geoops import spectral
>>> # Coarsen hyperspectral cube to broad-band averages.
>>> binner = spectral.SpectralBinning(
... target_wavelengths=[490.0, 560.0, 665.0],
... width=30.0,
... method="weighted_mean",
... )
>>> coarse = binner(hyperspectral_geoarray)
Source code in packages/geotoolz-ops/src/geoops/spectral/_src/operators.py
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 | |
SpectralSmoothing
¶
Bases: Operator
Smooth spectra along the band axis.
Pure per-spectrum math — accepts a GeoArray or a plain
np.ndarray and returns the same carrier kind.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
str
|
|
'savgol'
|
window
|
int
|
Filter window length in bands. Must be odd for
|
7
|
polyorder
|
int
|
Polynomial order for Savitzky-Golay (ignored by the
other methods). Default |
2
|
dim
|
str
|
Name of the band dim (default |
'band'
|
axis
|
int | None
|
Deprecated: the band axis position. |
None
|
Examples:
>>> from geoops import spectral
>>> # De-noise hyperspectral spectra before continuum removal.
>>> smooth = spectral.SpectralSmoothing(
... method="savgol", window=9, polyorder=2
... )
>>> denoised = smooth(hyperspectral_geoarray)
Source code in packages/geotoolz-ops/src/geoops/spectral/_src/operators.py
SplitBands
¶
Bases: Operator
Split a multiband GeoArray into one single-band GeoArray per band.
Plain np.ndarray input is supported and yields a list of plain
single-band arrays.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
names
|
list[str] | None
|
Optional override for band names. If omitted, names are
read from |
None
|
dim
|
str
|
Name of the band dim (default |
'band'
|
axis
|
int | None
|
Deprecated: the band axis position. |
None
|
Examples:
>>> from geoops import spectral
>>> bands = spectral.SplitBands()(rgb_geoarray) # list of (1, H, W)
>>> red, green, blue = bands
Source code in packages/geotoolz-ops/src/geoops/spectral/_src/operators.py
StackBands
¶
Bases: Operator
Concatenate carriers along the band axis.
The checks of :func:geoarray.concatenate, extended to plain arrays,
2-D inputs and any band axis: every input must sit on the first
input's pixel grid (:func:geoops._src.geo.grid_matches -- equal
spatial shape, CRS and transform) and declare the same
fill_value (NaN matches NaN), since the stack can
declare only one fill. Each per-band attrs key (band_names,
descriptions, wavelengths, ...) is concatenated in input order
when every input carries it with one entry per band; otherwise that
key is dropped on the output. Other attrs come from the first input.
Plain np.ndarray inputs are supported (only the spatial shape is
checked and a plain array is returned); mixing GeoArrays and plain
arrays raises because their georeferencing cannot agree.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dim
|
str
|
Name of the band dim (default |
'band'
|
axis
|
int | None
|
Deprecated: the band axis position. |
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If given a single array instead of a sequence. |
ValueError
|
If the sequence is empty, mixes GeoArrays and plain arrays, or the inputs differ in grid or fill value. |
Examples:
>>> from geoops import spectral
>>> stack = spectral.StackBands()
>>> stacked = stack([gt_b4, gt_b8]) # (2, H, W)
Source code in packages/geotoolz-ops/src/geoops/spectral/_src/operators.py
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 | |
band_ratio(arr, numerator_idx, denominator_idx, *, axis=-3, eps=1e-10)
¶
Compute numerator / (denominator + eps) with the band axis collapsed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
Num[ndarray, 'c h w']
|
Input array with the band axis at position |
required |
numerator_idx
|
int
|
Integer position of the numerator band. |
required |
denominator_idx
|
int
|
Integer position of the denominator band. |
required |
axis
|
int
|
Position of the band axis. Default |
-3
|
eps
|
float
|
Small constant added to the denominator to shadow division
by zero on no-data / saturated pixels. Default |
1e-10
|
Returns:
| Type | Description |
|---|---|
Float[ndarray, 'h w']
|
Float ratio array with the band axis collapsed. Integer input is |
Float[ndarray, 'h w']
|
promoted to float first (see |
Source code in packages/geotoolz-ops/src/geoops/spectral/_src/array.py
continuum_removal(arr, wavelengths, *, axis=-3, method='convex_hull')
¶
Apply hull-quotient continuum removal along the band axis.
Each spectrum (the 1-D slice along axis at every remaining
position) is divided by a continuum envelope so absorption features
stand out as dips below 1:
method="convex_hull"— the envelope is the upper convex hull of the spectrum vs wavelength. Output values lie in(0, 1], with hull touch-points exactly at 1.method="linear"— the envelope is the straight line between the first and last band. Cheaper, but only appropriate when no spectral curvature lies outside the absorption feature of interest.
Where the continuum is exactly zero the quotient is defined as 1 (flat), avoiding division-by-zero artefacts on empty pixels.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
Float[ndarray, 'c h w']
|
Spectral cube with the band axis at position |
required |
wavelengths
|
Float[ndarray, ' c']
|
Band-center wavelengths, strictly increasing, with
length equal to |
required |
axis
|
int
|
Position of the band axis. Default |
-3
|
method
|
str
|
Continuum model, |
'convex_hull'
|
Returns:
| Type | Description |
|---|---|
Float[ndarray, 'c h w']
|
Float array of the same shape as |
Float[ndarray, 'c h w']
|
continuum-removed (hull-quotient) spectra. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in packages/geotoolz-ops/src/geoops/spectral/_src/array.py
evaluate_band_math(expression, variables)
¶
Evaluate a restricted arithmetic expression over named band arrays.
The expression is parsed with Python's :mod:ast module — never
eval — and only a small arithmetic grammar is permitted:
- numeric constants,
- unary
+/-, - binary
+ - * / **, - calls to the whitelisted numpy functions
abs,sqrt,log,log10,exp,where,minimum,maximum, andclip.
Bare names resolve against variables; anything else (comparison
operators, attribute access, subscripts, lambdas, ...) raises. With
no comparisons in the grammar, where's condition is a numeric
expression read as truthy where non-zero (e.g.
where(clip(B8 - B4, 0, 1), B8, B4)), not B8 > B4.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
expression
|
str
|
Arithmetic expression over the keys of
|
required |
variables
|
Mapping[str, Num[ndarray, 'h w']]
|
Mapping from band name to band array. All arrays
should broadcast against each other (typically identical
|
required |
Every band array is promoted to floating point before evaluation
(see geoops._src.dtype.as_float), so integer DN never wrap
around or overflow: "a - b" over uint16 bands 1000 and
3000 gives -2000.0, not 63536.
Returns:
| Type | Description |
|---|---|
Num[ndarray, 'h w']
|
The evaluated result as a float ndarray (broadcast shape of the |
Num[ndarray, 'h w']
|
participating bands). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the expression references an unknown band name, uses a non-numeric constant, or contains any construct outside the grammar above. |
Source code in packages/geotoolz-ops/src/geoops/spectral/_src/array.py
reorder_bands(arr, order, *, axis=-3)
¶
Reorder bands by integer index along the configured band axis.
Alias of :func:select_bands that emphasises intent: order
should be a permutation of range(arr.shape[axis]) so every input
band appears exactly once in the output (this is not enforced).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
Shaped[ndarray, 'c h w']
|
Input array with the band axis at position |
required |
order
|
list[int]
|
New band ordering as integer positions. |
required |
axis
|
int
|
Position of the band axis. Default |
-3
|
Returns:
| Type | Description |
|---|---|
Shaped[ndarray, 'c h w']
|
Array with the same shape as |
Shaped[ndarray, 'c h w']
|
according to |
Source code in packages/geotoolz-ops/src/geoops/spectral/_src/array.py
select_bands(arr, indexes, *, axis=-3)
¶
Select bands by integer index along the configured band axis.
Thin wrapper over :func:numpy.take. Shapes are shown for the
default channel-first (C, H, W) layout, but any number of
dimensions is supported — only the axis at position axis is
touched.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
Shaped[ndarray, 'c h w']
|
Input array with the band axis at position |
required |
indexes
|
list[int]
|
Integer band positions to keep, in output order. Repeats are allowed (the band is duplicated in the output). |
required |
axis
|
int
|
Position of the band axis. Default |
-3
|
Returns:
| Type | Description |
|---|---|
Shaped[ndarray, 'k h w']
|
Array with the band axis replaced by the |
Shaped[ndarray, 'k h w']
|
selected bands; all other axes are unchanged. |
Source code in packages/geotoolz-ops/src/geoops/spectral/_src/array.py
spectral_binning(arr, source_wavelengths, target_wavelengths, width, *, axis=-3, method='mean')
¶
Aggregate source bands into wavelength-centered bins.
For each target bin center :math:\lambda_c with width :math:w,
the source bands satisfying
:math:|\lambda_s - \lambda_c| \le w/2 are aggregated into one
output band. Aggregation modes:
method="mean"— uniform average of the in-bin bands.method="median"— per-pixel median; robust to outlier bands in narrow bins.method="weighted_mean"— Gaussian weights centered on :math:\lambda_cwith :math:\sigma = w / (2\sqrt{2\ln 2}), i.e. the bin width is interpreted as the FWHM of a synthetic Gaussian response; weights are normalised to sum to one.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
Num[ndarray, 'c h w']
|
Spectral cube with the band axis at position |
required |
source_wavelengths
|
Float[ndarray, ' c']
|
Wavelengths of the source bands, strictly
increasing, with length equal to |
required |
target_wavelengths
|
Float[ndarray, ' k']
|
Center wavelengths of the output bins,
shape |
required |
width
|
float | Float[ndarray, ' k']
|
Bin width(s) in the same units as the wavelengths — a
scalar applied to every bin, or a per-bin array broadcast
against |
required |
axis
|
int
|
Position of the band axis. Default |
-3
|
method
|
str
|
|
'mean'
|
Returns:
| Type | Description |
|---|---|
Float[ndarray, 'k h w']
|
Float array with the band axis replaced by the |
Float[ndarray, 'k h w']
|
bands; all other axes are unchanged. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in packages/geotoolz-ops/src/geoops/spectral/_src/array.py
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 | |
spectral_smoothing(arr, *, axis=-3, method='savgol', window=7, polyorder=2)
¶
Smooth spectra along the band axis.
Filters each spectrum (1-D slice along axis) independently:
method="savgol"— Savitzky-Golay least-squares polynomial fit of orderpolyorderover an oddwindowof bands. Preserves peak shape better than a plain average.method="gaussian"— Gaussian filter withsigma = window / 2bands (polyorderignored).method="moving_average"— uniform boxcar ofwindowbands vianp.convolve(..., mode="same")(polyorderignored); spectrum edges taper because the kernel overhangs zeros.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
Float[ndarray, 'c h w']
|
Spectral cube with the band axis at position |
required |
axis
|
int
|
Position of the band axis. Default |
-3
|
method
|
str
|
|
'savgol'
|
window
|
int
|
Filter window length in bands. Must be odd for
|
7
|
polyorder
|
int
|
Polynomial order of the Savitzky-Golay fit; must be
less than |
2
|
Returns:
| Type | Description |
|---|---|
Float[ndarray, 'c h w']
|
Float array of the same shape as |
Float[ndarray, 'c h w']
|
spectra. Integer input is promoted to float64 first (see |
Float[ndarray, 'c h w']
|
|
Float[ndarray, 'c h w']
|
float array rather than a truncated integer one. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |