Skip to content

Distance transforms

Algorithm atlasMorphology

For every nonzero pixel, measure the distance to the nearest zero pixel.

Try it on your image ↓

VISUAL WALKTHROUGHMorphology
REFERENCE INPUTBinary foreground

Zero-valued pixels are the distance sources.

RESULTEuclidean distance field

Interior pixels are farther from the background and appear brighter. The isolated speck has distance one.

STEP 03 / 03

Optionally attach the identity of the nearest zero component or pixel.

Computed teaching example on a 24 × 16 image. Small kernels and simplified settings keep each change visible; use the image laboratory for native OpenCV.

Try it on an image

YOUR IMAGE · REAL OPENCV

Experiment at pixel level

Open full lab ↗

Distance from each white mask pixel to its nearest zero. Preview is normalized; native values are distances in pixels.

The engine loads on your first run. Your images stay in this browser.

Input448 × 320
OutputWaiting for a result

Scroll over either image to zoom at the pointer. Use the scrollbars to pan both views over the same relative area. Zoom is relative to the input; pixel coordinates belong to each image. Warps can change scene correspondence.

Pixel inspector RGBA · native values · matched scale · 9 × 9 output pixels
Hover to inspect. Click to pin a pixel.
Input
Select a pixel

Output
Select a pixel

Sample models and licenses

When to use it

Estimate object thickness, find interior centres, create feathered masks, or assign pixels to nearby boundaries.

How it works

  1. 01Treat zero pixels as distance sources.
  2. 02Propagate distance through the chosen metric.
  3. 03Optionally attach the identity of the nearest zero component or pixel.

D(p) = min over q with mask(q)=0 of distance(p,q)

What to tune

distanceType selects L1, L2 or chessboard distance; maskSize controls approximation; labelType controls label identity.

Where it breaks down

Approximate masks and precise Euclidean distance have different error bounds. The labelled variant has its own supported settings.

TypeScript API

Open an entry for its exact overloads, parameter descriptions, result ownership and pinned upstream source.

All of these calls execute on the CPU. Native objects need explicit disposal. See matrices and ownership and build compatibility.