Normalize¶
Per-band scaling and contrast operators for model inputs and display.
- Per-band scalers:
StandardScaler(z-score),RobustScaler(median / IQR),MinMaxScaler,ZeroOne - Fixed statistics:
Normalize(z-score with given per-band mean / std),PerBandStats(compute and cache NaN-aware per-band statistics) - Non-linear scaling:
LogScale,AsinhScale,PowerScale - Contrast / histogram:
HistogramStretch,HistogramMatch,CLAHE - Tier-A primitives:
standard_scale,robust_scale,minmax_scale(and their inversesinverse_standard_scale,inverse_robust_scale,inverse_minmax_scale),log_scale,asinh_scale,power_scale,histogram_match,reference_cdf,match_cdf,clahe,per_band_stats - Per-band statistics on every backend:
band_stats,band_quantiles(arrays, band axis by position) andcarrier_band_stats(a carrier, band dim by name), mask-aware on NumPy, JAX (underjax.jittoo) and dask
See the Normalization guide for when to use which.
geoops.normalize
¶
Normalization operators for remote-sensing GeoArrays.
AsinhScale
¶
Bases: Operator
Inverse-hyperbolic-sine scaling.
.. math::
y \;=\; \mathrm{asinh}(x / a)
Linear near zero, logarithmic for |x| >> a. Symmetric and
well-defined for negative values (unlike log) — a common pick
for astronomy and signed radar quantities. Nodata (fill /
non-finite) pixels hold the output fill value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
float
|
Scale parameter. Must be strictly positive. Default
|
1.0
|
Examples:
Source code in packages/geotoolz-ops/src/geoops/normalize/_src/operators.py
CLAHE
¶
Bases: Operator
Contrast-Limited Adaptive Histogram Equalization.
Reproduces :func:skimage.exposure.equalize_adapthist (through
clahe, without scikit-image) independently per band for
(C, H, W) carriers while preserving NaN positions and GeoArray
metadata. Nodata (fill / non-finite) pixels are excluded from the
histograms and hold the output fill.
Backends: NumPy, JAX (under jax.jit too) and dask, where each
frame's whole (band, y, x) cube is one task: the tiles need every
pixel, so a spatially chunked cube is rechunked per frame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
window
|
int | tuple[int, int] | list[int] | None
|
Contextual-region shape for the local histograms.
|
None
|
clip_limit
|
float
|
Contrast-limiting clip threshold in |
0.01
|
nbins
|
int
|
Number of histogram bins. Default |
256
|
Examples:
Source code in packages/geotoolz-ops/src/geoops/normalize/_src/operators.py
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 398 399 400 401 402 403 404 405 406 407 408 409 | |
HistogramMatch
¶
Bases: Operator
Match a GeoArray histogram to a reference GeoArray.
Reshapes the per-band empirical CDF of the input to match the reference. Useful for visual harmonisation across scenes acquired under different illumination. Nodata (fill / non-finite) pixels of both the input and the reference are excluded from the CDFs; input nodata pixels hold the output fill value.
A (T, C, H, W) stack is matched per band with one CDF pooled over
every frame (like the module's other fitted statistics), so the
relative brightness of the frames survives the matching; a 4-D
reference likewise pools its frames per band.
The reference is a live GeoArray — not JSON / YAML serialisable —
so forbid_in_yaml = True.
Backends: exact rank matching (reference_cdf, then match_cdf: a sort
and searchsorted, the same result as scikit-image's
match_histograms) with static shapes, so it runs on NumPy, on JAX
under jax.jit (the reference's table is a constant), and lazily on
dask, where each band of the source is gathered into one block.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reference
|
GeoArray | ndarray
|
Reference GeoArray whose per-band CDF the input will be matched against. |
required |
Examples:
>>> from geoops.normalize import HistogramMatch
>>> op = HistogramMatch(reference=reference_scene)
>>> matched = op(source_scene)
Source code in packages/geotoolz-ops/src/geoops/normalize/_src/operators.py
869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 | |
HistogramStretch
¶
Bases: Operator
Per-band percentile stretch into out_range for visualisation.
Lighter-weight cousin of :class:geoops.radiometry.PercentileClip
(same shared percentile stretch, same lower / upper
vocabulary): clips to [P_lower, P_upper] using NaN-aware
percentiles, then maps the result into out_range instead of
fixed [0, 1]. Percentiles follow the normalize per-band
statistics convention: per band, pooled over the frames of a
(T, C, H, W) stack (PercentileClip stretches each frame
independently by default). Nodata (fill / non-finite) pixels are
excluded from the percentiles and hold the output fill value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
out_range
|
tuple[float, float]
|
Two-element increasing tuple. Default
|
(0.0, 1.0)
|
lower
|
float
|
Lower percentile. Default |
2.0
|
upper
|
float
|
Upper percentile. Default |
98.0
|
Examples:
>>> from geoops.normalize import HistogramStretch
>>> # Standard "satellite RGB to display byte range" stretch.
>>> op = HistogramStretch(out_range=(0.0, 255.0))
>>> display = op(reflectance_scene)
Source code in packages/geotoolz-ops/src/geoops/normalize/_src/operators.py
LogScale
¶
Bases: Operator
Logarithmic scaling with an epsilon offset for zeros.
.. math::
y \;=\; \log_{\text{base}}(\max(x, 0) + \epsilon)
Compresses heavy-tailed distributions (radar backscatter, fire
radiative power, etc.) before downstream training. eps keeps
the log finite at zero. Nodata (fill / non-finite) pixels hold the
output fill value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base
|
float
|
Logarithm base. Must be |
10.0
|
eps
|
float
|
Small positive offset added before the log. Default
|
1e-06
|
Examples:
>>> from geoops.normalize import LogScale
>>> log_sar = LogScale(base=10.0, eps=1e-6)(sar_backscatter)
Source code in packages/geotoolz-ops/src/geoops/normalize/_src/operators.py
MinMaxScaler
¶
Bases: Operator
Per-band min-max scaling into an arbitrary output range.
.. math::
y \;=\; \frac{x - v_{\min}}{v_{\max} - v_{\min}}
\cdot (o_{\max} - o_{\min}) + o_{\min}
Per-band variant of :class:geoops.radiometry.MinMaxStretch. The
radiometry version takes scalar bounds and is the display-prep
pick when you already know fixed reflectance limits; this version
fits per-band bounds (one vmin / vmax per channel) or
accepts cached training-time bounds for inference. When
vmax == vmin for a band the divisor falls back to 1. Nodata
(fill / non-finite) pixels are excluded from the fit and hold the
output fill value.
Fitted operator with the same fit / transform / inverse
contract as :class:StandardScaler (fitted state vmin_ /
vmax_, never part of get_config()).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vmin
|
ndarray | list[float] | float | None
|
Per-band lower bound, scalar / list / ndarray, or
|
None
|
vmax
|
ndarray | list[float] | float | None
|
Per-band upper bound. |
None
|
out_range
|
tuple[float, float]
|
|
(0.0, 1.0)
|
fit_on_call
|
bool
|
If |
False
|
Attributes:
| Name | Type | Description |
|---|---|---|
vmin_ |
ndarray | None
|
Fitted per-band lower bound, or |
vmax_ |
ndarray | None
|
Fitted per-band upper bound, or |
Examples:
>>> from geoops.normalize import MinMaxScaler
>>> # Map per-band [vmin, vmax] into [0, 1]:
>>> op = MinMaxScaler(vmin=[0.0, 0.0], vmax=[0.3, 0.4])
>>> scaled = op(scene)
>>>
>>> # Or fit on the scene and emit a uint8-style range:
>>> op = MinMaxScaler(out_range=(0.0, 255.0)).fit(scene)
>>> display = op(scene)
Source code in packages/geotoolz-ops/src/geoops/normalize/_src/operators.py
677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 | |
fit(gt)
¶
Learn per-band vmin_ / vmax_ from the valid pixels of gt.
Returns:
| Type | Description |
|---|---|
Self
|
This operator, for chaining. |
Source code in packages/geotoolz-ops/src/geoops/normalize/_src/operators.py
inverse(gt)
¶
Map out_range values back to the [vmin, vmax] input scale.
Source code in packages/geotoolz-ops/src/geoops/normalize/_src/operators.py
transform(gt)
¶
Map gt from the fitted (or constructor) bounds into out_range.
Source code in packages/geotoolz-ops/src/geoops/normalize/_src/operators.py
Normalize
¶
Bases: StandardScaler
Fixed-stats per-band z-score normaliser.
Convenience alias for :class:StandardScaler with mandatory
mean / std (no fit_on_call knob exposed). The canonical
inference-time normaliser: cache stats once at training time,
instantiate at inference.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mean
|
ndarray | list[float] | float
|
Per-band mean (scalar, list, or ndarray). |
required |
std
|
ndarray | list[float] | float
|
Per-band std (scalar, list, or ndarray). |
required |
Examples:
>>> from geoops.normalize import Normalize
>>> import numpy as np
>>> op = Normalize(
... mean=np.array([0.1, 0.2, 0.15]),
... std=np.array([0.05, 0.07, 0.06]),
... )
>>> normed = op(scene)
Source code in packages/geotoolz-ops/src/geoops/normalize/_src/operators.py
PerBandStats
¶
Bases: Operator
Compute NaN-aware per-band statistics and cache them.
Side-effect-only operator: returns the input unchanged after caching
a stats dict containing per-band mean, std, min,
max, and percentiles over the spatial (H, W) axes. Use
this in a Tap-style stage to inspect a scene before applying a
downstream normaliser. Nodata (fill / non-finite) pixels are
excluded from every statistic.
Backends: NumPy, eager JAX and dask, where one compute of the
statistics (not of the data) runs and the input passes through still
lazy. Under jax.jit writing self.stats would leak tracers, so it
raises; use carrier_band_stats inside a trace instead.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
percentiles
|
list[float] | None
|
Percentiles (in |
None
|
Examples:
>>> from geoops.normalize import PerBandStats
>>> op = PerBandStats(percentiles=[2.0, 98.0])
>>> _ = op(scene)
>>> op.stats["mean"] # one entry per band
[...]
Source code in packages/geotoolz-ops/src/geoops/normalize/_src/operators.py
PowerScale
¶
Bases: Operator
Non-negative power scaling.
.. math::
y \;=\; \max(x, 0)^{\gamma}
A simple gamma-style brightness curve. gamma < 1 brightens
midtones; gamma > 1 darkens. Differs from
:class:geoops.radiometry.Gamma only in convention
(Gamma raises to 1/g). Nodata (fill / non-finite) pixels
hold the output fill value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gamma
|
float
|
Power exponent. Must be strictly positive. Default
|
0.5
|
Examples:
Source code in packages/geotoolz-ops/src/geoops/normalize/_src/operators.py
RobustScaler
¶
Bases: Operator
Per-band median / IQR scaling (robust to outliers).
.. math::
y \;=\; \frac{x - \mathrm{median}}{Q_{3} - Q_{1}}
Identical role to :class:StandardScaler but uses the median and
interquartile range instead of mean and std — robust against
bright-pixel outliers (cumulus, glint, saturation). When
iqr == 0 the divisor falls back to 1. Nodata (fill /
non-finite) pixels are excluded from the fit and hold the output fill.
Fitted operator with the same fit / transform / inverse
contract as :class:StandardScaler (fitted state median_ /
iqr_, never part of get_config()).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
median
|
ndarray | list[float] | float | None
|
Per-band median (scalar, list, or ndarray) or |
None
|
iqr
|
ndarray | list[float] | float | None
|
Per-band IQR ( |
None
|
fit_on_call
|
bool
|
If |
False
|
Attributes:
| Name | Type | Description |
|---|---|---|
median_ |
ndarray | None
|
Fitted per-band median, or |
iqr_ |
ndarray | None
|
Fitted per-band IQR, or |
Examples:
>>> from geoops.normalize import RobustScaler
>>> op = RobustScaler().fit(scene)
>>> op.median_, op.iqr_
Source code in packages/geotoolz-ops/src/geoops/normalize/_src/operators.py
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 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 | |
fit(gt)
¶
Learn per-band median_ / iqr_ from the valid pixels of gt.
Returns:
| Type | Description |
|---|---|
Self
|
This operator, for chaining. |
Source code in packages/geotoolz-ops/src/geoops/normalize/_src/operators.py
inverse(gt)
¶
Invert a previously applied robust scaling (x = y * iqr + median).
Source code in packages/geotoolz-ops/src/geoops/normalize/_src/operators.py
transform(gt)
¶
Scale gt with the fitted (or constructor) median / IQR.
Source code in packages/geotoolz-ops/src/geoops/normalize/_src/operators.py
StandardScaler
¶
Bases: Operator
Per-band z-score normalisation.
.. math::
y \;=\; \frac{x - \mu}{\sigma}
Statistics reduce over the spatial axes (-2, -1) so a
(C, H, W) carrier yields per-band mu / sigma of shape
(C,). Pass cached training-set statistics via mean / std
for inference, call :meth:fit on a training scene, or set
fit_on_call=True to fit on the first scene seen. When
sigma == 0 (a constant band) the divisor falls back to 1 so
the band collapses to zero instead of producing inf / nan.
Nodata (fill / non-finite) pixels are excluded from the fit and hold
the output fill value.
Fitted operator (see Fitted operators in the concepts guide):
:meth:fit learns mean_ / std_ (which then take precedence
over the constructor statistics), :meth:transform applies them
without mutating the operator, and :meth:inverse undoes the
scaling. Learned statistics are never part of get_config(); to
persist them, build StandardScaler(mean=op.mean_, std=op.std_).
Backends: :meth:fit runs on NumPy, eager JAX and dask (one compute of
the statistics, not of the data) and always stores host NumPy arrays.
Under jax.jit it raises, and so does a first fit_on_call
call: fit eagerly, then apply the fitted operator inside the trace,
where its statistics are constants. :meth:transform and
:meth:inverse run everywhere, lazily on dask.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mean
|
ndarray | list[float] | float | None
|
Per-band mean (scalar, list, or ndarray) or |
None
|
std
|
ndarray | list[float] | float | None
|
Per-band std (scalar, list, or ndarray) or |
None
|
fit_on_call
|
bool
|
If |
False
|
Attributes:
| Name | Type | Description |
|---|---|---|
mean_ |
ndarray | None
|
Fitted per-band mean, or |
std_ |
ndarray | None
|
Fitted per-band std, or |
Examples:
>>> from geoops.normalize import StandardScaler
>>> # Inference: cached per-band statistics from training.
>>> scaler = StandardScaler(mean=[0.1, 0.2], std=[0.05, 0.07])
>>> normed = scaler(scene)
>>>
>>> # Training-time fit, then apply:
>>> fit = StandardScaler().fit(train_scene)
>>> normed = fit(scene)
>>> fit.mean_ # fitted per-band ndarray
Source code in packages/geotoolz-ops/src/geoops/normalize/_src/operators.py
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 | |
fit(gt)
¶
Learn per-band mean_ / std_ from the valid pixels of gt.
Returns:
| Type | Description |
|---|---|
Self
|
This operator, for chaining. |
Source code in packages/geotoolz-ops/src/geoops/normalize/_src/operators.py
inverse(gt)
¶
Invert a previously applied standard scaling.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gt
|
GeoArray | ndarray
|
Scaled carrier (GeoArray or plain ndarray). |
required |
Returns:
| Type | Description |
|---|---|
GeoArray | ndarray
|
The un-scaled carrier, same kind as |
GeoArray | ndarray
|
hold the output fill value. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the scaler has no statistics yet. |
Source code in packages/geotoolz-ops/src/geoops/normalize/_src/operators.py
transform(gt)
¶
Z-score gt with the fitted (or constructor) statistics.
Raises:
| Type | Description |
|---|---|
ValueError
|
If the operator has neither fitted nor constructor statistics. |
Source code in packages/geotoolz-ops/src/geoops/normalize/_src/operators.py
ZeroOne
¶
Bases: Operator
Scale the current scene extent into [0, 1].
.. math::
y \;=\; \frac{x - \min(x)}{\max(x) - \min(x)}
Stateless per-scene min-max stretch. per_band=True (default)
stretches each band independently; per_band=False uses a
single global min / max. Nodata (fill / non-finite) pixels are
excluded from the min / max and hold the output fill value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
per_band
|
bool
|
Compute min / max per band rather than globally. |
True
|
Examples:
Source code in packages/geotoolz-ops/src/geoops/normalize/_src/operators.py
asinh_scale(arr, *, a=1.0)
¶
Apply inverse-hyperbolic-sine scaling.
.. math::
y \;=\; \mathrm{asinh}(x / a)
Linear near zero, logarithmic for |x| >> a; symmetric and
well-defined for negative values (unlike log).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
Float[ndarray, '*dims']
|
Input float array. NaN pixels propagate through untouched. |
required |
a
|
float
|
Scale parameter marking the linear-to-log transition. Must
be strictly positive. Default |
1.0
|
Returns:
| Type | Description |
|---|---|
Float[ndarray, '*dims']
|
Float array of the same shape. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in packages/geotoolz-ops/src/geoops/normalize/_src/array.py
band_quantiles(x, valid=None, *, band_axis=BAND_AXIS, q=(0.25, 0.5, 0.75))
¶
Per-band quantiles of the valid pixels, on any backend.
:math:q_c(p) is the :math:p-th quantile (linear interpolation, as
np.nanpercentile) of the valid elements of band :math:c, pooled
over every axis except band_axis.
On dask an exact quantile needs every pixel of a band in one block, so
dask.array.nanquantile rechunks the reduced axes to a single chunk
and the band axis to "auto": a task holds whole bands, as many as fit
dask's array.chunk-size (at least one), never the whole cube.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Float[ndarray, '*dims']
|
Float array with the band axis at |
required |
valid
|
Shaped[ndarray, '*dims'] | None
|
Boolean array broadcasting to |
None
|
band_axis
|
int | None
|
The axis kept; |
BAND_AXIS
|
q
|
tuple[float, ...] | list[float]
|
Quantile levels in |
(0.25, 0.5, 0.75)
|
Returns:
| Type | Description |
|---|---|
Float[ndarray, 'levels ...']
|
|
Float[ndarray, 'levels ...']
|
backend; a band without valid elements gives |
Raises:
| Type | Description |
|---|---|
TypeError
|
|
ValueError
|
A level outside |
Examples:
>>> x = np.arange(8.0).reshape(2, 2, 2) # (C=2, H=2, W=2)
>>> band_quantiles(x, q=(0.0, 0.5, 1.0))
array([[0. , 4. ],
[1.5, 5.5],
[3. , 7. ]])
>>> # IQR per band, nodata left out
>>> lo, hi = band_quantiles(x, x != 0.0, q=(0.25, 0.75))
>>> (hi - lo).tolist()
[1.0, 1.5]
Source code in packages/geotoolz-ops/src/geoops/normalize/_src/array.py
band_stats(x, valid=None, *, band_axis=BAND_AXIS, stats=BAND_STATS)
¶
Per-band mean, std, min and max of the valid pixels, on any backend.
.. math::
\mu_c \;=\; \frac{1}{|V_c|} \sum_{i \in V_c} x_{c,i}
where :math:V_c is the set of valid elements of band :math:c, pooled
over every axis except band_axis (the frames of a (T, C, H, W)
stack too), and likewise for std, min and max. Written on the
array namespace: NumPy, JAX (under jax.jit too, one trace per shape)
and dask, where each statistic is a lazy tree reduction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Float[ndarray, '*dims']
|
Float array with the band axis at |
required |
valid
|
Shaped[ndarray, '*dims'] | None
|
Boolean array broadcasting to |
None
|
band_axis
|
int | None
|
The axis kept, one statistic per entry; |
BAND_AXIS
|
stats
|
tuple[str, ...] | list[str]
|
Which of |
BAND_STATS
|
Returns:
| Type | Description |
|---|---|
dict[str, Float[ndarray, '*stat']]
|
One array per requested statistic, |
dict[str, Float[ndarray, '*stat']]
|
|
dict[str, Float[ndarray, '*stat']]
|
elements gives |
Raises:
| Type | Description |
|---|---|
TypeError
|
|
ValueError
|
An unknown statistic name. |
Examples:
>>> x = np.array([[[1.0, 3.0]], [[2.0, -9.0]]]) # (C=2, H=1, W=2)
>>> band_stats(x, x != -9.0, stats=("mean", "max"))
{'mean': array([2., 2.]), 'max': array([3., 2.])}
>>> # a (T, C, H, W) stack pools its frames: still one value per band
>>> band_stats(np.ones((4, 3, 2, 2)), stats=("min",))["min"].shape
(3,)
>>> float(band_stats(x, x != -9.0, band_axis=None, stats=("min",))["min"])
1.0
Source code in packages/geotoolz-ops/src/geoops/normalize/_src/array.py
carrier_band_stats(x, *, dim='band', per_band=True, stats=BAND_STATS, quantiles=())
¶
Per-band statistics of a carrier's valid pixels, by dim name, on its backend.
The carrier form of band_stats and band_quantiles. The band dim is
found by name, so a (time, band, y, x) stack pools its frames into
one (C,) statistic per band. Nodata follows geoops' pixel rule
(geoops._src.valid): a pixel is invalid in every band when any of its
bands is non-finite or equals the carrier's fill, judged per frame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Any
|
A NumPy or JAX |
required |
dim
|
str
|
The band dim. A carrier without it gives scalar statistics. |
'band'
|
per_band
|
bool
|
|
True
|
stats
|
tuple[str, ...] | list[str]
|
Names for |
BAND_STATS
|
quantiles
|
tuple[float, ...] | list[float]
|
Levels in |
()
|
Returns:
| Type | Description |
|---|---|
One array per statistic on the data's backend
|
NumPy, JAX (tracers |
dict[str, Any]
|
under |
dict[str, Any]
|
( |
Raises:
| Type | Description |
|---|---|
TypeError
|
|
ValueError
|
An unknown statistic, or a level outside |
Examples:
>>> scene = np.array([[[1.0, 3.0]], [[2.0, np.nan]]]) # (band, y, x)
>>> # the NaN in band 1 invalidates that pixel in band 0 too
>>> carrier_band_stats(scene, stats=("mean",))
{'mean': array([1., 2.])}
>>> out = carrier_band_stats(scene, stats=(), quantiles=(0.5,))
>>> out["quantiles"].shape # (len(quantiles), C)
(1, 2)
>>> float(carrier_band_stats(scene, per_band=False, stats=("max",))["max"])
2.0
Source code in packages/geotoolz-ops/src/geoops/normalize/_src/operators.py
clahe(arr, *, window=None, clip_limit=0.01, nbins=256)
¶
Apply contrast-limited adaptive histogram equalization per image band.
The algorithm of :func:skimage.exposure.equalize_adapthist, written on
the array namespace so it runs on NumPy and on JAX (under jax.jit too,
one trace per shape) without scikit-image. Each (H, W) slice (every
band of a (C, H, W) cube, every band of every frame of a
(T, C, H, W) stack) is equalized independently:
- rescale to
[0, 1]over its finite range, quantise to 14-bit grey levels and bin them intonbins; - reflect-pad to whole tiles of
window, take each tile's histogram, clip it atclip_limittimes the tile size and redistribute the excess as scikit-image does; - map each pixel through the cumulative histograms of its four nearest tiles, blended bilinearly, and map the result back to native units.
NaN pixels are excluded (filled with the slice median before the histograms, as before) and stay NaN. A constant or all-NaN slice is returned unchanged.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
Shaped[ndarray, '*dims']
|
Input array; trailing axes are |
required |
window
|
int | tuple[int, int] | None
|
Contextual-region shape for the local histograms.
|
None
|
clip_limit
|
float
|
Contrast-limiting clip threshold in |
0.01
|
nbins
|
int
|
Number of histogram bins. Default |
256
|
Returns:
| Type | Description |
|---|---|
Float[ndarray, '*dims']
|
Float array of the same shape, equalized per band. |
Examples:
>>> ramp = np.linspace(0.0, 1.0, 64).reshape(8, 8) ** 2
>>> out = clahe(ramp, window=4)
>>> out.shape, float(out.min()), float(out.max())
((8, 8), 0.0, 1.0)
>>> # a stack is equalized slice by slice
>>> clahe(np.stack([ramp, ramp]), window=4).shape
(2, 8, 8)
Source code in packages/geotoolz-ops/src/geoops/normalize/_src/array.py
histogram_match(source, reference)
¶
Match source values to the empirical CDF of reference.
Per-band monotone remapping: each source value is replaced by the
reference value at the same empirical quantile (reference_cdf then
match_cdf). NaN pixels in the source are left untouched; NaNs in the
reference are excluded from its CDF.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
Float[ndarray, '*dims']
|
Array to remap. If 3-D+ ( |
required |
reference
|
Float[ndarray, '*ref']
|
Reference array. Either band-matched (same leading
band count as |
required |
Returns:
| Type | Description |
|---|---|
Float[ndarray, '*dims']
|
Float array of the same shape as |
Float[ndarray, '*dims']
|
histograms reshaped to the reference. |
Example
histogram_match(np.array([[0.0, 1.0, 2.0]]), np.array([[10.0, 20.0, 30.0]])) array([[10., 20., 30.]])
Source code in packages/geotoolz-ops/src/geoops/normalize/_src/array.py
inverse_minmax_scale(arr, vmin, vmax, *, out_range=(0.0, 1.0), reduce_axes=(-2, -1))
¶
Undo :func:minmax_scale: map out_range back onto [vmin, vmax].
.. math::
x \;=\; \frac{y - o_{\min}}{o_{\max} - o_{\min}}
\cdot (v_{\max} - v_{\min}) + v_{\min}
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
Float[ndarray, '*dims']
|
Scaled float array. NaN pixels propagate through untouched. |
required |
vmin
|
Float[ndarray, '*stat'] | float
|
Scalar or per-band lower bound, as for |
required |
vmax
|
Float[ndarray, '*stat'] | float
|
Scalar or per-band upper bound; |
required |
out_range
|
tuple[float, float]
|
The |
(0.0, 1.0)
|
reduce_axes
|
tuple[int, ...] | None
|
Axes the bounds were reduced over. Default
|
(-2, -1)
|
Returns:
| Type | Description |
|---|---|
Float[ndarray, '*dims']
|
Float array of the same shape as |
Raises:
| Type | Description |
|---|---|
TypeError
|
|
ValueError
|
If |
Examples:
>>> x = np.array([[[1.0, 3.0]]])
>>> inverse_minmax_scale(minmax_scale(x, 1.0, 3.0), 1.0, 3.0)
array([[[1., 3.]]])
>>> y = minmax_scale(x, 1.0, 3.0, out_range=(0.0, 255.0))
>>> inverse_minmax_scale(y, 1.0, 3.0, out_range=(0.0, 255.0))
array([[[1., 3.]]])
Source code in packages/geotoolz-ops/src/geoops/normalize/_src/array.py
inverse_robust_scale(arr, median, iqr, *, reduce_axes=(-2, -1))
¶
Undo :func:robust_scale.
.. math::
x \;=\; y \cdot (Q_{3} - Q_{1}) + \mathrm{median}
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
Float[ndarray, '*dims']
|
Scaled float array. NaN pixels propagate through untouched. |
required |
median
|
Float[ndarray, '*stat'] | float
|
Scalar or per-band median, as for |
required |
iqr
|
Float[ndarray, '*stat'] | float
|
Scalar or per-band interquartile range; a zero |
required |
reduce_axes
|
tuple[int, ...] | None
|
Axes the statistics were reduced over. Default
|
(-2, -1)
|
Returns:
| Type | Description |
|---|---|
Float[ndarray, '*dims']
|
Float array of the same shape as |
Raises:
| Type | Description |
|---|---|
TypeError
|
|
Examples:
>>> x = np.array([[[1.0, 3.0]]])
>>> inverse_robust_scale(robust_scale(x, 2.0, 4.0), 2.0, 4.0)
array([[[1., 3.]]])
>>> # per-band statistics for a (C, H, W) cube
>>> cube = np.ones((2, 1, 2))
>>> inverse_robust_scale(cube, [0.0, 1.0], [2.0, 3.0])[:, 0, 0]
array([2., 4.])
Source code in packages/geotoolz-ops/src/geoops/normalize/_src/array.py
inverse_standard_scale(arr, mean, std, *, reduce_axes=(-2, -1))
¶
Undo :func:standard_scale.
.. math::
x \;=\; y \cdot \sigma + \mu
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
Float[ndarray, '*dims']
|
Scaled float array. NaN pixels propagate through untouched. |
required |
mean
|
Float[ndarray, '*stat'] | float
|
Scalar or per-band mean :math: |
required |
std
|
Float[ndarray, '*stat'] | float
|
Scalar or per-band standard deviation :math: |
required |
reduce_axes
|
tuple[int, ...] | None
|
Axes the statistics were reduced over. Default
|
(-2, -1)
|
Returns:
| Type | Description |
|---|---|
Float[ndarray, '*dims']
|
Float array of the same shape as |
Raises:
| Type | Description |
|---|---|
TypeError
|
|
Examples:
>>> x = np.array([[[1.0, 3.0]]])
>>> inverse_standard_scale(standard_scale(x, 2.0, 0.5), 2.0, 0.5)
array([[[1., 3.]]])
>>> # a constant band (std 0) round-trips too
>>> inverse_standard_scale(standard_scale(x, 1.0, 0.0), 1.0, 0.0)
array([[[1., 3.]]])
Source code in packages/geotoolz-ops/src/geoops/normalize/_src/array.py
log_scale(arr, *, base=10.0, eps=1e-06)
¶
Apply log scaling with a small offset for zero-valued pixels.
.. math::
y \;=\; \log_{\text{base}}(\max(x, 0) + \epsilon)
Compresses heavy-tailed distributions (radar backscatter, fire
radiative power, ...). Negative inputs are clipped to zero before
the log; eps keeps the log finite at zero.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
Float[ndarray, '*dims']
|
Input float array. NaN pixels propagate through untouched. |
required |
base
|
float
|
Logarithm base. Must be positive and not equal to |
10.0
|
eps
|
float
|
Small positive offset added before the log. Default
|
1e-06
|
Returns:
| Type | Description |
|---|---|
Float[ndarray, '*dims']
|
Float array of the same shape. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in packages/geotoolz-ops/src/geoops/normalize/_src/array.py
match_cdf(x, valid, levels, values, ok)
¶
Map each band of x through its CDF onto a reference_cdf table.
.. math::
y \;=\; G_c^{-1}\big(F_c(x)\big), \qquad
F_c(x) \;=\; \frac{\#\{\text{valid } x' \le x\}}{n_c}
:math:F_c comes from a sort and searchsorted (invalid values sort
last as +inf), and :math:G_c^{-1} is a linear interpolation through
the table, so this is exact rank matching with static shapes: it runs on
NumPy and JAX, under jax.jit too (one trace per shape), and on a
dask block holding whole bands.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Float[ndarray, 'C N']
|
|
required |
valid
|
Shaped[ndarray, 'C N']
|
|
required |
levels
|
Float[ndarray, 'C M']
|
|
required |
values
|
Float[ndarray, 'C M']
|
|
required |
ok
|
Shaped[ndarray, 'C 1']
|
|
required |
Returns:
| Type | Description |
|---|---|
Float[ndarray, 'C N']
|
|
Example
table = reference_cdf(np.array([[10.0, 20.0, 30.0]]), None) x = np.array([[2.0, 0.0, 1.0]]) match_cdf(x, np.isfinite(x), *table) array([[30., 10., 20.]])
Source code in packages/geotoolz-ops/src/geoops/normalize/_src/array.py
minmax_scale(arr, vmin, vmax, *, out_range=(0.0, 1.0), reduce_axes=(-2, -1))
¶
Linearly map [vmin, vmax] into out_range.
.. math::
y \;=\; \frac{x - v_{\min}}{v_{\max} - v_{\min}}
\cdot (o_{\max} - o_{\min}) + o_{\min}
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
Float[ndarray, '*dims']
|
Input float array. NaN pixels propagate through untouched. |
required |
vmin
|
Float[ndarray, '*stat'] | float
|
Scalar or per-band lower bound (maps to |
required |
vmax
|
Float[ndarray, '*stat'] | float
|
Scalar or per-band upper bound (maps to |
required |
out_range
|
tuple[float, float]
|
|
(0.0, 1.0)
|
reduce_axes
|
tuple[int, ...] | None
|
Axes the bounds were reduced over. Default |
(-2, -1)
|
Returns:
| Type | Description |
|---|---|
Float[ndarray, '*dims']
|
Float array of the same shape as |
Float[ndarray, '*dims']
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in packages/geotoolz-ops/src/geoops/normalize/_src/array.py
per_band_stats(arr, *, percentiles=(1.0, 99.0), reduce_axes=(-2, -1))
¶
Compute NaN-aware statistics over spatial axes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
Float[ndarray, '*dims']
|
Input float array, typically a channel-first |
required |
percentiles
|
list[float] | tuple[float, ...]
|
Percentiles (in |
(1.0, 99.0)
|
reduce_axes
|
tuple[int, ...] | None
|
Axes to reduce over. Default |
(-2, -1)
|
Returns:
| Type | Description |
|---|---|
dict[str, ndarray]
|
Dict with keys |
dict[str, ndarray]
|
(each shaped like the kept axes, e.g. |
dict[str, ndarray]
|
|
Source code in packages/geotoolz-ops/src/geoops/normalize/_src/array.py
power_scale(arr, *, gamma=0.5)
¶
Apply non-negative power scaling.
.. math::
y \;=\; \max(x, 0)^{\gamma}
A simple gamma-style brightness curve; negative inputs are clipped to zero before the power to avoid complex results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
Float[ndarray, '*dims']
|
Input float array. NaN pixels propagate through untouched. |
required |
gamma
|
float
|
Power exponent. |
0.5
|
Returns:
| Type | Description |
|---|---|
Float[ndarray, '*dims']
|
Float array of the same shape. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in packages/geotoolz-ops/src/geoops/normalize/_src/array.py
reference_cdf(reference, valid)
¶
The per-band empirical CDF of reference, as a padded table for match_cdf.
For each band, the distinct valid values :math:v_1 < \dots < v_m and
their cumulative fractions :math:G(v_k) = \#\{x \le v_k\} / n, the
points that scikit-image's match_histograms interpolates through.
Bands have different numbers of distinct values, so each row is padded to
the longest with levels above 1 and its maximum, which an
interpolation at a fraction in [0, 1] never reaches. Host NumPy only:
a reference is concrete, and its table is a constant for match_cdf.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reference
|
Float[ndarray, 'C N']
|
|
required |
valid
|
Shaped[ndarray, 'C N']
|
|
required |
Returns:
| Type | Description |
|---|---|
``(levels, values, ok)``
|
|
Float[ndarray, 'C M']
|
|
Example
levels, values, ok = reference_cdf(np.array([[1.0, 1.0, 3.0]]), None) levels.tolist(), values.tolist(), ok.tolist() ([[0.6666666666666666, 1.0]], [[1.0, 3.0]], [[True]])
Source code in packages/geotoolz-ops/src/geoops/normalize/_src/array.py
robust_scale(arr, median, iqr, *, reduce_axes=(-2, -1))
¶
Apply median/IQR scaling while preserving NaN pixels.
.. math::
y \;=\; \frac{x - \mathrm{median}}{Q_{3} - Q_{1}}
The outlier-robust counterpart of :func:standard_scale — bright
outliers (clouds, glint, saturation) barely move the median and
interquartile range.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
Float[ndarray, '*dims']
|
Input float array. NaN pixels propagate through untouched. |
required |
median
|
Float[ndarray, '*stat'] | float
|
Scalar or per-band median (shape matching the kept axes). |
required |
iqr
|
Float[ndarray, '*stat'] | float
|
Scalar or per-band interquartile range |
required |
reduce_axes
|
tuple[int, ...] | None
|
Axes the statistics were reduced over. Default
|
(-2, -1)
|
Returns:
| Type | Description |
|---|---|
Float[ndarray, '*dims']
|
Float array of the same shape as |
Source code in packages/geotoolz-ops/src/geoops/normalize/_src/array.py
standard_scale(arr, mean, std, *, reduce_axes=(-2, -1))
¶
Apply z-score scaling while preserving NaN pixels.
.. math::
y \;=\; \frac{x - \mu}{\sigma}
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
Float[ndarray, '*dims']
|
Input float array. NaN pixels propagate through untouched. |
required |
mean
|
Float[ndarray, '*stat'] | float
|
Scalar or per-band mean :math: |
required |
std
|
Float[ndarray, '*stat'] | float
|
Scalar or per-band standard deviation :math: |
required |
reduce_axes
|
tuple[int, ...] | None
|
Axes the statistics were reduced over. Default
|
(-2, -1)
|
Returns:
| Type | Description |
|---|---|
Float[ndarray, '*dims']
|
Float array of the same shape as |