Banner

Remote Sensing Fundamentals

Remote sensing is the measurement of an object’s properties without touching it, usually by recording electromagnetic (EM) energy reflected or emitted from the Earth’s surface.

Five notebooks in this part, then the chapters that follow, take that measurement from the sensor to a map, using geolattice.rsense.

  • Remote Sensing Fundamentals. This notebook. What a remote sensing measurement is, and how the chapters that follow turn it into a map.

  • The Python Geospatial Environment. NumPy, xarray, rioxarray, GeoPandas, Dask, and the CPU/GPU backend of geolattice.rsense.

  • Raster and Vector Data Essentials. Read a raster, check its metadata, reproject it, cut it to a study area, combine tiles, summarise it over polygons, and save the result.

  • Data Discovery and Access. Find scenes in public archives and load only the pixels you need, through STAC, Cloud-Optimized GeoTIFFs, and lazy data cubes.

  • Getting Access to Remote Sensing Images. Which catalogue holds which image, and which GeoLattice call opens it.

  • Introduction to Optical Satellite Images. Sunlight in visible, near-infrared and shortwave-infrared light: preprocessing, then MODIS, Landsat, Sentinel-2, Sentinel-3, and Sentinel-5P.

  • SAR Fundamentals. Microwave echoes, day and night through clouds, in three mission blocks: Sentinel-1, RADARSAT, and NISAR.

  • UAV Fundamentals and Mission Planning. A drone mission from the flight plan to measured crop traits.

  • Introduction to Imaging Spectroscopy. Hundreds of narrow bands, from the sensor file to a map.

  • LiDAR Fundamentals. A point cloud from the instrument to a map.

  • Texture Analysis. Pattern and roughness that brightness alone does not show, on a Landsat 9 scene over Las Vegas.

  • Image Super-Resolution. A finer image consistent with a coarse observation, from Landsat through Sentinel-2 and PlanetScope to 0.6 m imagery.

  • Introduction to Image Classification. A grid of numbers turned into a map of categories, from a Landsat scene to foundation models.

  • Object Detection. Boxes in aerial tiles, and field parcels in Bangladesh and the US Corn Belt.

  • What Foundation Models Are and Why Remote Sensing Needs Them. A network trained once without labels, then reused for embeddings, segmentation, and maps with few labels.

  • Capstones:

    Thirty-five Years of Change around Pucallpa, Peru,

    Fifty Years of Change in the Bangladesh Delta,

    Wild Fire Burned-area Mapping,

    Timeline of the Rohingya Exodus: Deforestation in Bangladesh (2016-2018),

    Flood Mapping with Sentinel-1 Data - Sylhet, Bangladesh,

    Timeline of the Rohingya Exodus: Deforestation in Bangladesh (2016-2018), Sentinel-1 Radar,

    Ship Detection in the Strait of Hormuz with Sentinel-1,

    Crop Classification with NISAR GCOV Time Series and Self-Supervised Learning,

    Sea Ice Mapping for Shipping Routes in the St. Lawrence Estuary with RADARSAT Constellation Mission (RCM),

    Charland Monitoring with Sentinel-1 SAR (and NISAR L-band), Lower Meghna Estuary of Bangladesh,

    Mapping Shrimp Ghers in Coastal Bangladesh with a 2025–2026 Sentinel-1 Time Series and Sentinel-2,

    Mapping the 2026 Big Sur Wildfire with Time-Series Sentinel-1 SAR and Sentinel-2 Optical Images,

    Field Edge Detection across Four Countries: Training in Mexico, Mali, Cambodia and Bangladesh, Testing on an Unseen Bangladesh Site, and

    Tree Inventory, Biomass and Carbon from Airborne Lidar. Fourteen studies that apply the methods.

Overview

Every technique in this course, from NDVI to InSAR, rests on a handful of physical ideas. This module builds them up from the physics, surveys the branches and applications of the field, introduces the remote sensing toolkit of GeoLattice (geolattice.rsense), and tests each idea on real Landsat 8 and Sentinel-2 data from the GeoLattice data folder in DropBox.

Core concepts

Learning objectives

  1. Define remote sensing and describe the chain from energy source to information product.
  2. Place optical, thermal and microwave sensors on the electromagnetic spectrum, and use Planck’s and Wien’s laws to explain why the Sun dominates reflected wavelengths and the Earth dominates thermal wavelengths.
  3. Explain how the atmosphere scatters and absorbs radiation, and how energy interacts with the surface (reflection, absorption, transmission, emission).
  4. Name the main branches of remote sensing (by energy source, spectral region, platform and spectral resolution) and their typical applications.
  5. Find the right function in geolattice.rsense for a task.
  6. Extract and interpret spectral signatures of water, vegetation and built surfaces.
  7. Explain spatial, spectral, temporal and radiometric resolution, and see their effect on data.
  8. Convert digital numbers (DN) to radiance, reflectance and brightness temperature using a real Landsat metadata file.

Data

Source Used for
Data/00_shared/data_remote_sensing/Landsat8_RAW/ (scene + *_MTL.txt) Landsat 8 Level-1 over New York: band placement, solar spectrum, DN→radiance/reflectance/BT
Data/00_shared/data_remote_sensing/Sentinel_2/ Sentinel-2 bands and ground-truth polygons for spectral signatures near Buffalo, NY
Data/00_shared/data_remote_sensing/LC09_L2SP_138043_20221216_20221223_02_T1/ Landsat 9 Level-2 surface reflectance window over northwestern Bangladesh

Contents

  1. What is remote sensing?
  2. Physical principles
  3. Branches of remote sensing
  4. Applications
  5. Remote sensing in GeoLattice: geolattice.rsense
  6. Setup and data
  7. Where satellite bands sit on the spectrum
  8. Spectral signatures from real images
  9. Physics in the data: the Sun’s spectrum and atmospheric scattering
  10. The four resolutions
  11. Passive and active sensors
  12. Processing levels: from DN to physical units
  13. Summary and exercises

What is remote sensing?

Remote sensing is the acquisition of information about an object or area from a distance, typically from aircraft, drones or satellites, by measuring electromagnetic radiation that the object reflects, emits or scatters back. A sensor never touches the surface: it records a number, and the science of remote sensing is turning that number into a physical quantity (reflectance, temperature, backscatter, height) and then into information (land cover, crop health, flood extent, ground motion).

The remote sensing process

Every remote sensing system, from a smartphone camera to a radar satellite, follows the same chain (Lillesand, Kiefer & Chipman, 2015; Jensen, 2007):

Step What happens Example
A. Energy source The Sun (passive) or the sensor itself (active) illuminates the target Sunlight; a radar pulse
B. Path to the target Radiation passes through the atmosphere and is partly scattered and absorbed Blue light scattered by air molecules
C. Interaction with the target The surface reflects, absorbs, transmits and emits energy depending on its properties Leaves reflect near-infrared strongly
D. Path to the sensor The returning signal crosses the atmosphere again Haze adds “path radiance”
E. Recording The sensor converts radiance into digital numbers 12-bit Landsat OLI counts
F. Transmission and processing Data are downlinked, calibrated, geolocated and corrected Level-1 → Level-2 products
G. Interpretation and analysis Physical values become information NDVI, land-cover maps, change maps
H. Application Information supports a decision Irrigation scheduling, disaster response

A short history

Year Milestone
1858 Gaspard-Félix Tournachon (“Nadar”) takes the first aerial photograph, from a balloon over Paris
1909 to 1918 Aerial photography from aircraft; systematic military reconnaissance in World War I
1940s Radar and colour-infrared film developed during World War II
1960 TIROS-1, the first weather satellite; the term “remote sensing” is coined (Evelyn Pruitt, U.S. Office of Naval Research)
1972 Landsat 1 (ERTS-1) begins the longest continuous record of Earth’s land surface
1978 Seasat, the first civilian spaceborne synthetic aperture radar (SAR)
1999 Terra/MODIS, daily global multispectral observation; IKONOS, first commercial sub-metre satellite
2014 to 2017 Copernicus Sentinel-1 (SAR) and Sentinel-2 (multispectral) with free and open data
2018 to 2019 GEDI and ICESat-2 bring spaceborne lidar for forest structure and elevation
2020s Small-satellite constellations, hyperspectral missions (EnMAP, EMIT, PRISMA) and L-band SAR (NISAR)

The open-data policies of Landsat (2008) and Copernicus (2014) turned remote sensing into a data-science discipline: petabytes of analysis-ready imagery are now searched through STAC catalogues and processed in the cloud, which is the workflow geolattice.rsense is built for.

Physical principles

The electromagnetic spectrum

EM energy travels as waves; the wavelength λ and frequency ν are linked by the speed of light, \(c = \lambda \nu\), and each photon carries energy \(E = h\nu = hc/\lambda\). Shorter wavelengths therefore mean more energetic photons.

Remote sensing uses several broad regions of the spectrum:

Region Wavelength What sensors measure Examples
Visible (VIS) 0.4 to 0.7 µm Reflected sunlight Landsat B2 to B4, Sentinel-2 B2 to B4
Near infrared (NIR) 0.7 to 1.3 µm Reflected sunlight; very bright for leaves Landsat B5, Sentinel-2 B8
Shortwave infrared (SWIR) 1.3 to 3 µm Reflected sunlight; sensitive to water content and minerals Landsat B6 to B7, Sentinel-2 B11 to B12
Mid-wave infrared (MWIR) 3 to 8 µm Mixed reflected and emitted energy; very hot targets MODIS fire bands (3.9 µm)
Thermal infrared (TIR) 8 to 14 µm Energy emitted by the surface (temperature) Landsat B10 to B11, MODIS LST
Microwave 1 mm-1 m Active radar echoes or passive emission Sentinel-1 (C-band, 5.6 cm), NISAR (L-band, 24 cm)
Code

# This code creates a visual representation of the regions of the electromagnetic (EM) spectrum
# that are used in remote sensing, and highlights the typical wavelength ranges and sensor channels.
# Here is what each part does:

# %matplotlib inline: ensures that plots display inline when using a Jupyter Notebook.

import warnings
warnings.filterwarnings("ignore", category=UserWarning)      # Suppress UserWarnings (usually from matplotlib)

import numpy as np  # arrays
import pandas as pd  # tables
import matplotlib.pyplot as plt  # figures

# Set figure display parameters for clarity in the notebook.
plt.rcParams.update({
    "figure.dpi": 110,    # Higher DPI for sharper figures
    "axes.grid": True,    # Show grid by default
    "grid.alpha": 0.3     # Light grid lines
})

# Define the major EM spectrum regions used in remote sensing as a list of tuples:
# Each tuple = (region_name, wavelength_start [m], wavelength_end [m], color_as_hex)
regions = [
    ("UV", 1e-8, 4e-7, "#7b3294"),
    ("Visible", 4e-7, 7e-7, "#ffd92f"),
    ("NIR", 7e-7, 1.3e-6, "#e66101"),
    ("SWIR", 1.3e-6, 3e-6, "#b2182b"),
    ("MWIR", 3e-6, 8e-6, "#d6604d"),
    ("TIR", 8e-6, 1.4e-5, "#f4a582"),
    ("Far IR", 1.4e-5, 1e-3, "#fddbc7"),
    ("Microwave", 1e-3, 1.0, "#4393c3"),
]

# Create a figure and axes object for the plot.
fig, ax = plt.subplots(figsize=(11, 2.4))

# Plot each region as a colored band (axvspan) and add its label:
for name, a, b, col in regions:
    ax.axvspan(a, b, color=col, alpha=0.8)                       # Fill band for each spectrum region
    # Place region name at geometric mean (center in log space); vertical if narrow region
    ax.text(np.sqrt(a * b), 0.5, name, ha="center", va="center",
            fontsize=9, rotation=90 if b / a < 3 else 0)

# Add annotations for notable remote sensing satellite sensors and their wavelengths:
for label, wl in [
    ("Sentinel-2 B4\n665 nm", 665e-9),
    ("Landsat B10\n10.9 µm", 10.9e-6),
    ("Sentinel-1\nC-band 5.6 cm", 0.0556),
]:
    # Draw an arrow and label at the corresponding wavelength
    ax.annotate(
        label, (wl, 1.0), xytext=(wl, 1.55), ha="center", fontsize=8,
        arrowprops=dict(arrowstyle="->")
    )

# Final plot settings:
ax.set_xscale("log")                                   # X axis as log scale (for wavelength)
ax.set_xlim(1e-8, 1)                                   # Range: 10 nm to 1 m
ax.set_ylim(0, 2)                                      # Unused y scale, for display
ax.set_yticks([])                                      # Hide y-axis ticks
ax.set_xlabel("Wavelength (m)")                        # Label x-axis
ax.set_title("Regions of the EM spectrum used in remote sensing")  # Set plot title
ax.grid(False)                                         # Remove default grid (already colored regions)
plt.tight_layout()                                     # Adjust layout to fit
plt.show()                                             # Display the plot

Code
# This code calculates and prints the wavelength (λ), frequency (ν), and energy per photon for different types of electromagnetic radiation relevant to remote sensing.
# Physical constants:
h = 6.626e-34  # Planck constant in joule-seconds (J·s)
c = 2.998e8    # Speed of light in meters per second (m/s)

# List of named wavelengths in meters for common remote sensing wavebands:
bands = [
    ("Blue light", 0.49e-6),      # Visible blue
    ("NIR", 0.86e-6),             # Near-infrared
    ("Thermal IR", 10.9e-6),      # Thermal infrared
    ("C-band radar", 0.0556),     # Microwave (C-band radar)
]

# Calculate and print properties for each wavelength:
for name, wl in bands:
    frequency = c / wl                # Frequency in Hz
    photon_energy = h * frequency     # Photon energy in joules
    # wavelength, frequency and photon energy of each region
    print(f"{name:13s} λ = {wl:9.3e} m   ν = {frequency:9.3e} Hz   photon energy = {photon_energy:9.3e} J")
Blue light    λ = 4.900e-07 m   ν = 6.118e+14 Hz   photon energy = 4.054e-19 J
NIR           λ = 8.600e-07 m   ν = 3.486e+14 Hz   photon energy = 2.310e-19 J
Thermal IR    λ = 1.090e-05 m   ν = 2.750e+13 Hz   photon energy = 1.822e-20 J
C-band radar  λ = 5.560e-02 m   ν = 5.392e+09 Hz   photon energy = 3.573e-24 J

A blue photon carries about 100,000 times more energy than a C-band radar photon. That is why optical detectors count photons with semiconductors while radar receivers measure the amplitude and phase of a wave, and why microwave radiation passes through clouds that block visible light.

Blackbody radiation: why the Sun and the Earth shine in different bands

Every object above absolute zero emits radiation. For an ideal emitter (a blackbody) the spectral radiance at temperature \(T\) follows Planck’s law:

\[B_\lambda(T) = \frac{2hc^2}{\lambda^5} \, \frac{1}{e^{hc/(\lambda k_B T)} - 1}\]

Two consequences follow:

  • Wien’s displacement law: the wavelength of peak emission is \(\lambda_{max} = 2898\,\mu m\,K / T\).
  • Stefan-Boltzmann law: the total emitted power grows as \(M = \varepsilon\sigma T^4\), where \(\sigma = 5.67\times10^{-8}\,W\,m^{-2}K^{-4}\) and \(\varepsilon \le 1\) is the emissivity. Real surfaces are grey bodies with \(\varepsilon\) between about 0.9 (dry soil) and 0.99 (water), which is why thermal remote sensing must correct for emissivity.

Comparing the Sun (≈5,778 K) with the Earth’s surface (≈300 K) explains the split between reflective and emissive remote sensing.

Code
# This code compares the blackbody radiation curves (spectral radiance) of the Sun and the Earth,
# and illustrates why they emit at very different wavelengths.

# Boltzmann constant in J/K
kB = 1.381e-23

# Define a range of wavelengths in meters: from 0.1 µm to 100 µm (for plotting)
wl = np.logspace(-7, -4, 2000)  # 1e-7 m = 0.1 µm, 1e-4 m = 100 µm

# Planck's law: returns spectral radiance B_lambda for wavelength(s) wl [m] and temperature T [K]
def planck(wl, T):
    # The formula returns radiance in W m⁻² sr⁻¹ m⁻¹
    return 2 * h * c**2 / wl**5 / (np.exp(h * c / (wl * kB * T)) - 1)

# Get the radiance curves for the Sun (5778 K) and the Earth (300 K)
# The Sun's radiance is scaled to represent the apparent radiance at Earth's distance (by solid angle factor)
sun = planck(wl, 5778) * (6.96e8 / 1.496e11) ** 2     # (Sun radius / Earth-Sun distance)^2
earth = planck(wl, 300)  # Planck curve of the Earth's surface at 300 K

# Plot both curves on a log-log plot (wavelength in microns)
fig, ax = plt.subplots(figsize=(9, 4.5))
# sunlight on log-log axes (wavelength in µm)
ax.loglog(wl * 1e6, sun, label="Sunlight at the top of the atmosphere (5,778 K)")
ax.loglog(wl * 1e6, earth, label="Earth's surface (300 K)")  # Earth emission

# Highlight important spectral regions for remote sensing
# Visible window
ax.axvspan(0.4, 0.7, color="gold", alpha=0.2, label="Visible")
# Thermal IR "window" (where Earth's emission escapes to space most easily)
ax.axvspan(8, 14, color="tomato", alpha=0.15, label="Thermal window 8–14 µm")

ax.set_ylim(1e3, 1e8)  # radiance range shown
ax.set_xlabel("Wavelength (µm)")  # x label
ax.set_ylabel("Spectral radiance (W m⁻² sr⁻¹ m⁻¹)")  # y label
ax.legend(fontsize=8)  # legend
ax.set_title("Planck curves: reflected sunlight vs emitted Earth radiation")  # title
plt.tight_layout()  # arrange
plt.show()  # draw

# Compute and print the wavelength of peak emission (Wien's law) and total radiated power (Stefan–Boltzmann law)
for name, T in [("Sun", 5778), ("Earth", 300), ("Forest fire", 1000)]:
    peak = 2898 / T  # Wien's law: peak wavelength in µm
    total = 5.67e-8 * T**4  # Stefan–Boltzmann law: total emittance in W/m²
    # peak wavelength (Wien) and total emitted power (Stefan-Boltzmann)
    print(f"{name:12s} T = {T:5d} K  → peak emission at {peak:6.2f} µm,  σT⁴ = {total:12,.0f} W/m²")

# Find the wavelength where Sun and Earth radiance curves cross (emitted power equal)
crossover = wl[np.argmin(np.abs(np.log(sun) - np.log(earth)))] * 1e6  # Convert to µm
print(f"Sunlight and Earth emission are equal near {crossover:.1f} µm")  # where the two curves cross

Sun          T =  5778 K  → peak emission at   0.50 µm,  σT⁴ =   63,196,527 W/m²
Earth        T =   300 K  → peak emission at   9.66 µm,  σT⁴ =          459 W/m²
Forest fire  T =  1000 K  → peak emission at   2.90 µm,  σT⁴ =       56,700 W/m²
Sunlight and Earth emission are equal near 4.6 µm

Interpretation. Sunlight peaks around 0.5 µm (green light) and dominates below about 4 µm, so optical sensors in the VIS, NIR and SWIR measure reflected solar energy. Beyond roughly 4 µm the Earth’s own emission takes over, so thermal sensors measure temperature. A forest fire at 1,000 K peaks near 2.9 µm and radiates more than 100 times as much power per square metre as the ground around it, which is why fire products use mid-infrared bands.

The atmosphere: scattering, absorption and windows

Radiation crosses the atmosphere twice in passive optical remote sensing (Sun → surface → sensor). Two processes change it on the way.

Scattering redirects radiation. Its strength depends on the size of the particle relative to the wavelength:

Type Particles Wavelength dependence Visible effect
Rayleigh Gas molecules (≪ λ) \(\propto \lambda^{-4}\) Blue sky; haze strongest in blue bands
Mie Aerosols, smoke, dust (≈ λ) roughly \(\lambda^{-1}\) to \(\lambda^{0}\) Hazy, washed-out images
Non-selective Cloud droplets, ice (≫ λ) none White clouds

Scattered light that reaches the sensor without touching the surface is path radiance. It brightens dark targets, especially in the blue, and lowers image contrast. Atmospheric correction (the Processing levels: from DN to physical units section) removes it.

Absorption removes energy at specific wavelengths: ozone (O₃) in the ultraviolet, water vapour (H₂O) near 0.94, 1.14, 1.38, 1.87 and 2.7 µm and above 5 µm, carbon dioxide (CO₂) near 2.0, 4.3 and 15 µm, and oxygen (O₂) at 0.76 µm. The spectral regions where the atmosphere is mostly transparent are the atmospheric windows, and sensor bands are placed inside them:

Window Used by
0.3 to 1.3 µm (VIS-NIR) All multispectral sensors
1.5 to 1.8 µm and 2.0 to 2.4 µm (SWIR) Landsat B6/B7, Sentinel-2 B11/B12
3.5 to 4.2 µm (MWIR) Fire detection (MODIS, VIIRS)
8 to 14 µm (TIR), split by ozone at 9.6 µm Landsat B10/B11, ECOSTRESS
> 1 cm (microwave) Radar; almost unaffected by clouds

The opposite trick is also useful: bands placed inside an absorption feature measure the absorber itself. Landsat 8 band 9 (1.37 µm) sits in a strong water-vapour band, so the ground is invisible and only high cirrus clouds appear bright.

The code below compares the relative strength of Rayleigh scattering across the Landsat 8 reflective bands. The Physics in the data: the Sun’s spectrum and atmospheric scattering section tests this \(\lambda^{-4}\) law on a real image.

Code
# This cell shows why blue light is scattered much more than red light.
#
# Rayleigh scattering (molecules in clear air) gets weaker as wavelength gets longer.
# The strength scales as 1 / wavelength^4. Dividing each Landsat band by the red band
# and raising that ratio to the power -4 answers: "how many times more does this band
# scatter than red?"
#
# 1. Store the centre wavelength (micrometres) of each Landsat 8 reflective band.
# 2. Compute the Rayleigh ratio relative to the red band.
# 3. Show both numbers side by side. Coastal and blue come out several times stronger
#    than red; the SWIR bands barely scatter at all.

oli = pd.Series({"coastal (B1)": 0.443, "blue (B2)": 0.482, "green (B3)": 0.561, "red (B4)": 0.655,
                 "nir (B5)": 0.865, "swir16 (B6)": 1.609, "swir22 (B7)": 2.201}, name="centre_um")
# (λ_band / λ_red) ^ -4. A value of 4 means "scattered four times as much as red".
rayleigh = (oli / oli["red (B4)"]) ** -4
# band centres and their relative Rayleigh scattering
pd.DataFrame({"centre (µm)": oli, "Rayleigh scattering relative to red": rayleigh.round(2)})
centre (µm) Rayleigh scattering relative to red
coastal (B1) 0.443 4.78
blue (B2) 0.482 3.41
green (B3) 0.561 1.86
red (B4) 0.655 1.00
nir (B5) 0.865 0.33
swir16 (B6) 1.609 0.03
swir22 (B7) 2.201 0.01

Blue light is scattered about three times more strongly than red, and the coastal/aerosol band almost five times more. SWIR bands are nearly free of molecular scattering, which is why SWIR composites look sharp even on hazy days.

Energy-matter interactions at the surface

Radiation reaching the surface is split three ways. By conservation of energy, at each wavelength

\[E_I(\lambda) = E_R(\lambda) + E_A(\lambda) + E_T(\lambda),\]

the incident energy equals the reflected, absorbed and transmitted parts. Dividing by \(E_I\) gives the reflectance, absorptance and transmittance, which sum to one. Remote sensing of reflected energy measures the spectral reflectance

\[\rho(\lambda) = \frac{E_R(\lambda)}{E_I(\lambda)},\]

and the curve of \(\rho\) against wavelength is the material’s spectral signature (the Spectral signatures from real images section). Kirchhoff’s law links absorption and emission: a surface in thermal equilibrium emits as well as it absorbs at each wavelength (\(\varepsilon_\lambda = \alpha_\lambda\)), so for an opaque surface \(\varepsilon_\lambda = 1 - \rho_\lambda\). That is why water, a poor reflector in the thermal infrared, is an almost perfect emitter.

The geometry of reflection matters too:

  • A specular surface (calm water, smooth roofs) reflects like a mirror. It looks either very dark or, at the mirror angle, dazzlingly bright (sun glint).
  • A Lambertian (perfectly diffuse) surface reflects equally in all directions, so its radiance does not depend on viewing angle. Most land surfaces are treated as approximately Lambertian.
  • Real surfaces lie in between. Their directional behaviour is described by the bidirectional reflectance distribution function (BRDF): forests look brighter with the Sun behind the observer (the “hot spot”) because shadows are hidden.

For microwaves the controlling properties are different: surface roughness relative to the wavelength, dielectric constant (mainly moisture) and geometry (corner reflectors in cities, volume scattering in canopies). The radar notebooks (07_03) develop these for SAR.

Radiometric quantities and the radiative transfer equation

Quantity Symbol Unit Meaning
Radiant flux Φ W Energy per unit time
Irradiance E W m⁻² Flux arriving on a surface
Exitance M W m⁻² Flux leaving a surface
Radiance L W m⁻² sr⁻¹ µm⁻¹ Flux per area, per solid angle, per wavelength: what a sensor measures
Reflectance ρ , Ratio of reflected to incident flux (0 to 1)

For a Lambertian surface the radiance reaching a sensor at the top of the atmosphere is

\[L_{sensor}(\lambda) = \frac{\rho(\lambda)\,E_{sun}(\lambda)\cos\theta_s\,T_{\downarrow}(\lambda)\,T_{\uparrow}(\lambda)}{\pi\,d^2} + L_{path}(\lambda),\]

with exo-atmospheric solar irradiance \(E_{sun}\), solar zenith angle \(\theta_s\), Earth-Sun distance \(d\) (astronomical units), downward and upward atmospheric transmittances \(T\), and path radiance \(L_{path}\). Setting \(T = 1\) and \(L_{path} = 0\) and solving for \(\rho\) gives the top-of-atmosphere (TOA) reflectance

\[\rho_{TOA} = \frac{\pi\,L_{sensor}\,d^2}{E_{sun}\cos\theta_s}.\]

Estimating \(T\) and \(L_{path}\) (from radiative transfer models, or from dark objects in the image) gives surface reflectance, the starting point of most analysis. The Physics in the data: the Sun’s spectrum and atmospheric scattering section uses this equation to recover the solar spectrum from a real Landsat metadata file.

Branches of remote sensing

Remote sensing is a family of techniques. They are usually grouped four ways.

By energy source

Branch Principle Strengths Limitations
Passive Records natural energy: reflected sunlight or emitted heat Rich spectral information, long archives, cheap Needs daylight (optical) and clear skies
Active Sends its own pulse and records the echo Day and night; radar sees through clouds; measures range and structure Complex geometry, speckle, fewer bands

By spectral region

Branch Wavelengths What it measures Typical sensors In this course
Optical (multispectral) 0.4 to 2.5 µm, 4 to 15 bands Surface reflectance: vegetation, water, soils, built-up areas Landsat 8/9, Sentinel-2, MODIS, PlanetScope Part II (07_02)
Hyperspectral (imaging spectroscopy) 0.4 to 2.5 µm, 100 to 400 narrow contiguous bands Detailed spectra: minerals, plant pigments, water quality EnMAP, PRISMA, EMIT, AVIRIS 07_06
Thermal infrared 3 to 14 µm Surface temperature and emissivity Landsat TIRS, ECOSTRESS, MODIS 07_02, the Processing levels: from DN to physical units section
Passive microwave 1 mm-30 cm Natural microwave emission: soil moisture, sea ice, rainfall SMAP, SMOS, AMSR2 ,
Radar (SAR) 1 cm-1 m Backscatter, phase and polarisation: structure, moisture, deformation (InSAR) Sentinel-1, NISAR, RADARSAT, ALOS-2 Part III (07_03)
Lidar Laser, usually 532 or 1064 nm Range to targets: terrain, canopy height, 3-D structure Airborne lidar (USGS 3DEP), GEDI, ICESat-2 07_05

By platform

Platform Altitude Typical pixel size Examples
Ground and proximal 0 to 100 m mm-cm Spectroradiometers, terrestrial lidar, phenocams
Unoccupied aerial vehicles (UAV, drones) 30 to 120 m 1 to 10 cm RGB, multispectral and thermal drone cameras (07_04)
Aircraft 1 to 20 km 0.1 to 5 m NAIP aerial photography, AVIRIS, airborne lidar
Low Earth orbit (LEO) satellites 400 to 900 km 0.3 m-1 km Landsat, Sentinel, WorldView
Geostationary satellites 35,786 km 0.5 to 2 km GOES, Himawari, Meteosat: images every 5 to 15 minutes

Most land-imaging satellites fly sun-synchronous polar orbits, crossing the equator at the same local time on every pass (about 10:00 to 10:30 for Landsat and Sentinel-2), so illumination is comparable between dates.

By spectral resolution

  • Panchromatic: one broad band (for example Landsat 8 band 8, 15 m), finest spatial detail.
  • Multispectral: a few broad bands (Landsat, Sentinel-2).
  • Hyperspectral: hundreds of narrow, contiguous bands, enough to identify materials by the shape of their spectra.

Applications

Remote sensing is used wherever a quantity varies over space and time and is hard to measure on the ground everywhere.

Domain Typical questions Data and methods geolattice.rsense tools
Agriculture Crop type, crop health, yield, irrigation, drought NDVI/EVI time series, phenology, SAR for cloudy seasons, thermal water stress optical.index, timeseries.phenology, timeseries.vhi, uav.cwsi
Forestry Forest cover and loss, canopy height, biomass, fire Change detection, lidar canopy height, GEDI, burn indices (NBR) classify.cva, lidar.chm, lidar.detect_trees, timeseries.bfast_monitor
Water resources and floods Surface water extent, flood mapping, water quality NDWI/MNDWI, SAR backscatter thresholds, optical-SAR fusion sar.flood_map, optical.index, fusion.sar_gap_fill
Urban studies Urban growth, impervious surfaces, heat islands Classification, NDBI, land surface temperature classify.Classifier, optical.landsat_lst, optical.surface_urban_heat_island
Natural hazards Earthquakes, landslides, subsidence, volcanoes InSAR deformation, change detection, rapid mapping insar.interferogram, insar.sbas_inversion, sar.change_map
Climate and cryosphere Snow cover, glaciers, sea ice, surface temperature trends NDSI, thermal time series, passive microwave optical.index, timeseries.anomaly, timeseries.ccdc
Oceans and coasts Ocean colour, sea surface temperature, shoreline change, oil spills Chlorophyll indices, thermal bands, SAR sar.oil_spill_detection, sar.cfar (ship detection)
Geology and soils Mineral mapping, soil organic carbon, erosion SWIR and hyperspectral spectra, terrain analysis optical.unmix, lidar.geomorphons
Environmental and public health Heat exposure, air quality, vector habitats, green space LST, vegetation indices, land cover linked to health records optical.landsat_lst, core.zonal_stats
Biodiversity and conservation Habitat mapping, protected-area monitoring Classification, structure from lidar, explainable ML classify, xai.aoa, xai.SpatialBlockCV

The capstone notebooks in 08_11_Capstones work through agriculture, hazards, forestry, precision agriculture and environmental health end to end.

Remote sensing in GeoLattice: geolattice.rsense

GeoLattice bundles a complete remote sensing toolkit in the subpackage geolattice.rsense. Rasters are xarray objects with a coordinate reference system (through rioxarray), and every array operation can run on the CPU (NumPy) or on an NVIDIA GPU (CuPy) through one backend switch. Install it with

pip install "geolattice[rsense]"          # core: xarray, rioxarray, rasterio, scikit-image
pip install "geolattice[rsense-all]"      # data access, SAR, InSAR, lidar, UAV, ML, DL, XAI, viz, scaling

and import it as import geolattice.rsense as rs. Heavy optional dependencies (PyTorch, Earth Engine, PDAL, …) are imported only when a function needs them.

Submodule Purpose
backend Choose CPU or GPU (set_backend), move arrays (to_device, to_cpu), precision and memory
core Read and write rasters (GeoTIFF, COG, NetCDF, HDF, Zarr, SAFE), reproject, clip, mosaic, tile, zonal statistics, data cubes and point clouds
access Search and download data: STAC (Earth Search, Planetary Computer), Google Earth Engine, ASF (SAR), Copernicus Data Space (CDSE), NASA Earthdata
optical Sensor loaders (Landsat, Sentinel-2, HLS, MODIS), scaling, cloud masks, 100+ spectral indices, compositing, radiometric and atmospheric correction, land surface temperature, spectral unmixing
sar Sentinel-1 calibration, speckle filters, multilooking, dB conversion, PolSAR decompositions, change detection, flood, ship and oil-spill mapping
insar Interferograms, filtering, phase unwrapping, atmospheric correction, SBAS time series, line-of-sight to vertical motion; HyP3, ISCE and MintPy interfaces
uav OpenDroneMap processing, radiometric calibration, canopy height and cover, plant counting, thermal water stress
lidar Point-cloud I/O, ground classification, DTM/DSM/CHM, terrain derivatives, tree detection, forest metrics, GEDI and ICESat-2
timeseries Smoothing (Savitzky-Golay, Whittaker), harmonic fits, phenology, anomalies, drought indices, BFAST-style monitoring, CCDC
classify Pixel classifiers, clustering, object-based image analysis, change detection, accuracy assessment (Olofsson area estimates)
dl Deep learning: tile datasets, U-Net and detection models, training, inference, TorchGeo and foundation-model adapters
fusion STARFM spatiotemporal fusion, optical-SAR and lidar-optical fusion
xai Explainable and trustworthy ML: permutation and SHAP importance, spatial cross-validation, area of applicability, conformal prediction
viz RGB composites, stretches, raster, time-series and point-cloud plots, interactive maps
scale Dask clusters, Zarr data cubes, STAC export for large-area processing
apps Streamlit app templates (change viewer, flood mapper, index explorer)

geolattice.rsense also registers an .rs accessor on every xarray object, so common steps chain naturally, for example ds.rs.scale().rs.mask_clouds().rs.index("NDVI").

The next cells list every public function and class directly from the installed package, with the first line of its documentation.

Code
# This cell checks that geolattice and geolattice.rsense import, and reports which compute
# backend is active.
#
# 1. importlib and inspect are used in the next cells to walk the public API.
# 2. Import the top-level package and the remote-sensing subpackage.
# 3. Print versions, the backend in use (cpu or cuda), and every backend this
#    machine can actually run.

import importlib          # load a submodule by its name string
import inspect            # read functions, classes and docstrings

import geolattice  # GeoLattice
import geolattice.rsense as rs  # GeoLattice remote sensing subpackage

print("geolattice", geolattice.__version__, "| geolattice.rsense", rs.__version__)  # versions
# array backend in use and the ones available
print("backend:", rs.get_backend(), "| available backends:", rs.available_backends())
geolattice 0.3.49 | geolattice.rsense 0.3.49
backend: cpu | available backends: ['cpu', 'cuda']
Code
# This block of code dynamically inspects all public functions and classes in the submodules of `geolattice.rsense`
# and summarizes them in a pandas DataFrame. It then prints a summary table of the counts of functions and classes per submodule.

# List of submodules in geolattice.rsense to inspect
SUBMODULES = [
    "backend", "core", "access", "optical", "sar", "insar", "uav", "lidar",
    "timeseries", "classify", "dl", "fusion", "xai", "viz", "scale", "apps"
]

rows = []  # one row per public function or class

# For each submodule, import it, retrieve its public API, and extract all functions/classes with their descriptions
for sub in SUBMODULES:
    # Dynamically import the submodule
    mod = importlib.import_module(f"geolattice.rsense.{sub}")
    # Get the list of public names, preferring __all__ if present, else all non-private attributes
    public_names = getattr(mod, "__all__", [n for n in dir(mod) if not n.startswith("_")])

    for name in public_names:  # every public name of the submodule
        obj = getattr(mod, name, None)  # the object behind the name
        # Only process functions and classes
        if not (inspect.isfunction(obj) or inspect.isclass(obj)):
            continue
        # Only include objects declared in geolattice.rsense (skip re-exported names from other libraries)
        if not getattr(obj, "__module__", "").startswith("geolattice.rsense"):
            continue
        # Extract the first line of the object's docstring as its description
        doc = (inspect.getdoc(obj) or "").split("\n")[0]
        rows.append({  # one row: submodule, name, kind and description
            "submodule": sub,
            "name": name,
            "kind": "class" if inspect.isclass(obj) else "function",
            "description": doc
        })

# Create a DataFrame to organize the API entries
api = pd.DataFrame(rows)

# Print the total number of discovered public API entries
print(f"{len(api)} public functions and classes in geolattice.rsense")

# Group the DataFrame by submodule, aggregating counts of functions and classes, and display as a transposed table
print(
    api.groupby("submodule", sort=False)
       .agg(
           functions=("kind", lambda k: int((k == "function").sum())),
           classes=("kind", lambda k: int((k == "class").sum()))
       ).T
)
                             
541 public functions and classes in geolattice.rsense
submodule  backend  core  access  optical  sar  insar  uav  lidar  timeseries  \
functions       22    22      14       34  140     45   74     95          12   
classes          1     3       0        0    0      0    2      1           0   

submodule  classify  dl  fusion  xai  viz  scale  apps  
functions        12  27       6    7    7      5     3  
classes           1   3       0    5    0      0     0  
Code
# Set pandas to display up to 110 characters per column, so descriptions are not truncated.
pd.set_option("display.max_colwidth", 110)

# Loop through each submodule in the API DataFrame, preserving the defined order.
for sub, grp in api.groupby("submodule", sort=False):
    # Print a header for the submodule, showing the full import path and number of entries.
    print(f"\n=== geolattice.rsense.{sub}  ({len(grp)}) " + "=" * 40)
    # For each API entry (function or class) in the submodule, print its name and the first 105 characters of its description.
    for _, r in grp.iterrows():
        print(f"  {r['name']:<28s} {r['description'][:105]}")  # name and the start of its description
 

=== geolattice.rsense.backend  (23) ========================================
  Backend                      An active compute backend.
  array_module                 Return the array module that owns ``arr`` (works for NumPy, CuPy and Dask chunks).
  as_compute_dtype             Cast integer or mismatched float data to the compute dtype (no copy if already right).
  autocast                     PyTorch mixed-precision context on the active backend.
  available_backends           Return the backends usable on this machine, e.g. ``['cpu', 'cuda']``.
  clear_cache                  Release cached GPU memory held by CuPy's pool and PyTorch's allocator.
  compute_dtype                dtype used for array math under the current policy.
  device                       Temporarily switch backend::
  fft                          
  free_gpu_memory_bytes        Free memory on the active CUDA device, or ``None`` on CPU.
  get_backend                  Return the currently active backend.
  get_precision                
  get_xp                       Return the array module (``numpy`` or ``cupy``) for the backend.
  info                         Report hardware and library availability, useful for bug reports.
  is_gpu_array                 
  memory_report                Host and active-GPU memory usage in GB.
  ndimage                      ``scipy.ndimage`` on CPU, ``cupyx.scipy.ndimage`` on CUDA (chosen from ``arr`` if given).
  recommend_chunks             Suggest Dask chunks: full extent on leading dims, square spatial chunks sized to
  scatter_reduce               In-place unbuffered reduction ``target[index] = op(target[index], values)``.
  set_backend                  Set the global compute backend and return it.
  set_precision                Set the default floating dtype for array computations (``float32`` or ``float64``).
  to_cpu                       Move an array, DataArray or Dataset back to host (NumPy) memory.
  to_device                    Move an array, DataArray or Dataset to the active (or given) backend.

=== geolattice.rsense.core  (25) ========================================
  PointCloud                   Points as aligned 1-D arrays: ``x``, ``y``, ``z`` plus optional attributes.
  RasterCube                   A georeferenced image time series with one variable per band.
  Window                       A tile: the ``core`` region it owns and the ``padded`` region it reads.
  apply_tiled                  Apply ``func`` to the last two axes of ``data`` tile by tile on the active backend.
  auto_tile_size               Pick a square tile edge that fits in a fraction of free GPU memory (``default`` on CPU).
  clip                         Clip to geometries (a GeoDataFrame, GeoSeries or list of shapely/GeoJSON geometries).
  ensure_crs                   Return ``obj`` with a CRS, writing ``crs`` if missing; raise if neither is available.
  estimate_utm_crs             UTM EPSG for the centre of a raster or GeoDataFrame.
  iter_windows                 Yield non-overlapping core windows, each with a padded read window.
  list_subdatasets             GDAL subdataset paths of an HDF/NetCDF file (e.g. MODIS HDF-EOS layers).
  map_to_pix                   Map (x, y) → fractional pixel (col, row).
  mosaic                       Merge rasters onto one grid (reprojecting to the first raster's CRS unless ``crs``).
  pix_to_map                   Affine pixel (col, row) → map (x, y), independent of the ``affine`` package version.
  read                         Read a raster (GeoTIFF/COG/JP2/HDF subdataset/NetCDF) as a georeferenced DataArray.
  read_hdf                     Read one layer of an HDF4/HDF5 file through GDAL.
  read_netcdf                  Open NetCDF with spatial dims and CRS set for rioxarray (CF ``grid_mapping`` honored).
  read_safe                    Index a Sentinel-1/2 ``.SAFE`` directory.
  read_zarr                    
  reproject                    Reproject to ``dst_crs`` (EPSG code, WKT or pyproj CRS).
  stack_times                  Concatenate same-grid DataArrays along a new ``time`` dimension.
  transform_bounds             Reproject a bounding box (minx, miny, maxx, maxy), densifying edges.
  utm_epsg                     EPSG code of the WGS84 UTM zone containing a lon/lat point (Norway/Svalbard exceptions).
  write                        Write a DataArray/Dataset to GeoTIFF, as a Cloud-Optimized GeoTIFF by default.
  write_zarr                   Write to Zarr, keeping CRS (``spatial_ref``) so it round-trips with :func:`read_zarr`.
  zonal_stats                  Compute statistics of a single-band raster within each polygon.

=== geolattice.rsense.access  (14) ========================================
  aoi_to_geojson               Normalize an AOI to a GeoJSON geometry in EPSG:4326.
  asf_download                 Download search results using Earthdata credentials (arguments, or ``~/.netrc`` with
  asf_search                   Search Sentinel-1 products. ``product``: ``SLC``, ``GRD_HD``, ``BURST``, ``OCN``.
  baseline_stack               Temporal/perpendicular baseline stack for InSAR pair selection.
  cdse_download                Download a full product (zipped SAFE) by STAC item, product name or CDSE UUID.
  cdse_search                  Search CDSE STAC. ``collection`` may be a CDSE id or a short alias from ``COLLECTIONS``.
  cdse_token                   Obtain an access token (valid ~10 minutes).
  earthdata_download           Download granules found by :func:`earthdata_search`; returns local file paths.
  earthdata_search             Search NASA CMR for granules, e.g. ``earthdata_search("MOD13Q1", aoi=..., dates=...)``.
  gee_image_to_xarray          Single ``ee.Image`` → xarray Dataset (wrapped as a one-image collection).
  gee_init                     Initialize Earth Engine (optionally running the browser authentication flow).
  gee_to_xarray                Open an ``ee.ImageCollection`` (object or asset id) lazily as an xarray Dataset via xee.
  stac_load                    Load STAC items into a lazy, Dask-backed ``xarray.Dataset`` (one variable per band).
  stac_search                  Search a STAC catalog and return a ``pystac.ItemCollection``.

=== geolattice.rsense.optical  (34) ========================================
  as_dataset                   Convert a DataArray with a ``band`` dim to a Dataset with one variable per band.
  brightness_temperature       At-sensor brightness temperature (K): ``BT = K2 / ln(K1 / L + 1)``.
  cloud_mask                   Return the validity mask for ``obj`` using its sensor's QA band.
  composite                    Composite a time series of (already cloud-masked) images.
  coregister                   Estimate (and optionally apply) the translation aligning ``target`` to ``reference``.
  decode_bits                  Extract an integer field of ``length`` bits starting at bit ``start``.
  dos1                         Dark Object Subtraction (DOS1, Chavez 1996) on TOA reflectance.
  emissivity_ndvi              NDVI threshold method (Sobrino et al. 2004) for land surface emissivity.
  endmembers_from_samples      Mean spectrum per class at sample points (GeoDataFrame of points).
  fractional_vegetation        Proportion of vegetation ``Pv = ((NDVI - NDVIs) / (NDVIv - NDVIs))^2``, clipped 0-1.
  get_band                     Fetch canonical ``band`` from a Dataset (by variable) or DataArray (by ``band`` coord).
  guess_sensor                 Guess the sensor from attributes or band names; ``None`` if ambiguous.
  hls_fmask_mask               Mask from the HLS v2.0 ``Fmask`` layer (bits 0-5 flags, bits 6-7 aerosol level 0-3).
  index                        Compute one or more spectral indices.
  landsat_lst                  End-to-end LST from a Landsat Level-1 thermal band and NDVI (MTL values for M, A, K1, K2).
  landsat_qa_mask              Mask from Landsat Collection 2 ``QA_PIXEL``. Flags set to ``True`` are excluded.
  list_indices                 Return a DataFrame of registered indices, optionally filtered by domain.
  load_hls                     Load Harmonized Landsat Sentinel-2 (HLS v2.0) from NASA LP DAAC.
  load_landsat                 Search, load, scale and cloud-mask Landsat Collection 2 Level-2.
  load_modis                   Search, load, scale and cloud-mask MODIS 8-day surface reflectance (MOD09A1/MYD09A1).
  load_sentinel2               Search, load, scale to reflectance and cloud-mask Sentinel-2 L2A.
  lst_single_channel           Single-channel emissivity correction (Artis & Carnahan 1982):
  mask_clouds                  Set cloudy/invalid pixels to NaN in every band.
  modis_state_mask             Mask from MOD09 ``state_1km`` / ``sur_refl_state_500m``.
  modis_vi_mask                Mask from MOD13 ``VI Quality`` bits 0-1 (0 good, 1 check QA, 2 cloudy, 3 not produced).
  pansharpen                   Fuse coarse multispectral bands with a fine panchromatic band.
  parse_mtl                    Parse a Landsat ``*_MTL.txt`` metadata file into a flat dict of numbers/strings.
  radiance                     Level-1 DN to top-of-atmosphere spectral radiance: ``L = M * DN + A``.
  register_index               Register a spectral index.
  s2_scl_mask                  Mask from the Sentinel-2 L2A Scene Classification Layer.
  scale                        Scale surface-reflectance products to reflectance (0-1) and thermal bands to Kelvin.
  toa_reflectance              Landsat Level-1 DN to TOA reflectance with sun-angle correction:
  topographic_correction       Remove terrain illumination effects from reflectance.
  unmix                        Linear spectral unmixing.

=== geolattice.rsense.sar  (140) ========================================
  ais_at_time                  One position per vessel at the SAR time ``t0``: linear interpolation between the last
  apply_offset                 Shift an image or ``(..., y, x)`` stack by whole pixels on its own grid (NaN where uncovered).
  apply_orbit_file             ``Apply-Orbit-File``: return a copy of ``ann`` (:func:`read_slc_annotation`) whose orbit
  azimuth_displacement_m       Expected along-track image displacement (m) of moving vessels: ``R * v_r / V``, with
  azimuth_sublooks             Azimuth sub-looks of one IW SLC burst. The burst is first deramped with
  back_geocode                 DEM-assisted co-registration (SNAP ``Back-Geocoding``) of a secondary burst to a
  boxcar                       Moving-average (multilook-style) filter.
  burst_coordinates            Fractional (line, sample) in a burst for zero-Doppler times and slant ranges from :func:`geo2rdr`.
  burst_window                 Range-sample window ``(start, stop)`` of a burst covering lon/lat ``bounds`` (TOPS-Split
  calibrate                    ``sigma0 = (DN^2 - noise) / A^2``, clipped at a small positive floor.
  calibrate_rcm                RCM Level-1 GRD radiometric calibration: ``(DN^2 + offset) / gain``.
  cfar                         Constant False Alarm Rate detector on linear intensity (bright targets, e.g. ships).
  cfar_tiled                   :func:`cfar` over a large image in overlapping tiles (overlap = half the outer window),
  change_map                   Two-date increase/decrease map from the log-ratio (Otsu on |ratio| if no threshold).
  coherence_at_points          Maximum sub-look coherence near each lon/lat point (e.g. GRD CFAR candidates).
  coherency_t3                 Locally averaged 3x3 Pauli-basis coherency matrix T3 from quad-pol SLC channels.
  common_grid                  A north-up target grid ``(transform, width, height)`` in ``crs`` covering a lon/lat box,
  compact_pol_mchi             m-chi decomposition of RCM compact-pol data into surface, volume and double-bounce power.
  coregister_stack             Co-register a stack of SLC acquisitions to one reference date (SNAP's back-geocoding of a
  covariance_c2                Locally averaged 2×2 covariance matrix from complex SLC channels.
  create_stack                 Co-register GRD scenes into one ``(time, y, x)`` stack on a common map grid.
  cross_pol_ratio              Cross-pol ratio ``CR = VH / VV`` (linear). Sensitive to crop structure and growth stage.
  crop_orbit                   State vectors of an orbit (``read_orbit_file`` dict or ``.EOF`` path) between ``start``
  deburst                      ``TOPS-Deburst``: join consecutive bursts (arrays on the same column window, lines from
  detect_ships_grd             CFAR ship detection on a Sentinel-1 IW GRDH AOI, in native radar geometry (10 m).
  detection_scores             Precision, recall and F1 from a :func:`match_points` result.
  detections_to_points         Group a detection mask into objects → GeoDataFrame of centroids with size and peak.
  download_orbit               Download the Sentinel-1 orbit file covering ``time`` from the open AWS ``s1-orbits``
  dpsvi                        Dual-Polarization SAR Vegetation Index ``DPSVI = (VV+VH) / VV`` (linear inputs).
  dual_pol_features            Intensity-only dual-pol features from GRD/RTC (linear power).
  dual_pol_indices             All single-date VV/VH indices and derived metrics in one call.
  dual_pol_model_decomposition Eigen-decomposition model-based power decomposition for dual-pol data.
  enl_estimate                 Estimate ENL over a homogeneous area: ``mean^2 / var`` of linear intensity.
  esd_azimuth_shift            Enhanced Spectral Diversity: the residual azimuth misregistration of the resampled
  estimate_doppler_centroid    Measured azimuth Doppler centroid (Hz) of an SLC in blocks of ``block`` lines, from the
  estimate_enl                 Equivalent number of looks ``mean^2 / var`` of linear intensity, from the most
  estimate_offset              Integer pixel offset ``(dy, dx)`` that best aligns ``moving`` with ``reference``.
  extract_targets              Connected components of a CFAR mask → one row per target.
  find_rcm_files               Locate the files of one polarisation inside an unzipped RCM Level-1 product folder.
  fit_incidence_slope          Least-squares slope of backscatter (dB) against incidence angle (degrees) over the
  flag_azimuth_ambiguities     True for targets that look like azimuth ghosts of a brighter target.
  flood_map                    Open-water flood extent from Sentinel-1 (VV or VH).
  from_db                      Decibels → linear power.
  geocode_l1                   Quickly interpolate a Level-1 layer to a regular map grid from geolocation arrays.
  gamma0_to_sigma0             RCM-ARD's own terrain-corrected ``sigma0 = gamma0 * ratio``.
  gamma_map                    Gamma-MAP filter (Lopes et al. 1990): homogeneous areas → mean, strong scatterers kept,
  gcov_indices                 Calculate GCOV ratios and RVI from linear powers.
  geo2rdr                      Range-Doppler geocoding of ground points: the zero-Doppler azimuth time and slant range
  geocode_points               Map coordinates of radar-geometry points (e.g. persistent scatterers), from the
  gslc_interferogram           Form a GSLC pair interferogram and local coherence on a shared map grid.
  h_alpha_classify             Unsupervised H-α plane classification into Cloude-Pottier zones (codes 1-9).
  h_alpha_dual                 Dual-pol H/A/α decomposition (Cloude 2007) from C2 elements.
  h_alpha_quad                 Quad-pol Cloude-Pottier H/A/alpha decomposition (Cloude & Pottier 1997) from T3 elements
  hand                         Height Above Nearest Drainage (HAND; Nobre et al. 2011), in the units of ``dem``.
  haversine_m                  Pairwise great-circle distances (m), shape ``(len(lat1), len(lat2))``.
  incidence_angle_grid         Full-resolution ellipsoid incidence angle (degrees), bilinearly interpolated from the
  interpolate_lut              Bilinear interpolation of a sparse (line, pixel) LUT onto an image grid.
  interpolate_orbit            Interpolate ``read_orbit_file``'s position/velocity to arbitrary ``times``.
  interpolate_rcm_lut          Interpolate a sparse RCM range-only gain LUT (:func:`read_rcm_lut`) onto ``width``
  interpolate_rcm_noise        Stitch RCM per-beam noise-level segments (:func:`read_rcm_noise_levels`) onto ``width``
  inspect_hdf5                 List datasets below an HDF5 group with shape, dtype, and attributes.
  land_mask_for_window         Land mask (True = land or coastal buffer) for a GRD window in radar geometry.
  layover_shadow_mask          Local layover/shadow classes on a projected DEM grid: 0 = fine, 1 = layover (terrain
  lee                          Lee (1980) adaptive filter: ``x = m + b (z - m)``, ``b = var_x / var_z``.
  llh_to_ecef                  WGS84 latitude/longitude (degrees) and ellipsoidal height (m) to ECEF XYZ (m), shape (..., 3).
  load_rtc                     Load Planetary Computer ``sentinel-1-rtc`` (gamma0, terrain-corrected, linear power).
  local_incidence_angle        Local incidence angle (degrees) from a DEM already resampled onto the SAR image grid.
  log_ratio                    Log-ratio change image ``10 log10(after / before)`` (dB) or natural log if ``db=False``.
  los_unit_vector              Unit vector from ground points to the satellite (at each point's zero-Doppler time), in
  m_chi_decomposition          m-χ model-based power decomposition (Raney 2007) of a dual-pol C2 matrix.
  m_delta_decomposition        m-δ model-based power decomposition (Raney 2007) of a dual-pol C2 matrix.
  mask_to_polygons             Vectorize a boolean mask into polygons with pixel count and area.
  match_points                 One-to-one matching (Hungarian) of predictions to reference points within
  median                       Median filter (NaN treated as missing by filling with the local mean first).
  multilook                    Block-average by (azimuth, range) looks.
  multitemporal                Quegan & Yu (2001) multi-temporal filter.
  multitemporal_speckle_filter Quegan & Yu (2001) multi-temporal speckle filter for a co-registered stack.
  normalize_incidence          Bring backscatter (dB) to a reference incidence angle with a linear slope:
  oil_spill_detection          Dark-spot detection for oil-slick candidates (VV).
  omnibus_test                 Likelihood-ratio test for change across k single-polarization intensity images
  pairwise_change              Sequential two-date LR tests between consecutive images: change map per interval,
  polarimetric_rvi             Polarimetric RVI ``PRVI = (1 - VV/(VH+VV)) * VH``, algebraically ``VH^2/(VH+VV)``
  process_offsets              Quality-filter NISAR ROFF/GOFF offsets and derive ground-range and EN displacement.
  process_rifg                 Mask a RIFG by coherence and optionally multilook the complex interferogram.
  process_unwrapped_phase      Quality-mask, reference, optionally correct ionosphere, and convert phase to LOS displacement.
  process_grd                  Process a Sentinel-1 GRD product to calibrated backscatter (linear units).
  radar_forest_degradation_index Radar Forest Degradation Index ``RFDI = (VV-VH) / (VV+VH)`` (linear inputs).
  radar_vegetation_index       Dual-pol Radar Vegetation Index ``RVI = 4*VH / (VV+VH)`` (linear inputs).
  range_sublooks               Range sub-looks of an IW SLC burst (or deburst image): the range spectrum is not
  rcm_incidence_angle          Per-column ellipsoid incidence angle (degrees) for ``width`` columns starting at scene
  read_ais_dma                 Read a Danish Maritime Authority daily AIS file (CSV or zipped CSV) and keep class A/B
  read_calibration_lut         Parse a ``calibration-*.xml`` file (local path or URL) → (lines, pixels, values).
  read_geolocation_grid        Parse an annotation XML's sparse ``geolocationGridPointList`` (an evenly spaced
  read_grd_subset              Calibrated backscatter for a lon/lat box cut out of one GRD measurement image.
  read_identification          Read NISAR identification metadata and attributes without loading raster arrays.
  read_l2                      Read a two-dimensional Level-2 raster layer and attach its map CRS.
  read_nisar                   Read a NISAR layer into an ``xarray.DataArray`` with product grid coordinates.
  read_noise_lut               Parse range noise vectors from ``noise-*.xml`` (local path or URL; IPF >= 2.9 and older layouts).
  read_orbit_file              Parse a Sentinel-1 precise (POEORB) or restituted (RESORB) orbit file (``.EOF``) into
  read_platform_heading        Platform flight-direction heading (degrees clockwise from north, 0-360) and the pass
  read_prf                     Pulse repetition frequencies (Hz) listed in a GRD or SLC annotation XML
  read_processing_params       Range and azimuth processing bandwidth (Hz) and Hamming window coefficients from an
  read_rcm_annotation          Parse what InSAR coregistration needs from an RCM Level-1 **Stripmap** SLC
  read_rcm_grd_subset          Calibrated, noise-corrected backscatter for a lon/lat box cut out of one polarisation of
  read_rcm_incidence           Parse RCM's ``incidenceAngles.xml``: a range-only (per-column) ellipsoid incidence angle
  read_rcm_lut                 Parse an RCM Level-1 ``lutSigma``/``lutBeta``/``lutGamma`` calibration XML
  read_rcm_metadata            Scene facts from an RCM ``product.xml`` that a workflow should record before processing:
  read_rcm_noise_levels        Parse an RCM Level-1 ``noiseLevels_<pol>.xml`` file's per-beam NESZ segments.
  read_rcm_tie_points          Ground control points from ``product.xml``'s geolocation grid (``imageTiePoint``: image
  read_radar                   Read a two-dimensional Level-1 radar-geometry layer.
  read_rslc_backscatter        Make multilooked RSLC beta0 and optional sigma0 backscatter quick looks.
  read_slc_annotation          Parse what TOPS interferometry needs from a Sentinel-1 IW SLC annotation XML (a SAFE
  read_slc_burst               Read one burst of an IW SLC measurement GeoTIFF as ``complex64`` (TOPS-Split).
  refined_lee                  Refined Lee filter (Lee 1981) with 7×7 edge-aligned windows.
  remove_border_noise          Mask likely GRD border-noise pixels near the left/right scene edges.
  resample_slc                 Resample a secondary burst ``slc`` (lines from 0, columns from ``col0``) at fractional
  rhrv_to_stokes               Stokes parameters from an RH/RV compact-pol covariance matrix (Raney 2007), the inverse
  rice_map                     Paddy rice mapping from a VH time series using the transplanting flood signature.
  rr_rl_to_stokes              RCM-ARD's circular-basis Stokes parameters from RR, RL and RRRL*.
  rrrl_to_rhrv                 Losslessly convert RCM-ARD's circular (RR, RL, RRRL*) product to the linear RH/RV
  ring_stats                   Mean, standard deviation and pixel count of ``img`` in the ring between a square
  rvi4s1                       Sentinel-1 RVI4S1 ``= sqrt(VV/(VV+VH)) * 4*VH/(VV+VH)`` (linear inputs).
  sentinel_normalized_index    Sentinel Normalized Index ``SNI = (VH-VV) / (VH+VV)`` (linear inputs); ``SNI = -RFDI``
  ship_cfar                    Constant false alarm rate detector on linear intensity (e.g. sigma0 VH).
  ship_detection               CFAR ship detection on linear intensity (VH or HV best). ``land_mask`` True = land.
  sigma0_to_gamma0             Ellipsoid normalisation ``gamma0 = sigma0 / cos(theta_inc)`` (no DEM).
  simulate_compact_pol         Simulate a right-circular-transmit, linear-receive (CTLR) compact-pol acquisition from
  split_rrrl                   Real and imaginary bands of an RCM-ARD ``rrrl`` asset (the RR/RL* complex correlation).
  split_spectrum               Two sub-look images from the lower and upper halves of an SLC's (baseband) spectrum
  stokes_parameters            Stokes-vector parameters from a dual-pol C2 covariance matrix.
  sublook_coherence            Sub-look coherence ``|<s1 s2*>| / sqrt(<|s1|^2><|s2|^2>)`` and the internal Hermitian
  temporal_change              Simple temporal difference ``x_t - x_t1`` of the same backscatter channel at two dates.
  temporal_ratio               Simple temporal ratio ``x_t / x_t1`` of the same backscatter channel at two dates.
  terrain_correct              ``Range-Doppler Terrain Correction``: resample radar-geometry layers onto a DEM's map grid.
  terrain_flatten              Beta0 -> terrain-flattened gamma0: ``gamma0 = beta0 / cos(local incidence angle)``,
  threshold                    Global threshold of a change or backscatter image.
  to_db                        Linear power → decibels.
  tops_deramp_phase            TOPS azimuth deramping phase ``phi(eta, tau)`` (radians) at burst ``lines``/``samples``.
  tops_doppler_centroid        Doppler centroid (Hz) of each burst pixel: ``fdc + kt (eta - eta_ref)`` -- the frequency
  un_spider_flood_mapping      Complete UN-SPIDER Sentinel-1 flood mapping workflow.

=== geolattice.rsense.insar  (45) ========================================
  amplitude_dispersion         Amplitude dispersion index ``D_A = sigma_A / mu_A`` and mean amplitude of a stack
  atmospheric_filter           Atmospheric phase screen of unwrapped point phase ``(n_dates, P)``: high-pass in time,
  coherence_threshold          Temporal coherence that pixels with *random* phase reach with :func:`ps_periodogram`, at
  combine_heights              Inverse-variance weighted mean of several height maps (e.g. one per interferometric pair)
  correct_unwrapping_errors    Correct 2 pi unwrapping errors with phase closure (MintPy's ``phase_closure`` method).
  decompose_asc_desc           Combine ascending and descending LOS into vertical and east-west components.
  dem_error_correction         DEM-error correction of an SBAS time series (Fattahi & Amelung 2013).
  dem_error_stats              Accuracy of a DEM against reference heights on the same grid (or at the same points):
  detrend_heights              Remove long-wavelength errors from an InSAR height map by fitting its difference from a
  differential_interferogram   ``reference * conj(secondary) * exp(-1j * topographic_phase(delta_range))`` for two
  enu_to_los                   Project east/north/up displacements (e.g. GNSS) onto the line of sight; ``los_enu`` is the
  era5_delay                   Slant tropospheric delay (as phase) from ERA5 using PyAPS (``pip install pyaps3``).
  fill_dem_voids               Fill NaN voids of a DEM.
  flat_earth_phase             Phase (rad) of a flat, ellipsoidal Earth from the secondary-minus-reference slant range
  gacos_correction             Subtract the GACOS tropospheric delay difference from unwrapped phase.
  geoid_to_ellipsoid           Convert heights above the geoid (orthometric, as in SRTM/NASADEM: ``EGM96``; Copernicus
  goldstein_filter             Goldstein & Werner (1998) adaptive phase filter.
  height_of_ambiguity          Height change (m) that produces one full fringe (2 pi): ``lambda R sin(theta) / (2 B_perp)``.
  height_std                   Height standard deviation (m) expected from phase noise: the Cramer-Rao bound
  interferogram                Form a complex interferogram with coherence.
  interferogram_stack          Form, deburst, multilook, filter and unwrap every interferogram of an SBAS network.
  loop_closure                 Phase closure ``u_ij + u_jk - u_ik`` of every triplet of interferograms in the network,
  los_to_vertical              Project LOS displacement to vertical assuming purely vertical motion: ``d_v = d_los / cos(theta)``.
  multilook_complex            Complex block averaging (azimuth, range looks) of an interferogram.
  network_components           Connected subsets of an interferogram network (dates linked by at least one chain of pairs),
  perpendicular_baseline       Perpendicular and parallel baseline (m) of a pair at ground points.
  phase_to_height              Convert flat-Earth-removed unwrapped phase (rad) to elevation (m) -- SNAP's
  phase_to_los                 Unwrapped phase (rad) → line-of-sight displacement (m).
  point_velocity               Least-squares linear rate (units per year) and residual RMSE of point time series
  ps_candidates                Boolean mask of PS candidates: ``D_A < threshold`` (Ferretti: 0.25; StaMPS uses a looser
  ps_periodogram               Per-point grid search (periodogram) of the DEM error -- and optionally a linear phase rate --
  read_gacos                   Read a GACOS ``.ztd`` binary grid (with its ``.rsc`` header) as a DataArray in metres.
  reference_to_point           Subtract the median of a ``window`` x ``window`` box around ``point`` (row, col) from
  remove_ramp                  Fit and subtract a planar (order 1) or quadratic (order 2) ramp from *unwrapped* phase.
  sbas_inversion               Small-baseline network inversion (Berardino et al. 2002) to a displacement time series.
  sbas_network                 Choose small-baseline interferometric pairs ``(earlier, later)`` among ``dates``.
  sbas_svd                     SBAS inversion of unwrapped interferograms (``(n_pairs, ...)``, phase or displacement) by
  select_reference_point       Choose a reference pixel ``(row, col)``: the centre of the ``window`` x ``window``
  sparse_lowpass               Gaussian low-pass of values known only at scattered points, evaluated at the same points.
  topographic_phase            Phase (rad) a DEM predicts for a pair: ``4 pi / lambda * (R_sec - R_ref)`` at the DEM
  unwrap                       Unwrap interferometric phase.
  unwrap_points                Unwrap the wrapped phase of sparse points ``(n_ifg, P)`` (after DEM-error removal).
  unwrap_snaphu_topo           Unwrap a topographic interferogram with SNAPHU in ``TOPO`` statistical-cost mode.
  velocity                     Per-pixel linear velocity (units per year) from a displacement time series by least
  wrap                         Wrap phase to (-pi, pi].

=== geolattice.rsense.uav  (76) ========================================
  Camera                       Nadir camera geometry for flight planning (sensor size in mm, image size in pixels).
  FlattenResult                Output of :func:`ransac_flatten`.
  as_image                     Wrap a ``(rows, cols)`` or ``(rows, cols, channels)`` array as a ``(band, y, x)`` DataArray.
  bare_soil_line               Fit the minimum bare-soil line to red and near-infrared digital numbers.
  blur_score                   Variance of the Laplacian (higher = sharper). Motion-blurred frames score low.
  boxes_to_gdf                 Box polygons in the image's coordinates (CRS kept for GeoTIFFs).
  build_catalog                Index every image under ``root`` into a tidy table, one row per file.
  build_ricenet                Build the RiceNet network: density + attention maps (``gap=False``) or the plant-size
  camera_from_equivalent       Build a :class:`Camera` from a 35 mm-equivalent focal length (diagonal-based), for
  canopy_cover                 Binary vegetation mask and fractional cover from a vegetation index (e.g. ExG, NDVI).
  chm_from_surfaces            Canopy height = DSM - DTM.
  chromatic                    Chromatic coordinates ``r = R/(R+G+B)`` (likewise ``g``, ``b``): removes brightness
  classify_senescence          Label plant pixels green (1) or senescent (2); background stays 0.
  coregister                   Align a 2-D ``moving`` band (e.g. NIR) to a 2-D ``reference`` band (e.g. green).
  cosine_weight                2-D raised-cosine (Hann) weight peaking at 1 in the tile centre.
  count_plants                 Detect individual plants (or trees) as local maxima of a CHM or vegetation index.
  count_summary                Count, mean confidence and (with a GSD/CRS image or ``area_m2``) objects per m².
  cover_layers                 Perpendicular vegetation index, ground cover and WDVI from red and NIR.
  cwsi                         Crop Water Stress Index ``(Tc - Twet) / (Tdry - Twet)``, clipped 0-1.
  density_count                Count plants on a large RGB image with a density model, tile by tile.
  detect_stages                Dates at which a fitted logistic curve reaches given fractions of its amplitude.
  detection_scores             Precision, recall, F1 and count agreement of predicted vs reference boxes (greedy
  doming_profile               Median elevation along one axis: a quick look at doming before and after flattening.
  edge_agreement               Correlation of the Sobel edge maps of two bands, away from NaN borders.
  empirical_line               Empirical line method with 2+ targets of known reflectance (linear fit per band).
  estimate_homography          3x3 homography mapping ``moving`` pixel coordinates onto ``reference``.
  exg_plant_mask               Model-free plant mask: Otsu threshold on ExG, then :func:`clean_mask`.
  exposure_stats               Mean brightness and the fractions of near-black and near-saturated pixels (0-1 scale).
  extract_frames               Save every ``step``-th frame of a flight video (the LUMS workflow keeps every 6th frame of
  fetch_weights                Path to the cached weights for ``name``, downloading them first if needed.
  fit_logistic                 Fit a 4-parameter logistic curve to a trait over time.
  flight_plan                  Ground sampling distance, image footprint and line/trigger spacing for a nadir survey.
  frame_quality                Blur and exposure statistics for many frames (read at ``max_dim`` for speed).
  frame_traits                 Standard RGB(+NIR) traits of one frame, ready for :func:`trait_table`.
  growth_rates                 Change in ``trait`` per day between consecutive flight dates (per ``by`` group).
  health_map                   Green / senescent map of a large RGB image, tile by tile (LUMS: 2048 px, 256 px overlap).
  health_summary               Plant cover and green/senescent fractions, for the whole image or per zone label.
  hsv_filter                   Send "senescent" pixels that are grey (S < ``s_min``) or dark (V < ``v_min``) to
  index_summary                Flat dictionary of index statistics (optionally inside a vegetation ``mask``), handy as
  list_weights                 Table of registered models and whether each is already cached.
  load_detector                Return ``predict(tile_rgb_uint8, conf) -> (n, 6) [x1, y1, x2, y2, conf, cls]``.
  load_outputs                 Load the orthomosaic, DSM and DTM of a photogrammetry project (whichever exist).
  load_pair                    Load an RGB frame and its NIR frame into one ``(band=[red, green, blue, nir], y, x)`` array.
  load_ricenet                 Load a RiceNet checkpoint (``kind="count"`` density model or ``"size"`` regressor).
  load_segveg                  Load a SegVeg pickle (``model_scikit``, ``XGBoost``, ``Necrosis.pkl``).
  map_to_pix                   Map (x, y) → fractional pixel (col, row).
  merge_boxes                  Greedy non-maximum suppression across tiles on columns ``x1, y1, x2, y2`` and ``score``.
  merge_points                 Merge points closer than ``radius`` (e.g. the same plant found in two tiles).
  pair_catalog                 Turn a :func:`build_catalog` table into one row per frame with a path column per band.
  panel_calibration            Single-panel calibration: ``reflectance = DN * (rho_panel / DN_panel)`` per band.
  panel_dn_from_image          Mean DN per band inside a pixel box (row0, row1, col0, col1) covering the panel.
  parse_date                   Find a date in a folder name: ``2025-08-22``, ``30072018`` (DDMMYYYY) or ``20250822``.
  peaks_from_density           Local maxima of a density map above ``threshold``; returns ``(n, 2)`` ``(row, col)``.
  pix_to_map                   Affine pixel (col, row) → map (x, y), independent of the ``affine`` package version.
  plants_per_area              Plant density per polygon (count / area in ``area_unit`` m², e.g. 1e4 for per-hectare).
  predict_tiled                Run ``fn`` on overlapping tiles of an ``(rows, cols, ...)`` image and stitch the output.
  ransac_flatten               Remove a shared doming/tilt surface from one or more DEMs of the same field.
  raw_to_celsius               Radiometric thermal camera raw counts to °C (FLIR/DJI R-JPEG style ``raw*gain + offset``).
  read_frame                   Read a UAV frame or exported orthomosaic as a ``(band, y, x)`` DataArray.
  refine_ecc                   Enhanced Correlation Coefficient alignment.
  run_docker                   Run ODM in Docker on ``project_dir/images``; outputs land in ``project_dir``.
  run_nodeodm                  Process images on a NodeODM server (``docker run -p 3000:3000 opendronemap/nodeodm``).
  sam_plant_mask               Binary plant mask (``uint8`` 0/1) of an RGB tile with Segment Anything and ExG prompts.
  sam_segment                  Segment a GeoTIFF with SAM; writes a mask raster and optionally polygons.
  segveg_features              The 14 SegVeg colour features per pixel for an ``(n, 3)`` or ``(rows, cols, 3)`` uint8 RGB.
  size_classes                 Label plants ``small`` / ``medium`` / ``large`` by size quartiles (LUMS colour classes).
  sliding_windows              Yield ``(row0, col0, rows, cols)`` windows of size ``tile`` with ``overlap`` pixels.
  summarize_dates              Mean, SD and count of each trait per flight date (and per ``by`` columns, e.g. crop).
  sunshine_normalize           Normalize for changing illumination using a downwelling light sensor (DLS):
  synthetic_dem                A GCP-free style DSM of a plot trial: crop canopy on a domed, tilted ground.
  tiled_detect                 Detect objects on a large RGB image window by window and merge the results.
  to_rgb_array                 ``(band, y, x)`` DataArray (or array) -> ``(rows, cols, 3)`` RGB array for OpenCV/torch.
  trait_table                  Run ``func(image) -> {trait: value}`` on each catalogue row and join the results.
  trend_surface                Fit ``z = poly(col, row)`` of ``degree`` to a DEM with RANSAC; return surface and fit info.
  vegetation_indices           Compute UAV vegetation indices from a ``(band, y, x)`` image or a Dataset of bands.
  write_dems                   Write corrected DEMs to GeoTIFF (georeferenced inputs keep their CRS).

=== geolattice.rsense.lidar  (96) ========================================
  Tile                         A tile: ``core`` bounds (no overlap between tiles) and ``buffered`` bounds.
  apply_transform              Apply a 4×4 rigid transform. ``origin`` (x, y, z) is subtracted before and added after,
  aspect                       Aspect: compass direction of steepest descent, degrees clockwise from north.
  assign_points_to_crowns      Add ``tree_id`` to points by looking up the crown raster (0 = none).
  building_footprints          Building outlines from class-6 points → GeoDataFrame with ``area_m2``, ``height_m``
  c2c_distance                 Cloud-to-cloud nearest-neighbour distance from each ``compared`` point to ``reference``.
  canopy_change                Canopy loss and growth between two CHMs.
  chm                          Canopy Height Model = DSM − DEM (clipped at ``min_height``).
  classify_buildings           Separate buildings (6) from vegetation using local and object-level geometry.
  classify_ground              Dispatch to :func:`smrf`, :func:`csf` or :func:`~geolattice.rsense.lidar.filters.pmf`.
  classify_vegetation          ASPRS low (3), medium (4) and high (5) vegetation by height above ground.
  clip_polygon                 Keep points inside (or outside, ``invert=True``) a shapely geometry or GeoDataFrame
  colorize                     Colour points from co-registered imagery (e.g. NAIP orthophotos, Sentinel-2).
  cross_section                Points within ``width/2`` of the line ``start → end``, with a ``distance`` field (m
  csf                          Cloth Simulation Filter (Zhang et al. 2016), simplified.
  curvature                    Total (Laplacian) curvature, 1/m: negative = convex (ridges), positive = concave.
  dem                          Digital Elevation (terrain) Model from ground points (class 2), gaps interpolated.
  dem_of_difference            DEM of Difference (after − before) with a level of detection (Brasington et al. 2003).
  density_map                  Points per m² on a ``res`` grid (a QC layer for coverage gaps).
  detect_power_lines           Wire conductors: elevated, strongly linear, near-horizontal points.
  detect_stems                 Stem positions and diameter at breast height from TLS/MLS/dense UAV lidar.
  detect_trees                 Treetops as local maxima of a CHM → GeoDataFrame (x, y, height).
  dsm                          Digital Surface Model: highest (first-return) elevation per cell.
  eigen_features               Covariance (eigenvalue) features of each point's ``k`` nearest neighbours.
  euclidean_clusters           Connected-component clustering: points closer than ``radius`` share a cluster.
  fill_depressions             Priority-flood depression filling (Barnes et al. 2014), with a small ``epsilon`` gradient
  fill_gaps                    Fill NaN cells: ``nearest``, inverse-distance from the 8 nearest cells (``idw``) or
  fit_circle                   Algebraic (Kåsa) least-squares circle fit, optionally refined by Gauss–Newton
  flatten_water                Hydro-flatten water bodies: set each polygon (GeoDataFrame or shapely geometries) to
  flow_accumulation            D8 upslope contributing cells (including the cell itself). Fills depressions first
  flow_direction               D8 flow direction as an index 0-7 (N, NE, E, SE, S, SW, W, NW); -1 for sinks/edges.
  foliage_height_diversity     Shannon diversity of returns across height layers above ``min_height`` (MacArthur 1961).
  footprints_to_raster         Grid footprint values onto a raster template (mean/median/count per cell).
  geomorphons                  Geomorphon landforms (Jasiewicz & Stepinski 2013), classes 1-10 (see GEOMORPHON_CLASSES).
  grid_metrics                 Area-based structure metrics per ``res`` cell from height-normalized points.
  hand                         Height Above Nearest Drainage (Rennó et al. 2008): elevation above the stream cell each
  height_profile               Vertical profile of returns with gap fraction and leaf area density (MacArthur–Horn).
  hillshade                    Analytical hillshade scaled 0-255.
  icp                          Point-to-point Iterative Closest Point (Besl & McKay 1992).
  illumination                 Cosine of the local solar incidence angle, cos(i), used for topographic correction.
  inundation                   Flood extent and depth for a water ``level``.
  iter_tiles                   Yield ``(tile, buffered sub-cloud)`` for every tile holding ``min_points`` points.
  las_info                     Header summary without reading the points: version, point format and dimensions,
  m3c2                         Multiscale Model-to-Model Cloud Comparison (Lague et al. 2013).
  merge_pointclouds            Concatenate point clouds (fields present in all of them are kept).
  merge_rasters                Mosaic tile rasters (first valid value wins) into one DataArray/Dataset.
  normalize_heights            Add ``height`` (z minus terrain, bilinear from ``dtm``) to every point.
  normals                      Upward-oriented unit surface normals (``nx, ny, nz``) from local PCA.
  pdal_pipeline                Run a PDAL pipeline (list of stage dicts or JSON string) and return the first output.
  plot_classification          Plan view coloured by ASPRS class (subsampled to ``max_points``).
  plot_cross_section           Profile view (distance vs elevation). Pass a cloud from :func:`cross_section`, or a
  plot_height_profile          Plot a :func:`height_profile` table (``lad``, ``fraction`` or ``gap_fraction``).
  plot_metrics                 Structure metrics for each field plot (the area-based approach for biomass models).
  pmf                          Progressive Morphological Filter (Zhang et al. 2003).
  point_feature_table          Per-point feature table for supervised classification.
  predict_point_classes        Apply a model from :func:`train_point_classifier` and write ``field``.
  process_files                Apply ``func`` to each LAS/LAZ file (read with :func:`read_las`) in parallel threads.
  process_tiles                Run ``func(sub_cloud)`` on every buffered tile and merge the trimmed results.
  radius_outlier_removal       Remove points with fewer than ``min_neighbors`` other points within ``radius`` (m).
  ransac_plane                 Fit one plane by RANSAC (refined by least squares on the inliers).
  rasterize                    Bin points onto a grid with a statistic, on the active backend (scatter reductions).
  read_atl08                   ICESat-2 ATL08 100 m land segments → canopy height (``h_canopy``), terrain
  read_gedi_l2a                GEDI L2A footprints → GeoDataFrame with relative heights ``rhNN`` (m), ground elevation,
  read_gedi_l2b                GEDI L2B canopy cover and vertical profile metrics per footprint.
  read_gedi_l4a                GEDI L4A aboveground biomass density (Mg/ha) with standard error per footprint.
  read_las                     Read LAS/LAZ (or COPC with ``bounds``/``resolution`` for spatial/level-of-detail queries).
  read_las_chunks              Iterate over a large LAS/LAZ file in ``chunk_size`` point chunks (PointClouds).
  read_pdal                    Read anything PDAL can (EPT URLs such as USGS 3DEP, E57, PLY, COPC...).
  remove_outliers              Dispatch to :func:`statistical_outlier_removal` or :func:`radius_outlier_removal`.
  reproject                    Transform x/y (and z for compound CRSs with a vertical datum, e.g. ``"EPSG:6339+5703"``)
  rigid_transform              4×4 matrix from rotations about x, y, z (degrees, applied x→y→z) and a translation.
  roughness                    Max minus min elevation in the 3×3 neighbourhood.
  sample_raster                Attach raster values (DTM, NDVI, land cover...) to every point as field ``name``.
  segment_crowns               Marker-controlled watershed crown segmentation of a CHM.
  segment_roof_planes          Sequential RANSAC roof-plane segmentation of (building) points.
  segment_trees_points         Point-based individual tree segmentation from treetops (no CHM rasterisation).
  slope                        Slope (Horn 1981) in ``degrees``, ``radians`` or ``percent``.
  smrf                         Simple Morphological Filter (Pingel et al. 2013).
  solar_potential              Relative clear-sky insolation on a DSM: mean of cos(incidence) over sun positions,
  statistical_outlier_removal  Statistical outlier removal (Rusu et al. 2008), as in PCL / PDAL ``filters.outlier``.
  structure_metrics            Gridded vertical-structure metrics: foliage height diversity (``fhd``), effective
  summary                      Quick inspection: point count, bounds, area, density, spacing, and tables of
  sun_positions                Solar azimuth/elevation (degrees) for day-of-year × local solar hour combinations
  swath_overlap                Inter-swath consistency: per cell, the elevation difference between flight lines
  thin                         Reduce point density: one point per ``size`` voxel, the lowest (``grid_min``) or highest
  tile_grid                    Regular tiles of ``size`` m covering ``bounds`` (minx, miny, maxx, maxy).
  tpi                          Topographic Position Index: elevation minus the mean of a ``window``×``window`` neighbourhood.
  train_point_classifier       Fit a point classifier (``rf``, ``xgb``, ``gbm``...) on eigen + attribute features.
  tri                          Terrain Ruggedness Index (Riley et al. 1999): sqrt of summed squared differences to 8 neighbours.
  trim                         Clip a PointCloud or raster (DataArray/Dataset) back to the tile's core bounds.
  twi                          Topographic Wetness Index ln(a / tan β), with a = specific catchment area (m).
  usgs_3dep_ept                Find USGS 3DEP Entwine (EPT) dataset URLs intersecting a lon/lat bbox.
  vertical_accuracy            Compare a DTM with surveyed checkpoints (GeoDataFrame with ``z_col``): RMSEz, mean
  write_las                    Write a PointCloud to LAS/LAZ (``.laz`` compresses with lazrs/laszip).
  write_ply                    Write a PLY file (CloudCompare, MeshLab, Open3D). ``offset="auto"`` subtracts the
  write_tiles                  Split a point cloud into LAS/LAZ tiles ``{prefix}_{x0}_{y0}{ext}`` and return the paths.

=== geolattice.rsense.timeseries  (12) ========================================
  anomaly                      Departure from climatology: ``x - mean`` (absolute), ``(x - mean)/std`` (z-score) or
  bfast_monitor                Detect the first disturbance after ``monitor_start`` (Verbesselt et al. 2012, simplified).
  ccdc                         Detect multiple land-cover breaks per pixel from a multi-band reflectance series.
  climatology                  Mean, std, min and max by calendar month / day-of-year / season over a base ``period``.
  harmonic_fit                 Per-pixel harmonic regression (Fourier series + optional linear trend).
  interpolate                  Fill NaNs by linear interpolation in time (respecting actual acquisition dates).
  phenology                    Seasonal metrics by the amplitude-threshold method (Jönsson & Eklundh 2004, TIMESAT).
  savgol                       Savitzky–Golay filter along time.
  tci                          Temperature Condition Index: ``100 (max - LST) / (max - min)`` (hot = stressed = low).
  vci                          Vegetation Condition Index (Kogan 1995): ``100 (NDVI - min) / (max - min)`` per calendar
  vhi                          Vegetation Health Index ``alpha * VCI + (1 - alpha) * TCI``.
  whittaker                    Whittaker smoother (Eilers 2003): minimizes ``|y - z|^2 + lambda |D^d z|^2``.

=== geolattice.rsense.classify  (13) ========================================
  Classifier                   Pixel/object classifier or regressor with automatic CPU/GPU engine selection.
  accuracy_report              Overall accuracy, Cohen's kappa, per-class user's/producer's accuracy and F1.
  cluster                      Unsupervised k-means classification of a feature Dataset (fit on a random sample).
  confusion_matrix             Confusion matrix with rows = map (predicted) classes, columns = reference classes.
  cva                          Change Vector Analysis: magnitude and direction of spectral change.
  extract_samples              Extract feature values at training samples.
  image_difference             Difference image with changes flagged beyond ``k`` standard deviations of the difference.
  olofsson                     Area-adjusted accuracy and area estimation (Olofsson et al. 2014, stratified random sampling).
  post_classification          From-to change analysis of two classified maps.
  segment                      Segment an image into objects (superpixels). Bands are min-max scaled first.
  segment_features             Per-segment statistics (mean, std, min, max, median) for each band, plus shape
  segment_labels               Majority label per segment from training points/polygons (for training an OBIA model).
  segments_to_raster           Map per-segment values (indexed by segment id) back onto the segment raster.

=== geolattice.rsense.dl  (30) ========================================
  CNN3D                        Compact 3-D CNN on ``(B, 1, bands, p, p)`` patches (joint spectral–spatial kernels).
  HSIPatchDataset              Patches ``(1, bands, p, p)`` (or spectra ``(bands,)`` with ``patch=1, flat=True``)
  HybridSN                     HybridSN (Roy et al. 2020): three 3-D convolutions followed by a 2-D convolution.
  SpectralCNN1D                1-D CNN on single-pixel spectra (input ``(B, bands)``).
  SpectralTransformer          Transformer over groups of neighbouring bands (SpectralFormer-style group-wise
  block_split                  Split labelled pixels into train/test masks by whole spatial blocks of ``block`` pixels,
  predict_hsi_map              Classify every valid pixel of ``cube`` with the patch size, normalisation and class codes
  train_hsi_classifier         Cross-entropy training; keeps the weights with the best validation accuracy.
  PointBlockDataset            Fixed-size point samples from square blocks of one or more PointClouds.
  PointNet2Seg                 PointNet++ single-scale-grouping segmentation network (Qi et al. 2017b).
  PointNetSeg                  Vanilla PointNet segmentation network (Qi et al. 2017a), without T-nets.
  predict_point_segmentation   Label every point of ``pc`` by sweeping blocks (same size/features/statistics as the
  train_point_segmentation     Train a point segmentation model with cross-entropy (labels -100 are ignored).
  RasterTileDataset            Tiles from an image (band, y, x) and optional label raster (y, x) as a torch Dataset.
  UNet                         Built-in U-Net instance (no extra dependencies).
  adapt_first_conv             Return a copy of a ``nn.Conv2d`` accepting ``in_channels``, reusing pretrained RGB weights.
  band_stats                   Per-band mean and std (from a random pixel sample) for normalization. ``image``: (band, y, x).
  build_detector               Create a torchvision detector (``num_classes`` includes background for R-CNNs).
  build_segmentation_model     Create a segmentation network.
  export_onnx                  Export a segmentation model to ONNX (dynamic batch/height/width) for CPU inference.
  from_torchgeo                Instantiate a TorchGeo benchmark dataset by class name, e.g. ``from_torchgeo("EuroSAT")``.
  grid_windows                 Top-left corners of a regular tile grid covering the image (last tiles snapped to the edge).
  labels_from_vectors          Rasterize labelled polygons onto the image grid → (label raster, {class_name: code}).
  lightning_task               Wrap a model in a LightningModule for multi-GPU / multi-node training::
  make_loader                  
  predict_detection            Sliced detection over a large image with global NMS → GeoDataFrame of boxes in map units.
  predict_segmentation         Run a segmentation model over an arbitrarily large image (band, y, x).
  random_flip_rotate           Simple geometric augmentation: random flips and 90° rotations (image and mask together).
  train_detection              Train a torchvision detector. Batches must be ``(images: list[Tensor], targets: list[dict])``
  train_segmentation           Train a segmentation model with cross-entropy (plain PyTorch, single device).

=== geolattice.rsense.fusion  (6) ========================================
  compare                      Agreement metrics between two co-registered rasters: R², RMSE, MAE, bias, n.
  sar_gap_fill                 Fill cloudy (NaN) optical pixels from co-registered SAR features of the same date.
  stack_features               Align datasets to the grid of ``sources[reference]`` and merge their variables.
  starfm                       Predict a fine-resolution image at t2 from a fine/coarse pair at t1 and coarse at t2.
  train_wall_to_wall           Model a sparse lidar/field variable (e.g. GEDI RH98, plot AGB) from wall-to-wall rasters
  upscale                      Aggregate a fine raster (e.g. UAV) onto a coarse grid (e.g. Sentinel-2).

=== geolattice.rsense.xai  (12) ========================================
  BufferedKFold                K-fold (random or block) where training samples within ``buffer`` (map units) of any
  ConformalClassifier          Split-conformal prediction sets (LAC score ``1 - p_true``; Sadinle et al. 2019).
  ConformalRegressor           Split-conformal intervals (Lei et al. 2018), optionally normalized by a difficulty model.
  SpatialBlockCV               K-fold over square spatial blocks of side ``block_size`` (map units), assigned to folds
  SpatialClusterCV             K-fold over k-means clusters of the sample coordinates (spatially contiguous folds).
  aoa                          Map the Dissimilarity Index and the Area of Applicability for a feature raster.
  coverage                     Empirical coverage of intervals.
  cross_validate_spatial       Run cross-validation with a spatial splitter; returns per-fold scores and the mean.
  dissimilarity_index          Dissimilarity Index of new data to training data, plus the AOA threshold.
  permutation_importance       Drop in score when each feature (or feature ``groups``, e.g. all S1 bands) is shuffled.
  shap_importance              Mean |SHAP| per feature (averaged over classes for multiclass).
  shap_values                  SHAP explanation object (TreeExplainer for tree ensembles, else a model-agnostic

=== geolattice.rsense.viz  (7) ========================================
  interactive_map              Interactive web map with raster and vector layers (leafmap). ``split=(left, right)``
  plot_pointcloud              3-D view of a PointCloud with PyVista (interactive) or matplotlib (fallback, subsampled).
  plot_raster                  Plot a single-band raster (continuous or categorical with ``{value: (label, color)}``).
  plot_rgb                     Show an RGB composite with map coordinates.
  plot_timeseries              Plot pixel time series at named (x, y) points, or the spatial ``agg`` if none given.
  rgb                          Build a display-ready RGB composite DataArray (y, x, rgb), each band stretched 0-1.
  stretch                      Scale an array to 0-1 for display (NaN preserved).

=== geolattice.rsense.scale  (5) ========================================
  export_stac                  Create a self-contained STAC catalog with one item per raster file.
  open_cube                    Open a Zarr cube lazily with its native chunks and CRS.
  rechunk_for                  Rechunk a Dataset/DataArray for spatial-first (``time=None`` → -1 keeps full time
  start_cluster                Start a Dask ``Client``.
  to_zarr_cube                 Write (or append along ``append_dim``) a cube to Zarr with sensible chunks/compression.

=== geolattice.rsense.apps  (3) ========================================
  create_app                   Copy a template app to ``path``; run it with ``streamlit run <file>``.
  launch                       Copy a template to a temp dir and launch it with Streamlit.
  list_templates               
Code
# This code demonstrates how to inspect and list the custom accessor methods available for xarray's
# Dataset and DataArray objects in the geolattice.rsense module.

import xarray as xr  # xarray is a package for N-dimensional labeled arrays (useful for remote sensing).

# Import custom accessors for xarray, which add "rs" property to xarray objects for remote sensing methods.
from geolattice.rsense.accessor import RSDataArrayAccessor, RSDatasetAccessor

# Get a list of all public (non-private) methods provided by the RSDatasetAccessor (xarray.Dataset.rs)
ds_methods = [m for m in dir(RSDatasetAccessor) if not m.startswith("_")]

# Get a list of all public (non-private) methods provided by the RSDataArrayAccessor (xarray.DataArray.rs)
da_methods = [m for m in dir(RSDataArrayAccessor) if not m.startswith("_")]

# Print available methods for the custom accessors attached to Dataset and DataArray
print("Dataset.rs   :", ", ".join(ds_methods))
print("DataArray.rs :", ", ".join(da_methods))  # the methods the .rs accessor adds to a DataArray
Dataset.rs   : clip, cloud_mask, composite, index, mask_clouds, reproject, scale, sensor, to_cpu, to_device, with_sensor, write
DataArray.rs : apply_tiled, clip, cloud_mask, composite, index, mask_clouds, reproject, scale, sensor, to_cpu, to_device, with_sensor, write, zonal_stats

To read the full documentation of any entry, use help(), for example help(rs.optical.index), or rs.optical.index? in Jupyter.

Setup and data

This module uses three scenes from the GeoLattice data folder in Dropbox

Dataset Folder Contents Used for
Landsat 8 OLI/TIRS Level-1 Landsat8_RAW/ Collection 1 L1TP subset (16 × 15 km), path 16 / row 30, acquired 2016-09-27: farmland between Canandaigua and Seneca lakes in the Finger Lakes region of New York (42.84°N, 77.13°W; UTM 18N, 30 m); bands 1 to 11, quality band and the MTL.txt metadata file Radiometric calibration, spectral indices, thermal infrared, scattering
Sentinel-2 MSI Sentinel_2/ 10 bands resampled to 10 m over a 2.1 × 1.7 km area in Amherst, near Buffalo, New York (43.00°N, 78.81°W; UTM 17N), values are reflectance × 10,000; 108 labelled ground-truth polygons (GroundTruth_data.shp) Spectral signatures, red edge, spatial resolution
Landsat 9 OLI-2 Level-2 LC09_L2SP_138043_20221216_20221223_02_T1/ Collection 2 surface reflectance, path 138 / row 43, 2022-12-16, northwestern Bangladesh (window centred near 24.58°N, 88.96°E) Scaling Level-2 products

Getting more data. The PyGIS Explorer app lets you draw an area of interest, search a catalogue and download the scenes you select from Earth Search (AWS), Microsoft Planetary Computer, Copernicus Data Space (CDSE), NOAA Digital Coast and USGS 3DEP lidar. The same searches are available in code through rs.access.stac_search, rs.access.stac_load, rs.access.cdse_search and rs.access.earthdata_search (notebook 09_01_03).

Installation. This notebook needs installation option 5 (core, spatial analysis, spatial statistics, geostatistics and remote sensing): pip install "geolattice[remote-sensing]". See “Installation options” in the GeoLattice README.

Code
# Import necessary libraries
from pathlib import Path
import geopandas as gpd  # vector data

# Set the base data directory
DATA = Path("../../../../Data/00_shared/data_remote_sensing")

# Set the directory and ID string for the Landsat 8 imagery (Level 1 product)
L8_DIR = DATA / "Landsat8_RAW"
L8_ID = "LC08_L1TP_016030_20160927_20170220_01_T1"  # Landsat 8 scene ID

# Parse the Landsat metadata file using the 'parse_mtl' function from rs.optical
# This reads key-value pairs describing the scene characteristics
mtl = rs.optical.parse_mtl(L8_DIR / f"{L8_ID}_MTL.txt")

# List of metadata fields of interest for display
fields_of_interest = [
    "SPACECRAFT_ID",
    "SENSOR_ID",
    "DATE_ACQUIRED",
    "SCENE_CENTER_TIME",
    "WRS_PATH",
    "WRS_ROW",
    "CLOUD_COVER",
    "SUN_ELEVATION",
    "SUN_AZIMUTH",
    "EARTH_SUN_DISTANCE"
]

# Print each selected metadata attribute and its value, formatting key names for clarity
for key in fields_of_interest:
    print(f"{key:20s} {mtl[key]}")  # field name and value
SPACECRAFT_ID        LANDSAT_8
SENSOR_ID            OLI_TIRS
DATE_ACQUIRED        2016-09-27
SCENE_CENTER_TIME    15:51:39.9873550Z
WRS_PATH             16.0
WRS_ROW              30.0
CLOUD_COVER          18.77
SUN_ELEVATION        42.38608767
SUN_AZIMUTH          157.00326767
EARTH_SUN_DISTANCE   1.0021199
Code
# Define a mapping from Landsat 8 band numbers to their descriptive names
L8_BANDS = {
    1: "coastal",   # Coastal/aerosol band
    2: "blue",      # Blue band
    3: "green",     # Green band
    4: "red",       # Red band
    5: "nir",       # Near-infrared band
    6: "swir16",    # Shortwave infrared 1 (1.6 μm)
    7: "swir22",    # Shortwave infrared 2 (2.2 μm)
    9: "cirrus",    # Cirrus cloud band
    10: "tir1",     # Thermal infrared 1
    11: "tir2"      # Thermal infrared 2
}

# Read each selected Landsat band into an xarray Dataset.
# - The 'rs.read' function loads the raster file (.TIF) for each band.
# - .squeeze("band", drop=True) ensures any singleton 'band' dimensions are removed for 2D array access.
# - Each band gets mapped to its descriptive name as a data variable in the Dataset.
dn = xr.Dataset({
    name: rs.read(L8_DIR / f"{L8_ID}_B{b}.TIF").squeeze("band", drop=True)
    for b, name in L8_BANDS.items()
})

# Write the coordinate reference system (CRS) metadata into the dataset using the CRS from the red band
dn = dn.rio.write_crs(dn["red"].rio.crs)

# Print the CRS, the size of each dimension (number of pixels), and the pixel size in meters.
print(dn.rio.crs, dict(dn.sizes), f"{abs(float(dn.x[1] - dn.x[0])):.0f} m pixels")

# Show a summary of the resulting dataset
dn
EPSG:32618 {'x': 541, 'y': 504} 30 m pixels
<xarray.Dataset> Size: 11MB
Dimensions:      (x: 541, y: 504)
Coordinates:
  * x            (x) float64 4kB 3.182e+05 3.182e+05 ... 3.344e+05 3.344e+05
  * y            (y) float64 4kB 4.753e+06 4.753e+06 ... 4.738e+06 4.738e+06
    spatial_ref  int64 8B 0
Data variables:
    coastal      (y, x) float32 1MB ...
    blue         (y, x) float32 1MB ...
    green        (y, x) float32 1MB ...
    red          (y, x) float32 1MB ...
    nir          (y, x) float32 1MB ...
    swir16       (y, x) float32 1MB ...
    swir22       (y, x) float32 1MB ...
    cirrus       (y, x) float32 1MB ...
    tir1         (y, x) float32 1MB ...
    tir2         (y, x) float32 1MB ...
Code
# Define the path to the Sentinel-2 data folder
S2_DIR = DATA / "Sentinel_2"

# Dictionary mapping Sentinel-2 band filenames to canonical band names
S2_BANDS = {
    "B2": "blue",
    "B3": "green",
    "B4": "red",
    "B5": "rededge1",
    "B6": "rededge2",
    "B8": "nir",
    "B8A": "nir08",
    "B11": "swir16",
    "B12": "swir22"
}

# Read each specified band into an xarray Dataset:
# - For each key:value pair (e.g., "B2": "blue") in S2_BANDS,
#   read the .tif file for that band from disk.
# - Remove any singleton (single-length) "band" dimension for a 2D array.
# - Scale the raw integer data to reflectance by dividing by 10,000.
# - Store each band as a variable with its canonical name in the Dataset.
s2 = xr.Dataset({
    name: rs.read(S2_DIR / f"{b}.tif").squeeze("band", drop=True) / 10000
    for b, name in S2_BANDS.items()
})

# Sentinel-2 GeoTIFFs carry no coordinate system metadata,
# so we assign the correct UTM 17N CRS (EPSG:32617) from documentation
s2 = s2.rio.write_crs("EPSG:32617")

# Load land use class information from a CSV, setting Class_ID as the index
# Resulting Series maps integer IDs to land use names
classes = pd.read_csv(S2_DIR / "Landuse_ID.csv").set_index("Class_ID")["Landuse"]

# Load ground truth polygons from a shapefile and set CRS to match the imagery
gt = gpd.read_file(S2_DIR / "GroundTruth_data.shp").set_crs("EPSG:32617")

# Filter out any polygons whose Class_ID does not exist in the land use mapping
# and create a copy to retain independence from the original DataFrame
gt = gt[gt["Class_ID"].isin(classes.index)].copy()

# Add a "Landuse" column to the polygons by mapping their Class_ID to descriptive names
gt["Landuse"] = gt["Class_ID"].map(classes)

# Print size information for the image data and the polygon counts per land use class
print(dict(s2.sizes), "| polygons per class:", gt["Landuse"].value_counts().to_dict())
{'x': 210, 'y': 170} | polygons per class: {'Building': 42, 'Parking/road/pavement': 28, 'Grass': 15, 'Tree/bushes': 14, 'Water': 5}

The Sentinel-2 folder also holds a file named B7.tif, but it is byte-for-byte identical to B6.tif, so it cannot be band 7 and is left out. Nine polygons with class 0 have no label in Landuse_ID.csv and are dropped.

Where satellite bands sit on the spectrum

Sensors sample the spectrum in discrete bands. The central wavelengths below come from the official sensor specifications. Sentinel-2 adds three narrow red-edge bands (705 to 783 nm) that Landsat lacks; these respond strongly to chlorophyll content.

Code
# Create a DataFrame describing the reflective bands for three satellite sensors:
# Landsat 8/9 OLI, Sentinel-2 MSI, and MODIS. Each row contains:
# - the sensor name
# - the band name as used by the sensor
# - the center wavelength for that band (in nanometers)
# - the wavelength width of the band (in nanometers)
# - the canonical name used by geolattice.rsense for that band
bands = pd.DataFrame([
    # sensor, band, centre (nm), width (nm), canonical name used by geolattice.rsense
    ("Landsat 8/9 OLI", "B1", 443, 16, "coastal"), 
    ("Landsat 8/9 OLI", "B2", 482, 60, "blue"),
    ("Landsat 8/9 OLI", "B3", 561, 57, "green"), 
    ("Landsat 8/9 OLI", "B4", 655, 37, "red"),
    ("Landsat 8/9 OLI", "B5", 865, 28, "nir"), 
    ("Landsat 8/9 OLI", "B6", 1609, 85, "swir16"),
    ("Landsat 8/9 OLI", "B7", 2201, 187, "swir22"),
    ("Sentinel-2 MSI", "B1", 443, 20, "coastal"), 
    ("Sentinel-2 MSI", "B2", 490, 65, "blue"),
    ("Sentinel-2 MSI", "B3", 560, 35, "green"), 
    ("Sentinel-2 MSI", "B4", 665, 30, "red"),
    ("Sentinel-2 MSI", "B5", 705, 15, "rededge1"), 
    ("Sentinel-2 MSI", "B6", 740, 15, "rededge2"),
    ("Sentinel-2 MSI", "B7", 783, 20, "rededge3"), 
    ("Sentinel-2 MSI", "B8", 842, 115, "nir"),
    ("Sentinel-2 MSI", "B8A", 865, 20, "nir08"), 
    ("Sentinel-2 MSI", "B11", 1610, 90, "swir16"),
    ("Sentinel-2 MSI", "B12", 2190, 180, "swir22"),
    ("MODIS", "b3", 469, 20, "blue"), 
    ("MODIS", "b4", 555, 20, "green"), 
    ("MODIS", "b1", 645, 50, "red"),
    ("MODIS", "b2", 858, 35, "nir"), 
    ("MODIS", "b5", 1240, 20, "swir12"),
    ("MODIS", "b6", 1640, 24, "swir16"), 
    ("MODIS", "b7", 2130, 50, "swir22"),
], columns=["sensor", "band", "centre_nm", "width_nm", "canonical"])

# Make a bar plot showing where these reflective bands are located on the spectrum for each sensor.
# Each horizontal bar represents a spectral band, its width equals the band wavelength range,
# and color corresponds to the canonical band name.
fig, ax = plt.subplots(figsize=(11, 3.6))
colours = {  # colour of each canonical band name
    "coastal": "#542788", "blue": "#2166ac", "green": "#1b7837", "red": "#b2182b",
    "rededge1": "#d6604d", "rededge2": "#f4a582", "rededge3": "#fdae61", "nir": "#7f3b08",
    "nir08": "#b35806", "swir12": "#8c510a", "swir16": "#636363", "swir22": "#252525"
}

# Group each sensor's bands and plot them row-by-row, coloring by canonical.
for i, (sensor, grp) in enumerate(bands.groupby("sensor", sort=False)):
    for _, b in grp.iterrows():  # each band of that sensor
        # Draw each band as a horizontal bar at the sensor's row with band width and centered at the central wavelength.
        ax.barh(i, b.width_nm, left=b.centre_nm - b.width_nm / 2, height=0.6, color=colours[b.canonical])
        # Place the band name just above the bar.
        ax.text(b.centre_nm, i + 0.38, b.band, ha="center", fontsize=7)

# Set axis labels and limits.
ax.set_yticks(range(3))
ax.set_yticklabels(bands.sensor.unique())  # sensor names on the y axis
ax.set_xlabel("Wavelength (nm)")  # x label
ax.set_xlim(400, 2350)  # visible to shortwave infrared
# title
ax.set_title("Reflective bands of Landsat 8/9, Sentinel-2 and MODIS (colour = geolattice.rsense canonical name)")
plt.tight_layout()  # arrange
plt.show()  # draw

geolattice.rsense refers to bands by these canonical names (blue, red, nir, swir16, …) so the same index formula works for every sensor. It translates each product’s own names (B04, SR_B4, sur_refl_b01) automatically:

Code
# Import the SENSOR_BANDS dictionary, which contains the mapping between canonical band names (like "blue", "nir", etc.)
# and each sensor's native band names for several optical satellite sensors.
from geolattice.rsense.optical import SENSOR_BANDS

# Build and display a DataFrame showing how the same canonical band (row; e.g., "blue") is called by each sensor (column):
# For each sensor, create a dictionary mapping the canonical name (e.g., "blue") to 
# a human-readable string listing all native band names for that sensor, joined by " / ".
# Collect these per-sensor dictionaries into a larger dictionary (columns).
# Finally, display the table, filling any missing bands with an en dash.
pd.DataFrame({
    s: {k: " / ".join(v) for k, v in SENSOR_BANDS[s].items()}
    for s in ["landsat", "sentinel2", "modis", "hls_s30"]
}).fillna("–")
landsat sentinel2 modis hls_s30
coastal coastal / SR_B1 coastal / B01 – B01
blue blue / SR_B2 blue / B02 sur_refl_b03 B02
green green / SR_B3 green / B03 sur_refl_b04 B03
red red / SR_B4 red / B04 sur_refl_b01 B04
nir nir08 / nir / SR_B5 nir / B08 sur_refl_b02 B08
swir16 swir16 / SR_B6 swir16 / B11 sur_refl_b06 B11
swir22 swir22 / SR_B7 swir22 / B12 sur_refl_b07 B12
thermal lwir11 / lwir / ST_B10 – b31 / Band31 / LST_Day_1km –
qa qa_pixel / QA_PIXEL scl / SCL sur_refl_state_500m / state_1km / sur_refl_state_1km Fmask
rededge1 – rededge1 / B05 – B05
rededge2 – rededge2 / B06 – B06
rededge3 – rededge3 / B07 – B07
nir08 – nir08 / B8A – B8A
swir12 – – sur_refl_b05 –

Spectral signatures from real images

A spectral signature is how reflectance changes with wavelength for a material:

  • Water reflects a little blue and green light and absorbs almost all NIR and SWIR, so it is dark beyond the visible.
  • Healthy vegetation absorbs blue and red light for photosynthesis, reflects some green, and reflects NIR very strongly because of the internal structure of leaves. The sharp rise between red and NIR is the red edge. Leaf water absorbs in the SWIR.
  • Built surfaces and bare soil have flatter spectra that rise gradually with wavelength.

Sentinel-2 signatures from ground-truth polygons

rs.classify.extract_samples collects the reflectance of every pixel inside the labelled polygons. Their class means give real surface-reflectance signatures with the red-edge bands.

Code
# Extract per-pixel spectral data and class labels from Sentinel-2 and ground-truth polygons
X, y = rs.classify.extract_samples(s2, gt, "Class_ID")

# Define the mapping from canonical band names to their wavelength (nm) for Sentinel-2
S2_NM = {
    "blue": 490,
    "green": 560,
    "red": 665,
    "rededge1": 705,
    "rededge2": 740,
    "nir": 842,
    "nir08": 865,
    "swir16": 1610,
    "swir22": 2190
}

# For each land cover class, compute the mean reflectance in each band:
# - Select only those columns in X that correspond to canonical bands defined in S2_NM.
# - Map each pixel label 'y' to its human-readable class name using 'classes'.
# - Group the reflectance samples by class name and compute the mean for each band.
sig_s2 = X[list(S2_NM)].groupby(pd.Series(y, index=X.index).map(classes)).mean()

# Print the number of pixels in each class to inform how many samples contributed to each signature
print("pixels per class:", pd.Series(y).map(classes).value_counts().to_dict())

# Show the class mean spectral signatures, rounded to 3 decimal places
sig_s2.round(3)
pixels per class: {'Tree/bushes': 504, 'Parking/road/pavement': 352, 'Grass': 313, 'Building': 275, 'Water': 53}
blue green red rededge1 rededge2 nir nir08 swir16 swir22
Building 0.355 0.384 0.407 0.374 0.373 0.428 0.419 0.347 0.227
Grass 0.033 0.067 0.048 0.105 0.275 0.383 0.397 0.244 0.128
Parking/road/pavement 0.099 0.109 0.120 0.119 0.127 0.138 0.153 0.172 0.154
Tree/bushes 0.024 0.044 0.033 0.070 0.185 0.255 0.267 0.163 0.090
Water 0.066 0.101 0.072 0.060 0.021 0.018 0.021 0.020 0.015
Code
# This code plots the mean spectral reflectance signatures for different land cover classes
# from Sentinel-2 satellite data, using samples labeled in the ground truth.

# Create a new figure and axes for the plot, with specified size
fig, ax = plt.subplots(figsize=(10, 4.8))

# Define plot color and marker styles for each class
style = {
    "Water": ("#2166ac", "o"),
    "Tree/bushes": ("#1b7837", "s"),
    "Grass": ("#7fbc41", "^"),
    "Building": ("#b2182b", "D"),
    "Parking/road/pavement": ("#636363", "v")
}

# Iterate over each class and its mean reflectance values
for cls, row in sig_s2.iterrows():
    # Get color and marker for this class, or use default if not specified
    col, mk = style.get(cls, ("k", "o"))
    # Plot signature: wavelength vs. mean reflectance for this class
    ax.plot(list(S2_NM.values()), row.values, marker=mk, color=col, lw=2, label=cls)

# Highlight the red-edge region in the spectrum
ax.axvspan(690, 760, color="#fdae61", alpha=0.2, label="red edge")

# Set axes labels
ax.set_xlabel("Wavelength (nm)")
ax.set_ylabel("Surface reflectance")  # y label

# Add plot title
ax.set_title("Sentinel-2 spectral signatures, Buffalo NY (class means of ground-truth pixels)")

# Add legend with smaller font size
ax.legend(fontsize=8)

# Adjust layout and display the plot
plt.tight_layout()
plt.show()  # draw

These are surface-reflectance signatures from 1,497 labelled pixels, and each follows the textbook shape:

  • Vegetation. Trees and grass absorb red light (reflectance 0.03 to 0.05) and reflect strongly in the NIR (0.26 and 0.38). The red edge is visible in the two red-edge bands: grass rises from 0.105 at 705 nm to 0.275 at 740 nm and 0.383 at 842 nm. Grass is brighter than the tree canopy in the NIR because tree crowns contain shadows. Both drop in the SWIR, where leaf water absorbs.
  • Water (one pond, 53 pixels) is dark in the NIR and SWIR (about 0.02). Its green peak (0.10) is higher than the blue, which suggests algae or suspended sediment rather than clear water.
  • Buildings are bright and nearly flat from blue to NIR (0.36 to 0.43): light-coloured flat roofs. Roads and parking lots are flat and dark (0.10 to 0.17).

Landsat 8 scene: colour composites

The Landsat 8 Level-1 file stores digital numbers. We first convert the reflective bands to top-of-atmosphere reflectance with the coefficients from the MTL file (the details are in The Processing levels: from DN to physical units section), then display a natural-colour composite (red, green, blue) and a false-colour composite (NIR, red, green), in which vegetation appears red.

Code
# Select all reflective bands to process from the Landsat 8 band mapping.
# Bands 1-7 and 9 are reflective (the rest are thermal or non-optical), so we keep those.
REFLECTIVE = {b: n for b, n in L8_BANDS.items() if b <= 7 or b == 9}

# For each reflective band, convert the digital number (DN) data to top-of-atmosphere (TOA) reflectance.
# This uses the multiplicative and additive calibration coefficients from the MTL metadata file,
# as well as the sun elevation angle. The resulting reflectance arrays are combined into an xarray Dataset.
toa = xr.Dataset({
    name: rs.optical.toa_reflectance(
        dn[name],
        mtl[f"REFLECTANCE_MULT_BAND_{b}"],
        mtl[f"REFLECTANCE_ADD_BAND_{b}"],
        mtl["SUN_ELEVATION"]
    )
    for b, name in REFLECTIVE.items()
}).rio.write_crs(dn.rio.crs)  # Set the coordinate reference system to match the original data

# Create a single figure with 3 subplots, arranged in one row.
fig, axes = plt.subplots(1, 3, figsize=(17, 5.4))

# Display three types of RGB composites using the reflectance data:
# 1. A true-color (natural color) composite: (red, green, blue)
rs.viz.plot_rgb(toa, "true_color", ax=axes[0], title="Natural colour (red, green, blue)")

# 2. A false-color composite, showing NIR, red, and green (vegetation shows up as red).
rs.viz.plot_rgb(toa, ("nir", "red", "green"), ax=axes[1], title="False colour (NIR, red, green)")

# 3. A SWIR composite: SWIR2, NIR, and red (useful for soil and moisture contrasts).
rs.viz.plot_rgb(toa, ("swir22", "nir", "red"), ax=axes[2], title="SWIR composite (SWIR2, NIR, red)")

# Remove axis tick marks for cleaner visual appearance.
for a in axes:
    a.set_xticks([])  # no x ticks
    a.set_yticks([])  # no y ticks

# Optimize layout and display the figure.
plt.tight_layout()
plt.show()  # draw

The subset is a patchwork of farm fields photographed in late September. In the false-colour image, growing crops, pasture and woodlots are red; harvested or bare fields are cyan and grey; small towns and roads are bluish grey. In the SWIR composite, vegetation is green and bare soil is magenta, because dry soil is bright in the SWIR while leaf water absorbs there.

Spectral indices

Spectral indices turn these contrasts into single numbers. NDVI, \((NIR - Red)/(NIR + Red)\), is high for vegetation; NDWI, \((Green - NIR)/(Green + NIR)\), is positive for open water; and NDBI, \((SWIR1 - NIR)/(SWIR1 + NIR)\), is high for built-up and bare surfaces. geolattice.rsense registers more than a hundred indices:

Code
# List all available spectral indices registered in rs.optical
catalog = rs.optical.list_indices()

# Print the total number of registered indices
print(len(catalog), "indices registered")

# Summarize the registered indices by their domain (e.g., vegetation, water, urban, etc.)
# Show a table with the counts for each domain
catalog.groupby("domain").size().sort_values(ascending=False).to_frame("count").T
121 indices registered
domain vegetation water rededge rgb burn urban soil snow other
count 41 20 18 14 9 7 5 4 3
Code
# Compute three common spectral indices (NDVI, NDWI, NDBI) for the scene using the reflectance data.
# - NDVI: Normalized Difference Vegetation Index, highlights vegetation
# - NDWI: Normalized Difference Water Index, highlights water
# - NDBI: Normalized Difference Built-up Index, highlights built-up and bare surfaces
vi = rs.optical.index(toa, ["NDVI", "NDWI", "NDBI"])

# Create a figure with 3 side-by-side subplots to visualize the three indices.
fig, axes = plt.subplots(1, 3, figsize=(17, 4.8))
for a, (name, cmap) in zip(  # each panel with an index and its colour map
    axes, [("NDVI", "RdYlGn"), ("NDWI", "Blues"), ("NDBI", "OrRd")]
):
    # Plot each index as an image, using an appropriate colormap and axis title.
    rs.viz.plot_raster(vi[name].rio.write_crs(toa.rio.crs), ax=a, cmap=cmap, title=name)
    a.set_xticks([])  # Remove x-axis ticks for a cleaner look
    a.set_yticks([])  # Remove y-axis ticks

plt.tight_layout()    # Adjust subplot spacing for neatness
plt.show()  # draw

# Define masks to classify pixels into three land cover types:
#   - Dense vegetation: pixels where NDVI > 0.6
#   - Harvested/bare fields: NDVI < 0.3 and not water (NDWI <= 0)
#   - Farm ponds (water): NDWI > 0
masks = {
    "Dense vegetation (NDVI > 0.6)": vi["NDVI"] > 0.6,
    "Harvested / bare fields (NDVI < 0.3)": (vi["NDVI"] < 0.3) & (vi["NDWI"] <= 0),
    "Farm ponds (NDWI > 0)": vi["NDWI"] > 0,
}

# Specify the order of Landsat 8 spectral bands to summarize reflectance
L8_ORDER = ["coastal", "blue", "green", "red", "nir", "swir16", "swir22"]

# For each class (mask), calculate the mean reflectance in each band by masking out pixels outside the class.
# Construct a DataFrame: rows = classes, columns = band reflectances.
sig_l8 = pd.DataFrame(
    {cls: [float(toa[b].where(m).mean()) for b in L8_ORDER] for cls, m in masks.items()},
    index=L8_ORDER,
).T

# Add the count of pixels in each class
sig_l8.insert(0, "pixels", [int(m.sum()) for m in masks.values()])
# Add the percentage of the scene that each class represents
sig_l8.insert(1, "% of scene", [round(float(m.mean()) * 100, 2) for m in masks.values()])

# Present the reflectance statistics rounded to 3 decimals
sig_l8.round(3)

pixels % of scene coastal blue green red nir swir16 swir22
Dense vegetation (NDVI > 0.6) 140996 51.71 0.114 0.091 0.078 0.053 0.351 0.169 0.081
Harvested / bare fields (NDVI < 0.3) 40302 14.78 0.143 0.130 0.129 0.148 0.238 0.289 0.248
Farm ponds (NDWI > 0) 129 0.05 0.124 0.103 0.083 0.066 0.062 0.046 0.037

Dense vegetation (NDVI > 0.6) covers 52% of the subset and harvested or bare fields (NDVI < 0.3) 15%. Their TOA signatures show the same contrasts as the Sentinel-2 ground truth:

  • Vegetation has red 0.053 and NIR 0.351.
  • Bare fields have red 0.148, NIR 0.238 and SWIR1 0.289. SWIR1 is above NIR, so NDBI is positive for bare soil as well as for buildings, a well-known limitation of that index.

Open water is almost absent. NDWI is negative everywhere except 129 pixels (0.05%) of small farm ponds, which are mixed pixels at 30 m. Even their TOA NIR reflectance (0.06) is far above that of clear water, because of path radiance and the land around them.

Physics in the data: the Sun’s spectrum and atmospheric scattering

Two theoretical results from the Physical principles section can be checked against the Landsat scene.

The solar spectrum hidden in the metadata

The MTL file gives two linear conversions for each band: DN to radiance (\(L = M_L\,DN + A_L\)) and DN to reflectance without the sun-angle term (\(\rho' = M_\rho\,DN + A_\rho\)). Both describe the same pixel, so the radiative transfer equation of the Radiometric quantities and the radiative transfer equation section, \(\rho' = \pi L d^2 / E_{sun}\), lets us solve for the exo-atmospheric solar irradiance each band sees:

\[E_{sun} = \frac{\pi\,L\,d^2}{\rho'}.\]

Planck’s law for a 5,778 K Sun predicts the same quantity: \(E_\lambda = \pi B_\lambda(T)\,(R_{sun}/d_{AU})^2\).

Code
# --- Explanation of the code below ---
# The following code section computes and compares the exo-atmospheric solar irradiance values used in a Landsat 8 scene's metadata (the MTL file)
# to theoretical values computed from Planck's law for a blackbody at the Sun's temperature (~5,778 K).
# This checks how closely the calibration metadata matches the physical solar spectrum.

# 1. Define the center wavelengths (in microns) for each OLI/Landsat 8 band.
OLI_CENTRE = {
    "coastal": 0.443,
    "blue": 0.482,
    "green": 0.561,
    "red": 0.655,
    "nir": 0.865,
    "swir16": 1.609,
    "swir22": 2.201,
}

# 2. Get the Earth-Sun distance for the day of imaging, from the MTL metadata.
d = mtl["EARTH_SUN_DISTANCE"]

# 3. Recover E_sun (exo-atmospheric solar irradiance) for each band using metadata calibration coefficients.
esun = {}
for b, name in REFLECTIVE.items():  # every reflective band
    if name not in OLI_CENTRE:  # skip bands without a centre wavelength
        continue
    # Choose any digital number (DN) value (here 20,000) since the ratio is linear; it cancels out.
    dn_ref = 20000.0
    # Compute radiance at the top of atmosphere using radiometric rescaling.
    L = mtl[f"RADIANCE_MULT_BAND_{b}"] * dn_ref + mtl[f"RADIANCE_ADD_BAND_{b}"]
    # Compute reflectance without correcting for sun angle.
    rho = mtl[f"REFLECTANCE_MULT_BAND_{b}"] * dn_ref + mtl[f"REFLECTANCE_ADD_BAND_{b}"]
    # Rearranged radiative transfer equation gives E_sun.
    esun[name] = np.pi * L * d**2 / rho
# Store these values in a pandas Series.
esun = pd.Series(esun, name="E_sun from MTL (W m⁻² µm⁻¹)")

# 4. Compute the theoretical solar irradiance at each band's wavelength using Planck's law (blackbody at 5,778 K).
#    - Converts wavelengths to meters, applies πB_λ(T), multiplies by the (Sun radius/distance)^2 solid angle, and scales units.
planck_esun = pd.Series(
    {
        n: np.pi * planck(OLI_CENTRE[n] * 1e-6, 5778) * (6.96e8 / 1.496e11) ** 2 * 1e-6
        for n in esun.index
    },
    name="Planck 5,778 K (W m⁻² µm⁻¹)",
)

# 5. Create a DataFrame summarizing the band center wavelengths, MTL irradiance, Planck prediction, and their ratio.
cmp = pd.concat(
    [pd.Series(OLI_CENTRE)[esun.index].rename("centre (µm)"), esun, planck_esun],
    axis=1,
)
# how close the metadata irradiance is to the Planck prediction
cmp["ratio MTL / Planck"] = cmp.iloc[:, 1] / cmp.iloc[:, 2]

# 6. Display the DataFrame, rounded for neatness.
display(cmp.round(3))

# 7. Plot comparison of the MTL (metadata) and theoretical (Planck) exo-atmospheric solar irradiances across wavelengths.
wl_um = np.linspace(0.3, 2.5, 400)
fig, ax = plt.subplots(figsize=(8.5, 4.2))  # one panel
# Plot the Planck blackbody curve (in solar units).
ax.plot(
    wl_um,
    np.pi * planck(wl_um * 1e-6, 5778) * (6.96e8 / 1.496e11) ** 2 * 1e-6,
    label="Planck, 5,778 K blackbody",
)
# Plot the actual band center values derived from the MTL.
ax.plot(
    cmp["centre (µm)"], cmp.iloc[:, 1], "o", ms=8, label="Landsat 8 bands (from the MTL file)"
)
ax.set_xlabel("Wavelength (µm)")  # x label
ax.set_ylabel("Solar irradiance (W m⁻² µm⁻¹)")  # y label
ax.set_title("Exo-atmospheric solar irradiance")  # title
ax.legend()  # legend
plt.tight_layout()  # arrange
plt.show()  # draw
centre (µm) E_sun from MTL (W m⁻² µm⁻¹) Planck 5,778 K (W m⁻² µm⁻¹) ratio MTL / Planck
coastal 0.443 1972.318 1727.557 1.142
blue 0.482 2019.631 1788.960 1.129
green 0.561 1861.103 1744.104 1.067
red 0.655 1569.337 1536.074 1.022
nir 0.865 960.359 996.773 0.963
swir16 1.609 238.826 203.072 1.176
swir22 2.201 80.500 74.703 1.078

The irradiance implied by the metadata peaks in the blue band at 2,020 W m⁻² µm⁻¹ and falls to 80 W m⁻² µm⁻¹ at 2.2 µm. That is the solar spectrum, recovered from two lines of calibration coefficients. The 5,778 K blackbody reproduces its shape to within 2 to 18%, with a peak near 0.5 µm as Wien’s law predicts. The real Sun is not a perfect blackbody: its photosphere emits from different temperatures at different wavelengths, and absorption lines are averaged over each band. That is why measured solar spectra, not Planck curves, are used in calibration.

Rayleigh scattering in the darkest pixels

The darkest pixels of a scene reflect almost nothing at the surface, so most of their TOA signal is atmospheric path radiance. If molecular (Rayleigh) scattering dominates, the dark-object reflectance should fall steeply with wavelength. The dark object subtraction method (DOS1, Chavez 1996; rs.optical.dos1) uses exactly this signal for a first-order atmospheric correction.

The method needs genuinely dark targets in every band it corrects: deep clear water or deep shadow. This farmland subset has no lake, and in the visible bands the darkest pixels are dense crops and woodland, which absorb blue and red light for photosynthesis. In the NIR and SWIR the same vegetation is bright, so the darkest pixels there are not dark at all. We therefore test the scattering law on the visible bands only.

Code
# Select the four visible Landsat 8 (OLI) bands by name.
vis = ["coastal", "blue", "green", "red"]

# For each band, calculate the 0.1th percentile of Top-Of-Atmosphere (TOA) reflectance values,
# representing the darkest pixels (potentially shadow or water). Store these in a pandas Series.
dark = pd.Series(
    {b: float(np.nanpercentile(toa[b].values, 0.1)) for b in OLI_CENTRE},
    name="dark-object TOA reflectance (0.1th percentile)"
)

# Fit a straight line in log-log space (power-law) to the relationship between wavelength and
# dark-object reflectance across the visible bands, to see how reflectance falls off with wavelength.
# This gives a slope which, for pure Rayleigh scattering, should be -4.
slope, intercept = np.polyfit(
    np.log([OLI_CENTRE[b] for b in vis]),
    np.log(dark[vis].values),
    1
)
# slope of the fitted power law
print(f"Power-law fit over the visible bands: dark reflectance ∝ λ^{slope:.2f}  (pure Rayleigh: λ^-4)")

# Plot the results:
fig, ax = plt.subplots(figsize=(8, 4.2))

# Plot the measured dark-object (0.1th percentile) reflectances vs wavelength for the visible bands,
# using a log-log scale.
ax.loglog([OLI_CENTRE[b] for b in vis], dark[vis].values, "o-", label="darkest 0.1% of pixels")

# Create an array of wavelengths between the blue and red bands (in microns).
lam = np.linspace(0.43, 0.68, 50)

# Plot the theoretical Rayleigh scattering line (λ^-4) normalised to the blue band.
ax.loglog(
    lam,
    dark["blue"] * (lam / OLI_CENTRE["blue"]) ** -4,
    "--",
    label="λ⁻⁴ through the blue band"
)

ax.set_xlabel("Wavelength (µm)")  # x label
ax.set_ylabel("TOA reflectance")  # y label

# Plot the fitted power-law line using the computed slope, again normalised to the blue band.
ax.loglog(
    lam,
    dark["blue"] * (lam / OLI_CENTRE["blue"]) ** slope,
    ":",
    label=f"fitted λ^{slope:.2f}"
)

ax.set_title("Path radiance in the darkest pixels (visible bands)")  # title
ax.legend()  # legend
plt.tight_layout()  # arrange
plt.show()  # draw

# Apply the Dark Object Subtraction (DOS1) atmospheric correction to all OLI bands.
corrected = rs.optical.dos1(toa[list(OLI_CENTRE)])

# Construct a dataframe comparing the dark-object and median reflectance before and after correction.
pd.DataFrame({
    "TOA dark object": dark,
    "after DOS1": pd.Series({b: float(np.nanpercentile(corrected[b].values, 0.1)) for b in OLI_CENTRE}),
    "median TOA": pd.Series({b: float(toa[b].median()) for b in OLI_CENTRE}),
    "median after DOS1": pd.Series({b: float(corrected[b].median()) for b in OLI_CENTRE})
}).round(4).T
Power-law fit over the visible bands: dark reflectance ∝ λ^-2.75  (pure Rayleigh: λ^-4)

coastal blue green red nir swir16 swir22
TOA dark object 0.1050 0.0805 0.0579 0.0349 0.1275 0.0650 0.0308
after DOS1 0.0107 0.0108 0.0130 0.0118 0.1088 0.0636 0.0321
median TOA 0.1175 0.0963 0.0862 0.0710 0.2959 0.1954 0.1106
median after DOS1 0.0232 0.0266 0.0413 0.0479 0.2771 0.1940 0.1119

Across the visible bands the dark-object reflectance falls as \(\lambda^{-2.75}\): from 0.105 in the coastal band to 0.035 in the red. That is steeper than aerosol (Mie) scattering alone, but shallower than the pure Rayleigh \(\lambda^{-4}\). Two reasons:

  • Aerosols add a flatter component.
  • The darkest pixels here are vegetation, not water, so they still carry some surface reflectance.

DOS1 removes most of this haze. It lowers the median blue reflectance from 0.096 to 0.027 and the coastal band from 0.118 to 0.023, which are typical surface values for vegetated land. In the NIR it subtracts 0.019, but the darkest NIR pixels in this scene are ponds and vegetation rather than haze, so that correction removes real signal. In the SWIR it changes almost nothing.

DOS is therefore a quick fix for the visible bands when a scene has dark targets. Level-2 surface reflectance (the Level-2 surface reflectance section) is the better starting point.

The four resolutions

Every sensor is a compromise between four kinds of resolution:

Resolution Question it answers Landsat 8/9 Sentinel-2 MODIS
Spatial How small an object can be seen? 30 m (15 m pan, 100 m thermal) 10, 20, 60 m 250, 500, 1000 m
Spectral How many bands, and how narrow? 11 bands 13 bands 36 bands
Temporal How often is a place revisited? 16 days (8 with both) 5 days (two satellites) 1 to 2 days
Radiometric How finely is brightness quantized? 12-bit (Landsat 9: 14-bit), stored 16-bit 12-bit 12-bit

Improving one usually costs another: MODIS sees the whole planet daily because its pixels are large, while Sentinel-2’s 10 m pixels need five days to cover the globe.

Spatial resolution

We simulate coarser sensors by block-averaging the 10 m Sentinel-2 image to 30 m (Landsat) and 250 m (MODIS). Each coarse pixel is a mixture of everything inside it: a mixed pixel.

Code
# Create a figure with 3 horizontal subplots, sized appropriately for display.
fig, axes = plt.subplots(1, 3, figsize=(17, 4.6))

# Loop through each subplot axis and corresponding coarsening factor:
# f = 1 shows the original 10m Sentinel-2 image,
# f = 3 simulates Landsat resolution (~30m, by averaging 3x3 blocks),
# f = 25 simulates a coarse MODIS-like pixel (~250m, by averaging 25x25 blocks).
for a, f in zip(axes, [1, 3, 25]):
    if f == 1:  # first panel
        # No coarsening; use original image.
        img = s2
    else:
        # Coarsen image by the given factor, trimming edges,
        # then take mean for each coarse pixel and restore CRS info.
        img = s2.coarsen(x=f, y=f, boundary="trim").mean().rio.write_crs(s2.rio.crs)
    # Plot the image in false color (NIR, red, green), set the subplot title
    # with the simulated pixel size and dimensions.
    rs.viz.plot_rgb(
        img, ("nir", "red", "green"), ax=a,
        title=f"{10 * f} m pixels ({img.sizes['x']} × {img.sizes['y']})"
    )
    # Remove x/y axis ticks for clean output presentation.
    a.set_xticks([]); a.set_yticks([])

# Adjust subplot layout for clarity and show the figure.
plt.tight_layout()
plt.show()  # draw

At 10 m the interchange, individual buildings, parking lots and the pond in the upper left are sharp. At 30 m (Landsat) the pond and the main roads remain, but buildings merge with the lawns around them. At 250 m (MODIS) the whole 2 km area is only 48 mixed pixels: one darker pixel hints at the pond, and the land cover can only be described as fractions.

Spectral resolution

Spectral resolution decides which materials can be told apart. Trees and grass are both green vegetation; the table compares how far apart their mean signatures are in each band, relative to the variation within the classes (a simple separability measure, \(|\mu_1 - \mu_2| / \sqrt{(s_1^2 + s_2^2)/2}\)).

Code
# Create a new pandas Series that maps numeric class labels y to their descriptive class names using the 'classes' dictionary, and index it with the same indices as X.
lab = pd.Series(y, index=X.index).map(classes)

# Split the DataFrame X into two groups: one for samples labeled as "Tree/bushes" and another for samples labeled as "Grass".
a = X[lab == "Tree/bushes"]
b = X[lab == "Grass"]  # grass pixels

# Calculate the separability between the "Tree/bushes" and "Grass" classes for each Sentinel-2 band.
# For each band:
#   1. Compute the difference in mean values between the classes.
#   2. Take the absolute value of the difference.
#   3. Divide by the pooled standard deviation (the square root of the average variance of the two classes).
# This gives a measure of how distinct the two classes are in each band.
sep = (
    (a[list(S2_NM)].mean() - b[list(S2_NM)].mean()).abs()
    / np.sqrt((a[list(S2_NM)].var() + b[list(S2_NM)].var()) / 2)
).rename("tree vs grass separability")

# Format the results to two decimal places, convert to a single-row DataFrame, and display.
sep.round(2).to_frame().T
blue green red rededge1 rededge2 nir nir08 swir16 swir22
tree vs grass separability 0.56 1.41 0.63 1.99 2.38 2.04 2.11 3.94 1.7

In the visible bands trees and grass are barely separable (0.56 in blue, 0.63 in red): both absorb for photosynthesis. Separability rises to 2.0 to 2.4 in the red-edge and NIR bands, where canopy structure differs. It is highest in SWIR1 (3.9), which responds to leaf water and shadow. The narrow red-edge band at 740 nm (2.38) separates them better than the broad NIR band (2.04). An RGB camera would struggle to tell these two classes apart; a multispectral sensor with red-edge and SWIR bands does not.

Radiometric resolution

Radiometric resolution is the number of distinct brightness levels, \(2^{bits}\). Landsat 8 records 12 bits (4,096 levels) and stores them as 16-bit integers scaled to 0 to 65,535. Fewer levels cause visible banding, most of all in dark, low-contrast targets such as water.

Code
# Loop over typical radiometric resolutions (number of bits per pixel)
for bits in (1, 4, 8, 12, 16):
    # For each bit depth, print the corresponding number of brightness levels
    print(f"{bits:2d}-bit → {2**bits:6,d} levels")

# Extract the digital number (DN) values for the NIR (near-infrared) band
nir_dn = dn["nir"].values

# Filter out any invalid (non-finite) pixel values
valid = nir_dn[np.isfinite(nir_dn)]

# Print the range of NIR DN values and how many unique values are present
print(
    f"NIR DN range in this subset: {valid.min():.0f}–{valid.max():.0f}; "
    f"distinct values: {np.unique(valid).size:,}"
)

# Quantize NIR DN values to different bit depths (simulating reduced radiometric resolution).
# This is done for 2, 4, and 8 bits as examples, using simple linear scaling.
q = {
    bits: np.floor((nir_dn - valid.min()) / (valid.max() - valid.min() + 1) * 2**bits)
    for bits in (2, 4, 8)
}

# Visualize the quantized images
fig, axes = plt.subplots(1, 3, figsize=(16, 4.6))
for ax, (bits, arr) in zip(axes, q.items()):  # each bit depth with its quantised image
    ax.imshow(arr, cmap="gray")  # show it in grey
    ax.set_title(f"NIR quantized to {bits} bits ({2**bits} levels)")  # title with the number of levels
    ax.set_xticks([])  # no x ticks
    ax.set_yticks([])  # no y ticks
plt.tight_layout()  # arrange
plt.show()  # draw
 1-bit →      2 levels
 4-bit →     16 levels
 8-bit →    256 levels
12-bit →  4,096 levels
16-bit → 65,536 levels
NIR DN range in this subset: 5290–27590; distinct values: 14,190

Temporal resolution

Temporal resolution cannot be seen in a single scene, but it decides what can be monitored. Crop growth needs observations every few days to weeks, floods need hours to days, and cloud cover reduces the usable revisit: the full Landsat scene used here was 18.8% cloudy (this subset happens to be clear), and in humid regions a 16-day revisit often yields only one or two clear views a month. Combining sensors (Landsat + Sentinel-2 in the Harmonized Landsat Sentinel-2 product, rs.optical.load_hls), adding SAR, or fusing coarse daily data with fine sparse data (rs.fusion.starfm) are the usual remedies. The time-series notebooks (07_06) cover time-series analysis.

Passive and active sensors

Passive sensors record natural energy: reflected sunlight (optical) or emitted heat (thermal). Everything in the sections from Spectral signatures from real images to The four resolutions is passive.

Active sensors send their own pulse and time the echo:

  • Radar (SAR) transmits microwaves that pass through clouds and work at night, which is why Sentinel-1 is the workhorse for flood mapping in the monsoon. It measures backscatter, usually expressed in decibels (dB).
  • Lidar transmits laser pulses and records return times, giving precise 3-D point clouds of terrain and vegetation structure.

Radar backscatter spans several orders of magnitude, so it is usually shown in decibels, \(\sigma^0_{dB} = 10 \log_{10}(\sigma^0)\):

Code
# Define typical radar backscatter (sigma0, linear scale) for various surfaces
surfaces = {
    "Calm water": 0.001,
    "Bare field": 0.03,
    "Grassland": 0.08,
    "Forest": 0.15,
    "Urban corner reflector": 2.0
}

# Convert linear sigma0 values to decibel (dB) using the SAR utility function
# This helps visualize the large dynamic range in radar backscatter for each surface type
db = rs.sar.to_db(np.array(list(surfaces.values())))

# Create a DataFrame showing both the original (linear) and dB-scaled sigma0 values for easy comparison
pd.DataFrame(
    {
        "sigma0 (linear)": list(surfaces.values()),
        "sigma0 (dB)": db.round(1)
    },
    index=surfaces.keys()
)
sigma0 (linear) sigma0 (dB)
Calm water 0.001 -30.0
Bare field 0.030 -15.2
Grassland 0.080 -11.0
Forest 0.150 -8.2
Urban corner reflector 2.000 3.0

Calm water acts as a mirror and sends the pulse away from the sensor (−30 dB, very dark), while buildings form corner reflectors that send it straight back (+3 dB, very bright). The same physical contrast drives SAR flood mapping (rs.sar.flood_map) in the radar notebooks (07_03).

Processing levels: from DN to physical units

Raw sensor counts pass through a chain of corrections before analysis:

Level Content Example
L0 Raw instrument data Downlinked telemetry
L1 Calibrated, geolocated radiance or TOA reflectance (as DN with scale factors) Landsat Collection 1/2 Level-1, Sentinel-2 L1C
L2 Geophysical variables: surface reflectance, surface temperature, backscatter Landsat C2 Level-2, Sentinel-2 L2A, MOD09
L3 Gridded, composited or aggregated products MOD13 16-day NDVI
L4 Model outputs that combine data GPP, soil moisture analyses

For Landsat Level-1 the conversions use coefficients from the scene’s metadata (*_MTL.txt):

  • Radiance: \(L_\lambda = M_L \cdot DN + A_L\) (rs.optical.radiance)
  • TOA reflectance: \(\rho = (M_\rho \cdot DN + A_\rho) / \sin(\theta_{SE})\), with sun elevation \(\theta_{SE}\) (rs.optical.toa_reflectance)
  • Brightness temperature (thermal bands): \(BT = K_2 / \ln(K_1/L_\lambda + 1)\) (rs.optical.brightness_temperature), the inverse of Planck’s law for the band.

Reflective bands

Code
# This block retrieves the calibration coefficients for each reflective band (used to convert between DN, radiance, and TOA reflectance),
# and then summarizes the typical values for each band over the scene.

# Collect the multiplicative/additive coefficients ("M" and "A") for both reflectance ("rho") and radiance ("L")
# from the metadata (MTL) file for each reflective band. These are necessary for conversions:
# - between digital number (DN) and top-of-atmosphere (TOA) reflectance
# - between DN and radiance.
# The coefficients are organized into a DataFrame for easy viewing.
coef = pd.DataFrame({
    name: {
        "M_rho": mtl[f"REFLECTANCE_MULT_BAND_{b}"],   # reflectance gain
        "A_rho": mtl[f"REFLECTANCE_ADD_BAND_{b}"],    # reflectance offset
        "M_L": mtl[f"RADIANCE_MULT_BAND_{b}"],        # radiance gain
        "A_L": mtl[f"RADIANCE_ADD_BAND_{b}"]          # radiance offset
    }
    for b, name in REFLECTIVE.items()
}).T
display(coef)  # show the calibration coefficients

# For a subset of common bands, compute and summarize the central tendency of their DN, radiance, and TOA reflectance values.
# This illustrates the typical pixel values encountered in this scene after calibration.
rows = []
for name in ["blue", "red", "nir", "swir16"]:  # four representative bands
    # Find the band number in L8_BANDS that matches the band name
    b = next(k for k, v in L8_BANDS.items() if v == name)
    # Convert DN to radiance using the calibration coefficients from the metadata
    rad = rs.optical.radiance(
        dn[name],
        mtl[f"RADIANCE_MULT_BAND_{b}"],
        mtl[f"RADIANCE_ADD_BAND_{b}"]
    )
    # Gather median values for DN, radiance, and TOA reflectance for this band
    rows.append({
        "band": name,
        "median DN": float(dn[name].median()),
        "median radiance": float(rad.median()),
        "median TOA reflectance": float(toa[name].median())
    })

# Display the results as a DataFrame (bands as index), rounding for clarity.
pd.DataFrame(rows).set_index("band").round(3)
M_rho A_rho M_L A_L
coastal 0.00002 -0.1 0.012503 -62.51346
blue 0.00002 -0.1 0.012803 -64.01454
green 0.00002 -0.1 0.011798 -58.98885
red 0.00002 -0.1 0.009949 -49.74272
nir 0.00002 -0.1 0.006088 -30.44007
swir16 0.00002 -0.1 0.001514 -7.57017
swir22 0.00002 -0.1 0.000510 -2.55155
cirrus 0.00002 -0.1 0.002379 -11.89667
median DN median radiance median TOA reflectance
band
blue 8247.0 41.572 0.096
red 7392.0 23.797 0.071
nir 14972.0 60.709 0.296
swir16 11585.0 9.970 0.195

Thermal band: brightness temperature

Band 10 (10.9 µm) records emitted radiance. Inverting Planck’s law with the band constants \(K_1\) and \(K_2\) from the MTL file gives the brightness temperature: the temperature a blackbody would need to produce the measured radiance. Correcting for emissivity (estimated from NDVI, rs.optical.emissivity_ndvi) turns it into land surface temperature (rs.optical.landsat_lst, optical notebooks 07_02).

Code
# Calculate at-sensor radiance for thermal Band 10 using the calibration coefficients from the MTL metadata
rad10 = rs.optical.radiance(
    dn["tir1"],                     # Digital numbers (DN) for thermal infrared band (Band 10)
    mtl["RADIANCE_MULT_BAND_10"],   # Radiance multiplicative scaling factor from metadata
    mtl["RADIANCE_ADD_BAND_10"]     # Radiance additive scaling factor from metadata
)

# Convert the radiance to brightness temperature (in Kelvin) using Planck's law and sensor-specific constants
bt = rs.optical.brightness_temperature(
    rad10,                          # at-sensor radiance for Band 10
    mtl["K1_CONSTANT_BAND_10"],     # K1 constant from metadata
    mtl["K2_CONSTANT_BAND_10"]      # K2 constant from metadata
)

# Convert brightness temperature from Kelvin to Celsius, and assign the coordinate reference system
bt_c = (bt - 273.15).rio.write_crs(dn.rio.crs)

# Display the K1 and K2 constants for reference
print(f"K1 = {mtl['K1_CONSTANT_BAND_10']}, K2 = {mtl['K2_CONSTANT_BAND_10']}")

# Set up a figure with two panels: map and histogram
fig, axes = plt.subplots(1, 2, figsize=(15, 5), gridspec_kw={"width_ratios": [1.3, 1]})

# Show the brightness temperature map on the left, colored by temperature
rs.viz.plot_raster(
    bt_c, ax=axes[0], cmap="inferno",
    title="Band 10 brightness temperature (°C), 2016-09-27"
)
axes[0].set_xticks([]); axes[0].set_yticks([])  # no ticks on the image panel

# Plot a histogram of brightness temperature for each land cover class on the right
lc = masks  # Dictionary mapping class names to boolean masks
for name, m in lc.items():  # each land-cover class and its mask
    v = bt_c.where(m).values.ravel()  # Extract temperature values where mask is True
    axes[1].hist(  # histogram of its brightness temperatures
        v[np.isfinite(v)], bins=60, alpha=0.6, density=True, label=name
    )
axes[1].set_xlabel("Brightness temperature (°C)")  # x label
axes[1].set_ylabel("density")  # y label
axes[1].legend(fontsize=8)  # legend

# Adjust layout and display the plots
plt.tight_layout(); plt.show()

# Summarize the results: For each land cover class, report the median brightness temperature (°C) and pixel count
pd.DataFrame({
    name: {
        "median BT (°C)": float(bt_c.where(m).median()),
        "pixels": int(m.sum())
    }
    for name, m in lc.items()
}).T.round(1)
K1 = 774.8853, K2 = 1321.0789

median BT (°C) pixels
Dense vegetation (NDVI > 0.6) 20.1 140996.0
Harvested / bare fields (NDVI < 0.3) 22.8 40302.0
Farm ponds (NDWI > 0) 19.6 129.0

On this late-September morning (scene time 15:51 UTC, about 11:50 local), harvested and bare fields were the warmest surfaces, with a median brightness temperature of 22.8 °C. Dense vegetation was 2.7 °C cooler (20.1 °C), because transpiring leaves spend energy evaporating water. The farm ponds (19.6 °C, 129 mixed pixels) were among the coolest. The map is blockier than the reflective bands because TIRS measures at 100 m and the product is resampled to 30 m.

Brightness temperature is not yet land surface temperature. It ignores emissivity, which here is below 1, and atmospheric absorption, so it usually underestimates the true surface temperature by a few degrees.

Level-2 surface reflectance

Most analysis today starts from Level-2 surface reflectance, which is already corrected for the atmosphere. These products are stored as scaled integers, and rs.optical.scale applies the right factors per sensor (for Landsat Collection 2: \(DN \times 2.75\times10^{-5} - 0.2\)). We read a 600 × 600 pixel window from the Landsat 9 Level-2 scene.

Code
# Define the directory and scene ID for the Landsat 9 Level-2 Surface Reflectance product.
L9_DIR = DATA / "LC09_L2SP_138043_20221216_20221223_02_T1"
L9_ID = "LC09_L2SP_138043_20221216_20221223_02_T1"  # the scene ID

# Define a window to select a 600x600 pixel subset from the full scene
win = dict(y=slice(2400, 3000), x=slice(2400, 3000))

# Read each required surface reflectance band file (bands 2, 3, 4, 5, 6) from disk,
# drop the redundant 'band' dimension, select the chosen window,
# and load all pixel values into memory.
l2 = xr.Dataset({
    f"SR_B{b}": rs.read(L9_DIR / f"{L9_ID}_SR_B{b}.TIF", masked=False, chunks={})
                  .squeeze("band", drop=True)
                  .isel(**win)
                  .load()
    for b in (2, 3, 4, 5, 6)
})

# Convert the raw digital numbers (DNs) in l2 to surface reflectance values 
# using the correct scaling for Landsat Collection 2.
sr = rs.optical.scale(l2, sensor="landsat")

# Print which sensor was recognized and used for scaling (metadata compatibility).
print("sensor recognised as:", sr.attrs.get("pyrsense:sensor"))

# Build and display a DataFrame summarizing, for each band:
# - the median raw DN value (from the original data)
# - the median surface reflectance (after scaling)
# and round the numbers to four decimal places for clarity.
pd.DataFrame(
    {
        "DN (median)": {v: float(l2[v].median()) for v in l2.data_vars},
        "surface reflectance (median)": {v: float(sr[v].median()) for v in sr.data_vars}
    }
).round(4)
         
sensor recognised as: landsat
DN (median) surface reflectance (median)
SR_B2 9869.0 0.0714
SR_B3 11314.0 0.1111
SR_B4 11131.0 0.1061
SR_B5 15213.0 0.2184
SR_B6 13821.0 0.1801
Code
# Calculate the NDVI (Normalized Difference Vegetation Index) from the surface reflectance data.
ndvi_l9 = rs.optical.index(sr, "NDVI")

# Set up a figure with two side-by-side subplots, with a specific size.
fig, axes = plt.subplots(1, 2, figsize=(14, 5.6))

# Plot a false color image (NIR, red, green) of the Level-2 Landsat 9 scene, showing healthy vegetation in red hues.
rs.viz.plot_rgb(
    sr,
    ("SR_B5", "SR_B4", "SR_B3"),
    ax=axes[0],
    title="Landsat 9 L2 false colour (NIR, red, green)"
)

# Plot the NDVI raster in the second subplot, using a green-yellow-red color map.
# The NDVI layer is assigned the same coordinate reference system as the original data.
rs.viz.plot_raster(
    ndvi_l9.rio.write_crs(l2.rio.crs),
    ax=axes[1],
    cmap="RdYlGn",
    title="NDVI from surface reflectance"
)

# Remove axis tick marks for a cleaner look on both subplots.
for a in axes:
    a.set_xticks([])  # no x ticks
    a.set_yticks([])  # no y ticks

# Adjust the layout to avoid overlap and display the figure.
plt.tight_layout()
plt.show()  # draw

# Print descriptive statistics for NDVI within the image window:
# median value and the range from 5th to 95th percentile (to summarize variability).
print(
    f"NDVI median {float(ndvi_l9.median()):.2f}, 5th–95th percentile "
    f"{float(ndvi_l9.quantile(0.05)):.2f} to {float(ndvi_l9.quantile(0.95)):.2f}"
)
 

NDVI median 0.29, 5th–95th percentile 0.11 to 0.63

rs.optical.scale recognised the Collection 2 band names and converted, for example, a median DN of 9,869 in the blue band to a surface reflectance of 0.071. No sun-angle or metadata file is needed, because the atmospheric correction was done by USGS.

The 18 × 18 km window in northwestern Bangladesh was imaged in December, in the dry season. A meandering river runs from the upper left to the lower right. Green vegetation along its floodplain and in the west has NDVI 0.5 to 0.65, while the dry fallow and harvested land to the east and south has NDVI 0.1 to 0.3 (median 0.29 over the window).

Summary and exercises

Key ideas

  • Remote sensing turns measured radiance into physical quantities and then into information, through a chain of source, atmosphere, target, sensor and processing.
  • Optical sensors (0.4 to 3 µm) measure reflected sunlight; thermal sensors (8 to 14 µm) measure emitted energy; radar and lidar supply their own illumination.
  • The atmosphere scatters (Rayleigh ∝ λ⁻⁴) and absorbs; sensors look through its windows, and atmospheric correction removes path radiance.
  • Spectral signatures (water, vegetation, built surfaces) are the basis of every spectral index and classifier.
  • Spatial, spectral, temporal and radiometric resolution trade off against each other.
  • Analysis-ready data are Level-2 surface reflectance, surface temperature or calibrated backscatter in physical units.
  • geolattice.rsense covers the whole workflow, from data access to deep learning, on CPU or GPU.

What the data showed

  • Sentinel-2 ground truth reproduced the textbook signatures, including the red edge (grass: 0.105 → 0.275 → 0.383 from 705 to 842 nm).
  • The Landsat 8 metadata alone recovered the solar spectrum, within 2 to 18% of a 5,778 K blackbody.
  • Path radiance in the visible bands fell as λ^−2.75, between Rayleigh and aerosol scattering. DOS1 removed most of it, but should not be trusted in bands without dark targets.
  • Bare fields were 2.7 °C warmer than transpiring vegetation in brightness temperature.
  • Red-edge and SWIR bands separated trees from grass four to six times better than the visible bands.

Exercises

  1. Use planck() to find the peak wavelength of a 600 K lava flow. Which Landsat band would detect it best?
  2. Add the Sentinel-2 signature of a sixth material by digitising a polygon (for example a sports field or a parking lot) and passing it to rs.classify.extract_samples.
  3. Compute "SAVI", "MNDWI" and "NBR" for the Landsat 8 scene with rs.optical.index and compare their maps with NDVI and NDWI.
  4. Repeat the Rayleigh scattering in the darkest pixels section on band 9 (cirrus, 1.37 µm). What do its brightest pixels show, and why?
  5. Compute the brightness temperature from band 11 and compare it with band 10 over the vegetation and the harvested fields. The difference is the basis of split-window LST algorithms.
  6. Use the PyGIS Explorer app or rs.access.stac_search to find a recent cloud-free Sentinel-2 L2A scene of your area, and plot its spectral signatures.

References

  • Chavez, P.S. (1996). Image-based atmospheric corrections, revisited and improved. Photogrammetric Engineering & Remote Sensing 62(9), 1025 to 1036.
  • Jensen, J.R. (2007). Remote Sensing of the Environment: An Earth Resource Perspective, 2nd ed. Pearson.
  • Lillesand, T., Kiefer, R.W. & Chipman, J. (2015). Remote Sensing and Image Interpretation, 7th ed. Wiley.
  • Schott, J.R. (2007). Remote Sensing: The Image Chain Approach, 2nd ed. Oxford University Press.
  • U.S. Geological Survey (2019). Landsat 8 (L8) Data Users Handbook, version 5.0. LSDS-1574.
  • European Space Agency (2015). Sentinel-2 User Handbook. ESA Standard Document.

Next: Notebook 09_01_01 sets up the Python geospatial environment and introduces the CPU/GPU backend of geolattice.rsense.

Back to top