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.

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.tsimport { 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;
}
} The React version uses the library's React adapter, cc-openlayers/react: each component creates the OpenLayers object it names when it mounts, updates it from its props and disposes of it when it unmounts.
region-growing.react.tsximport { useRef, useState, type ChangeEvent } from 'react';
import type { Coordinate as OLCoordinate } from 'ol/coordinate.js';
import type MapBrowserEvent from 'ol/MapBrowserEvent.js';
import type OLMap from 'ol/Map.js';
import type Raster from 'ol/source/Raster.js';
import type { Operation, RasterSourceEvent } from 'ol/source/Raster.js';
import {
Coordinate,
DefaultControls,
DefaultInteractions,
ImageLayer,
Map,
RasterSource,
TileLayer,
View,
XYZSource,
} from 'cc-openlayers/react';
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. */
export function RegionGrowing() {
const [threshold, setThreshold] = useState(20);
const [seedCoordinate, setSeedCoordinate] = useState<OLCoordinate | undefined>(undefined);
const map = useRef<OLMap>(null);
const raster = useRef<Raster>(null);
const seed = (event: MapBrowserEvent): void => {
setSeedCoordinate(event.coordinate);
raster.current?.changed();
};
/** Hands the threshold and the clicked pixel to the operation. */
const beforeOperations = (event: Pick<RasterSourceEvent, 'data'>): void => {
const data: RegionData = event.data;
data.delta = threshold;
if (seedCoordinate) data.pixel = map.current?.getPixelFromCoordinate(seedCoordinate);
};
return (
<>
<Map ref={map} height="480px" onClick={seed}>
<DefaultInteractions />
<DefaultControls />
<View zoom={15}>
<Coordinate x={19.9368} y={50.0614} srid="EPSG:4326" />
</View>
<TileLayer>
<XYZSource url={ORTHOPHOTO} attributions={ATTRIBUTIONS} crossOrigin="anonymous" maxZoom={19} />
</TileLayer>
<ImageLayer opacity={0.7}>
<RasterSource
ref={raster}
operationType="image"
operation={growRegion as Operation}
lib={WORKER_LIB}
onBeforeOperations={beforeOperations}
>
<XYZSource url={ORTHOPHOTO} crossOrigin="anonymous" maxZoom={19} />
</RasterSource>
</ImageLayer>
</Map>
<div className="example-controls">
<label>
Threshold
<input
type="range"
min="1"
max="50"
value={threshold}
onChange={(event: ChangeEvent<HTMLInputElement>) => {
setThreshold(event.target.valueAsNumber);
raster.current?.changed();
}}
/>
<output>{threshold}</output>
</label>
<p className="example-hint">Click a field, a roof or the river: the region of similar colour turns red.</p>
</div>
</>
);
}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;
}How the React version works
A region grown in red from the clicked pixel of the orthophoto by a raster source in a worker, within a colour threshold set with a slider.
What both versions share
OpenLayers renders the map and handles the interactions; the cc-openlayers/core layer gives both adapters the same view binding (MapViewBinding) and the same conversion of coordinates from EPSG:4326 to the map's projection. Both versions import the orthophoto URL, the worker library and growRegion from the example's .shared.ts file, so the logic exists once. The raster source turns the operation into source text for its worker.
From Angular to React
| Angular | React |
|---|---|
<aol-layer-image> with <aol-source-raster [operation] [lib] (beforeOperations)> | <ImageLayer> with <RasterSource operation lib onBeforeOperations> |
(olClick) with viewChild of the map | onClick on Map with useRef<OLMap> |
viewChild of the raster source and changed() after a control | ref on RasterSource (useRef) and changed() in the handler |
signals of the threshold and the seed | useState |
Who creates, updates and disposes
Map creates the ol/Map in useLayoutEffect and disposes of it on unmount; each layer, source and interaction component adds its object to the parent it gets from context and removes it in its effect's cleanup, as ngOnDestroy does in Angular.
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 triggerschanged()on the raster source to re-rungrowRegion.operationType="image"delivers the entire viewportImageDatabuffer to the worker sogrowRegioncan 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 viagetPixelFromCoordinateand passes both pixel position and threshold intoevent.data.
Pitfalls
- Leaving
operationTypeat its default pixel mode hands your worker only one pixel [R, G, B, A] at a time with zero neighbour access—always specifyoperationType="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.
Related examples
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.