Raster, GeoTIFF and WebGL · Angular, React and OpenLayers

Convolution filters on an orthophoto

Apply 3x3 sharpening, blur, emboss and edge-detection convolution kernels to OpenLayers WMTS orthophotos in postrender using getImageData().

GUGiK's orthophoto of central Kraków, sharpened: the Old Town inside the Planty, the bends of the Vistula, the Błonia meadow and the stadiums beside it, with the Kernel select on sharpen below.
A screenshot of the example. Orthophotomap © GUGiK.

What this example shows

Over central Kraków—spanning the Old Town, Planty ring, Vistula bends and Błonia meadow—GUGiK’s national WMTS aerial orthophotomap opens sharpened via a 3 × 3 spatial convolution matrix, with a Kernel selector below switching live across seven classic image-processing filters including sharpen, blur, shadow, emboss and edge detection.

When you need it

Photo-interpreters inspecting roof ridgelines, pavement cracks, drainage ditches or crop rows benefit from instant on-screen sharpening or edge-enhancement filters without exporting imagery to desktop software.

Running a 3 × 3 convolution kernel in postrender processes whatever aerial tiles are currently painted on the layer canvas with zero server round-trips.

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.

image-filter.shared.ts
import { getTopLeft, getWidth } from 'ol/extent';
import { EXTENT } from 'ol/proj/epsg3857';

const size = getWidth(EXTENT) / 256;

/** The tile grid of the national orthophoto's Web Mercator matrix set (20 levels). */
export const ORTHOPHOTO_GRID = {
  origin: getTopLeft(EXTENT),
  resolutions: Array.from({ length: 20 }, (_, z) => size / 2 ** z),
  matrixIds: Array.from({ length: 20 }, (_, z) => `EPSG:3857:${z}`),
};

export const KERNELS: Record<string, number[]> = {
  none: [0, 0, 0, 0, 1, 0, 0, 0, 0],
  sharpen: [0, -1, 0, -1, 5, -1, 0, -1, 0],
  sharpenless: [0, -1, 0, -1, 10, -1, 0, -1, 0],
  blur: [1, 1, 1, 1, 1, 1, 1, 1, 1],
  shadow: [1, 2, 1, 0, 1, 0, -1, -2, -1],
  emboss: [-2, 1, 0, -1, 1, 1, 0, 1, 2],
  edge: [0, 1, 0, 1, -4, 1, 0, 1, 0],
};

export const OPTIONS = [
  { value: 'none', label: 'none' },
  { value: 'sharpen', label: 'sharpen' },
  { value: 'sharpenless', label: 'sharpen less' },
  { value: 'blur', label: 'blur' },
  { value: 'shadow', label: 'shadow' },
  { value: 'emboss', label: 'emboss' },
  { value: 'edge', label: 'edge detect' },
];

/** A kernel divided by its sum, so the image keeps its brightness; a kernel summing to 0 or less is left as it is and the result is made opaque. */
export function normalize(kernel: number[]): { weights: number[]; normalized: boolean } {
  const sum = kernel.reduce((total, weight) => total + weight, 0);
  const normalized = sum > 0;
  return { weights: kernel.map((weight) => weight / (normalized ? sum : 1)), normalized };
}

/** Applies a convolution kernel to the canvas: works for any size, but gets slow above 3 x 3. */
export function convolve(context: CanvasRenderingContext2D, kernel: { weights: number[]; normalized: boolean }): void {
  const { width, height } = context.canvas;
  const { weights, normalized } = kernel;
  const kernelSize = Math.sqrt(weights.length);
  const half = Math.floor(kernelSize / 2);
  const input = context.getImageData(0, 0, width, height).data;
  const output = context.createImageData(width, height);
  const result = output.data;

  for (let pixelY = 0; pixelY < height; ++pixelY) {
    for (let pixelX = 0; pixelX < width; ++pixelX) {
      let r = 0;
      let g = 0;
      let b = 0;
      let a = 0;
      for (let kernelY = 0; kernelY < kernelSize; ++kernelY) {
        for (let kernelX = 0; kernelX < kernelSize; ++kernelX) {
          const weight = weights[kernelY * kernelSize + kernelX];
          const neighborY = Math.min(height - 1, Math.max(0, pixelY + kernelY - half));
          const neighborX = Math.min(width - 1, Math.max(0, pixelX + kernelX - half));
          const inputIndex = (neighborY * width + neighborX) * 4;
          r += input[inputIndex] * weight;
          g += input[inputIndex + 1] * weight;
          b += input[inputIndex + 2] * weight;
          a += input[inputIndex + 3] * weight;
        }
      }
      const outputIndex = (pixelY * width + pixelX) * 4;
      result[outputIndex] = r;
      result[outputIndex + 1] = g;
      result[outputIndex + 2] = b;
      result[outputIndex + 3] = normalized ? a : 255;
    }
  }
  context.putImageData(output, 0, 0);
}
image-filter.ts
import { ChangeDetectionStrategy, Component, signal, viewChild } from '@angular/core';
import {
  CoordinateComponent,
  DefaultControlComponent,
  DefaultInteractionComponent,
  LayerTileComponent,
  MapComponent,
  SourceTileWMTSComponent,
  TileGridWMTSComponent,
  ViewComponent,
} from 'cc-openlayers';
import type RenderEvent from 'ol/render/Event';
import { convolve, KERNELS, normalize, OPTIONS, ORTHOPHOTO_GRID } from './image-filter.shared';

/** The national orthophoto filtered after each render with a convolution kernel chosen from a list. */
@Component({
  selector: 'app-image-filter',
  imports: [
    CoordinateComponent,
    DefaultControlComponent,
    DefaultInteractionComponent,
    LayerTileComponent,
    MapComponent,
    SourceTileWMTSComponent,
    TileGridWMTSComponent,
    ViewComponent,
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <aol-map height="480px">
      <aol-interaction-default />
      <aol-control-defaults />
      <aol-view [zoom]="13"><aol-coordinate [x]="19.9368" [y]="50.0614" srid="EPSG:4326" /></aol-view>
      <aol-layer-tile [postrender]="filter">
        <aol-source-tilewmts
          attributions='Tiles © <a href="https://www.geoportal.gov.pl/" target="_blank">GUGiK</a>'
          url="https://mapy.geoportal.gov.pl/wss/service/PZGIK/ORTO/WMTS/StandardResolution"
          layer="ORTOFOTOMAPA"
          matrixSet="EPSG:3857"
          format="image/jpeg"
          projection="EPSG:3857"
          crossOrigin="anonymous"
          [style]="'default'"
          [wrapX]="true"
        >
          <aol-tilegrid-wmts [origin]="origin" [resolutions]="resolutions" [matrixIds]="matrixIds" />
        </aol-source-tilewmts>
      </aol-layer-tile>
    </aol-map>
    <div class="example-controls">
      <label>
        Kernel
        <select (change)="select($event)">
          @for (option of options; track option.value) {
            <option [value]="option.value" [selected]="option.value === kernel()">{{ option.label }}</option>
          }
        </select>
      </label>
    </div>
  `,
})
export class ImageFilter {
  readonly kernel = signal('sharpen');
  protected readonly options = OPTIONS;
  protected readonly origin = ORTHOPHOTO_GRID.origin;
  protected readonly resolutions = ORTHOPHOTO_GRID.resolutions;
  protected readonly matrixIds = ORTHOPHOTO_GRID.matrixIds;
  /** Applies the selected kernel on the layer's canvas after it renders. */
  protected readonly filter = (event: RenderEvent): void => {
    convolve(event.context as CanvasRenderingContext2D, normalize(KERNELS[this.kernel()]));
  };
  private readonly map = viewChild.required(MapComponent);

  protected select(event: Event): void {
    this.kernel.set((event.target as HTMLSelectElement).value);
    this.map().instance.render();
  }
}

Architecture and OpenLayers mechanics

GUGiK’s WMTS orthophoto loads with crossOrigin="anonymous" so its backing 2D canvas remains readable. After each frame paints, [postrender]="filter" invokes convolve with the 9-element matrix chosen by the kernel signal from KERNELS (starting on sharpen, normalized via normalize whenever its weights sum above zero).

convolve reads full canvas pixels via getImageData, computes the weighted 3 × 3 neighbourhood sum per RGB channel, and writes the filtered buffer back with putImageData.

How it works

  • [postrender]="filter" runs convolve on the tile layer’s canvas after every render using the matrix selected by kernel.
  • convolve reads rendered pixels via getImageData, multiplies 3 × 3 pixel neighbourhoods by kernel weights, and writes back via putImageData.
  • normalize divides weights by their positive sum across the seven presets in KERNELS (defaulting initially to sharpen).
  • crossOrigin="anonymous" on the GUGiK WMTS source keeps the canvas untainted for pixel access.

Pitfalls

  • Omitting crossOrigin="anonymous" (or using a non-CORS server) taints the canvas and causes getImageData to throw a SecurityError.
  • Main-thread postrender convolution iterates over every physical backing-canvas pixel on every pan frame—on 4K/Retina screens, consider WebGL fragment shaders (webgl-shaded-relief style neighbour sampling) when 60 fps drag performance is critical.
  • Zero-sum kernels such as edge detect cannot divide by their weight sum and must force output alpha to opaque (255) so filtered edges remain visible.

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.