Raster, GeoTIFF and WebGL · Angular, React and OpenLayers

Region growing from a clicked pixel

Segment contiguous roofs, squares or fields of similar RGB colour from a clicked orthophoto pixel in OpenLayers using an image RasterSource.

GUGiK's orthophoto of Kraków's Old Town inside the Planty, with a small red region grown on the Main Square, the Threshold slider at 20 and a hint to click below.
A screenshot of the example. Orthophotomap © GUGiK.

What this example shows

Zoomed onto Kraków’s Old Town inside the Planty ring on GUGiK’s orthophotomap, clicking any roof, plaza or grass patch grows a contiguous opaque red mask outward across neighbouring pixels whose RGB channels stay within the Threshold slider’s tolerance (starting at 20).

When you need it

Semi-automatic feature extraction—picking out a water body, uniform agricultural parcel, parking lot or roof plane with a single seed click—gives digitisers an instant footprint preview or pixel-area estimate.

Switching RasterSource from single-pixel mode to whole-image mode gives worker algorithms random access across the entire 2D pixel grid for flood-fill / breadth-first region growing.

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.

region-growing.shared.ts
/** The national orthophoto as XYZ tiles (the WMTS GetTile request with the tile indices in its template). */
export const ORTHOPHOTO =
  'https://mapy.geoportal.gov.pl/wss/service/PZGIK/ORTO/WMTS/StandardResolution' +
  '?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=ORTOFOTOMAPA&STYLE=default&FORMAT=image/jpeg' +
  '&TILEMATRIXSET=EPSG:3857&TILEMATRIX=EPSG:3857:{z}&TILEROW={y}&TILECOL={x}';

export const ATTRIBUTIONS = 'Tiles © <a href="https://www.geoportal.gov.pl/" target="_blank">GUGiK</a>';

export interface RegionData {
  delta: number | string;
  pixel?: number[] | null;
}

/**
 * The functions the raster worker defines under these names before it runs the operation. The operation calls
 * them by these names as globals: a production build renames the functions of this module, and a name the
 * operation took from the module would not exist in the worker.
 */
export const WORKER_LIB = {
  /** The four neighbours of a pixel. */
  next4Edges: (edge: number[]): number[][] => {
    const x = edge[0];
    const y = edge[1];
    return [
      [x + 1, y],
      [x - 1, y],
      [x, y + 1],
      [x, y - 1],
    ];
  },
};

/** Defined in the raster worker from `WORKER_LIB`. */
declare const next4Edges: (typeof WORKER_LIB)['next4Edges'];

/**
 * Grows a region from the seed pixel over the neighbours whose colour differs from the seed's by less than the
 * threshold in each channel, and paints it red. It runs in a worker, so beyond its own code it uses only
 * `next4Edges` from `WORKER_LIB`.
 */
export function growRegion(inputs: ImageData[], data: RegionData): ImageData {
  const image = inputs[0];
  let seed = data.pixel;
  const delta = Number(data.delta);
  if (!seed) {
    return image;
  }

  seed = seed.map(Math.round);
  const width = image.width;
  const height = image.height;
  const inputData = image.data;
  const outputData = new Uint8ClampedArray(inputData);
  const seedIdx = (seed[1] * width + seed[0]) * 4;
  const seedR = inputData[seedIdx];
  const seedG = inputData[seedIdx + 1];
  const seedB = inputData[seedIdx + 2];
  let edge = [seed];
  while (edge.length) {
    const newedge: number[][] = [];
    for (let i = 0, ii = edge.length; i < ii; i++) {
      const next = next4Edges(edge[i]);
      for (let j = 0, jj = next.length; j < jj; j++) {
        const s = next[j][0];
        const t = next[j][1];
        if (s >= 0 && s < width && t >= 0 && t < height) {
          const ci = (t * width + s) * 4;
          const cr = inputData[ci];
          const cg = inputData[ci + 1];
          const cb = inputData[ci + 2];
          const ca = inputData[ci + 3];
          // A visited pixel has alpha zero.
          if (ca === 0) {
            continue;
          }
          if (Math.abs(seedR - cr) < delta && Math.abs(seedG - cg) < delta && Math.abs(seedB - cb) < delta) {
            outputData[ci] = 255;
            outputData[ci + 1] = 0;
            outputData[ci + 2] = 0;
            outputData[ci + 3] = 255;
            newedge.push([s, t]);
          }
          // Mark as visited.
          inputData[ci + 3] = 0;
        }
      }
    }
    edge = newedge;
  }
  return { data: outputData, width, height } as ImageData;
}
region-growing.ts
import { ChangeDetectionStrategy, Component, signal, viewChild } from '@angular/core';
import type { Coordinate } from 'ol/coordinate';
import type MapBrowserEvent from 'ol/MapBrowserEvent';
import type { RasterSourceEvent } from 'ol/source/Raster';
import {
  CoordinateComponent,
  DefaultControlComponent,
  DefaultInteractionComponent,
  LayerImageComponent,
  LayerTileComponent,
  MapComponent,
  SourceRasterComponent,
  SourceXYZComponent,
  ViewComponent,
} from 'cc-openlayers';
import { ATTRIBUTIONS, growRegion, ORTHOPHOTO, type RegionData, WORKER_LIB } from './region-growing.shared';

/** A region grown in red from the clicked pixel of the orthophoto, by a raster source, within a colour threshold. */
@Component({
  selector: 'app-region-growing',
  imports: [
    CoordinateComponent,
    DefaultControlComponent,
    DefaultInteractionComponent,
    LayerImageComponent,
    LayerTileComponent,
    MapComponent,
    SourceRasterComponent,
    SourceXYZComponent,
    ViewComponent,
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <aol-map height="480px" (olClick)="seed($event)">
      <aol-interaction-default />
      <aol-control-defaults />
      <aol-view [zoom]="15">
        <aol-coordinate [x]="19.9368" [y]="50.0614" srid="EPSG:4326" />
      </aol-view>
      <aol-layer-tile>
        <aol-source-xyz [url]="url" [attributions]="attributions" crossOrigin="anonymous" [maxZoom]="19" />
      </aol-layer-tile>
      <aol-layer-image [opacity]="0.7">
        <aol-source-raster
          operationType="image"
          [operation]="operation"
          [lib]="lib"
          (beforeOperations)="beforeOperations($event)"
        >
          <aol-source-xyz [url]="url" crossOrigin="anonymous" [maxZoom]="19" />
        </aol-source-raster>
      </aol-layer-image>
    </aol-map>
    <div class="example-controls">
      <label>
        Threshold
        <input
          type="range"
          min="1"
          max="50"
          [value]="threshold()"
          (input)="threshold.set(number($event)); raster().instance.changed()"
        />
        <output>{{ threshold() }}</output>
      </label>
      <p class="example-hint">Click a field, a roof or the river: the region of similar colour turns red.</p>
    </div>
  `,
})
export class RegionGrowing {
  readonly threshold = signal(20);
  protected readonly url = ORTHOPHOTO;
  protected readonly attributions = ATTRIBUTIONS;
  protected readonly operation = growRegion;
  protected readonly lib = WORKER_LIB;

  private readonly map = viewChild.required(MapComponent);
  protected readonly raster = viewChild.required(SourceRasterComponent);
  private readonly seedCoordinate = signal<Coordinate | undefined>(undefined);

  protected seed(event: MapBrowserEvent): void {
    this.seedCoordinate.set(event.coordinate);
    this.raster().instance.changed();
  }

  /** Hands the threshold and the clicked pixel to the operation. */
  protected beforeOperations(event: Pick<RasterSourceEvent, 'data'>): void {
    const data: RegionData = event.data;
    data.delta = this.threshold();
    const coordinate = this.seedCoordinate();
    if (coordinate) data.pixel = this.map().instance.getPixelFromCoordinate(coordinate);
  }

  protected number(event: Event): number {
    return (event.target as HTMLInputElement).valueAsNumber;
  }
}

Architecture and OpenLayers mechanics

Setting operationType="image" on aol-source-raster passes complete ImageData buffers to the worker function growRegion instead of isolated 1 × 1 pixel arrays. Clicking the map invokes (olClick)="seed($event)", storing the map coordinate and calling changed() on the raster source.

In (beforeOperations), the stored map coordinate converts to current screen pixels via getPixelFromCoordinate alongside the RGB threshold, allowing growRegion to flood-fill outward from the seed pixel wherever |R - R0|, |G - G0| and |B - B0| all remain below threshold.

How it works

  • (olClick)="seed($event)" records the clicked map coordinate and triggers changed() on the raster source to re-run growRegion.
  • operationType="image" delivers the entire viewport ImageData buffer to the worker so growRegion can traverse neighbouring pixels.
  • Connected pixels whose R, G and B values each differ from the seed pixel by less than the threshold turn opaque red, while every other pixel keeps the underlying photograph.
  • (beforeOperations) converts the seed coordinate via getPixelFromCoordinate and passes both pixel position and threshold into event.data.

Pitfalls

  • Leaving operationType at its default pixel mode hands your worker only one pixel [R, G, B, A] at a time with zero neighbour access—always specify operationType="image" for flood-fill, morphology or spatial kernels.
  • Because region growing evaluates rendered viewport pixels at the active resolution, zooming in or panning outside the contiguous area changes which pixels connect to the seed.

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.