Raster, GeoTIFF and WebGL · Angular, React and OpenLayers

NDVI computed on the GPU

Compute Sentinel-2 NDVI on the GPU in an OpenLayers WebGL style from red and NIR COGs and inspect live pixel NDVI values via layer.getData().

The scene east of Kraków in shades of green by NDVI, the Niepołomice Forest darkest, the city and bare fields pale, and NDVI 0.88 for the pointer in the middle below the map.
A screenshot of the example. Contains modified Copernicus Sentinel data 2024.

What this example shows

Across Kraków and the dense Niepołomice Forest to the east, a two-band Sentinel-2 scene renders directly as a 20-stop Normalized Difference Vegetation Index (NDVI) map—colouring water, roofs and bare soil pale grey/beige and thriving forest canopies deep green.

Moving the pointer or clicking anywhere on the map reads the underlying pixel bands and prints the live two-decimal NDVI value (or an en dash – before interaction) inside the <output> readout below.

When you need it

Precision-agriculture platforms, urban green-canopy audits and drought monitors compute spectral band ratios (NDVI, NDWI, NBR) directly from single-band COGs stored on cloud object storage.

Evaluating band math on the GPU renders full-viewport vegetation maps at 60 fps while layer.getData(pixel) still gives analysts exact quantitative pixel values on hover or click.

The code

The example uses cc-openlayers, my Angular component library for OpenLayers: each aol-… element creates the OpenLayers object it names, updates it from its inputs and disposes of it with the component.

cog-math.ts
import { ChangeDetectionStrategy, Component, computed, signal, viewChild } from '@angular/core';
import { DefaultControlComponent, DefaultInteractionComponent, MapComponent, ViewComponent } from 'cc-openlayers';
import { LayerWebGLTileComponent, SourceGeoTIFFComponent } from 'cc-openlayers/webgl';
import type { MapBrowserEvent } from 'ol';
import type { ViewOptions } from 'ol/View';
import type { Style } from 'ol/layer/WebGLTile';
import type { SourceInfo } from 'ol/source/GeoTIFF';

const scene =
  'https://sentinel-cogs.s3.us-west-2.amazonaws.com/sentinel-s2-l2a-cogs/34/U/DA/2024/8/S2B_34UDA_20240814_0_L2A';

/** NDVI values from -0.2 to 0.65 and the colour of each, from grey through yellow to dark green. */
const ramp: [number, [number, number, number]][] = [
  [-0.2, [191, 191, 191]],
  [-0.1, [219, 219, 219]],
  [0, [255, 255, 224]],
  [0.025, [255, 250, 204]],
  [0.05, [237, 232, 181]],
  [0.075, [222, 217, 156]],
  [0.1, [204, 199, 130]],
  [0.125, [189, 184, 107]],
  [0.15, [176, 194, 97]],
  [0.175, [163, 204, 89]],
  [0.2, [145, 191, 82]],
  [0.25, [128, 179, 71]],
  [0.3, [112, 163, 64]],
  [0.35, [97, 150, 54]],
  [0.4, [79, 138, 46]],
  [0.45, [64, 125, 36]],
  [0.5, [48, 110, 28]],
  [0.55, [33, 97, 18]],
  [0.6, [15, 84, 10]],
  [0.65, [0, 69, 0]],
];

/** Two Sentinel-2 bands of a scene over Kraków (red and near infrared) turned into NDVI colours; the pixel under the pointer is read back. */
@Component({
  selector: 'app-cog-math',
  imports: [
    DefaultControlComponent,
    DefaultInteractionComponent,
    LayerWebGLTileComponent,
    MapComponent,
    SourceGeoTIFFComponent,
    ViewComponent,
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <aol-map height="480px" (pointerMove)="showNdvi($event)" (singleClick)="showNdvi($event)">
      <aol-interaction-default />
      <aol-control-defaults />
      @if (view(); as options) {
        <aol-view
          [projection]="options.projection"
          [resolutions]="options.resolutions"
          [extent]="options.extent"
          [center]="options.center"
          [zoom]="options.zoom"
        />
      }
      <aol-layer-webgltile [style]="style">
        <aol-source-geotiff
          [sources]="sources"
          attributions="Contains modified Copernicus Sentinel data 2024"
          (viewReady)="view.set($event)"
        />
      </aol-layer-webgltile>
    </aol-map>
    <div class="example-controls">
      <span>
        NDVI <output>{{ ndvi() }}</output>
      </span>
    </div>
  `,
})
export class CogMath {
  readonly view = signal<ViewOptions | undefined>(undefined);
  protected readonly layer = viewChild.required(LayerWebGLTileComponent);
  protected readonly value = signal<string | undefined>(undefined);
  protected readonly ndvi = computed(() => this.value() ?? '–');

  /** Red is band 1 and near infrared band 2 of the style expression. */
  protected readonly sources: SourceInfo[] = [
    { url: `${scene}/B04.tif`, max: 10000 },
    { url: `${scene}/B08.tif`, max: 10000 },
  ];

  protected readonly style: Style = {
    color: [
      'interpolate',
      ['linear'],
      ['/', ['-', ['band', 2], ['band', 1]], ['+', ['band', 2], ['band', 1]]],
      ...ramp.flat(),
    ],
  };

  /**
   * Calculates the NDVI of the pixel under the pointer from its red and near-infrared values in the data tile. The
   * source scaled both bands alike, from 0–10000 to 0–255, so the ratio holds up to the rounding to whole bytes.
   */
  protected showNdvi(event: MapBrowserEvent): void {
    const data = this.layer().instance.getData(event.pixel);
    if (!data || data instanceof DataView) return;
    const [red, nir] = data;
    this.value.set(nir + red === 0 ? undefined : ((nir - red) / (nir + red)).toFixed(2));
  }
}

Architecture and OpenLayers mechanics

sources pairs B04.tif (red, band 1) and B08.tif (near-infrared, band 2), each configured with max: 10000 under default byte normalization (0..10000 scaled linearly to 0..255). On aol-layer-webgltile, [style] linearly interpolates ['/', ['-', ['band', 2], ['band', 1]], ['+', ['band', 2], ['band', 1]]] across 20 colour stops (-0.2 to 0.65).

On (pointerMove)="showNdvi($event)" and (singleClick)="showNdvi($event)", showNdvi queries this.layer().instance.getData(event.pixel) and formats ((nir - red) / (nir + red)).toFixed(2) when nir + red !== 0.

How it works

  • B04.tif (red) and B08.tif (near infrared) load as bands 1 and 2 with max: 10000 and native UTM view options from (viewReady).
  • The WebGL style interpolates ['/', ['-', ['band', 2], ['band', 1]], ['+', ['band', 2], ['band', 1]]] across 20 stops from -0.2 (grey) to 0.65 (dark green).
  • showNdvi reads [red, nir] via getData(event.pixel) on pointer move and single click, formatting NDVI to two decimals with toFixed(2).

Pitfalls

  • getData(event.pixel) returns the scaled byte values (0..255) stored in the rendered tile texture rather than raw 0..10000 integers—the (nir - red) / (nir + red) formula stays mathematically valid (up to 8-bit rounding) strictly because both bands share identical min: 0 and max: 10000 scaling.
  • Guard against nir + red === 0 (outer nodata pixels) and DataView return types before dividing so the readout falls back cleanly to – instead of NaN.

The same feature in the OpenLayers examples .

Background: state and lifecycle of maps in Angular with OpenLayers, which the components of cc-openlayers take care of.