Skip to content

Distance maps

The distance map of a binary image gives each object pixel its distance to the nearest background pixel, and 0 on the background. distance.distance_map(image, kind) computes seven kinds of distance. The image is surrounded by an infinite background: the pixels on the border of the array are at distance 1 from the outside.

kind Dimension Distance
"squared_euclidean" (default) 2D, 3D straight-line distance, squared so that the values stay integers: \(dx^2 + dy^2\) (+ \(dz^2\))
"chamfer" 2D 5 for a step to a side neighbour, 7 for a diagonal step: about 5 times the Euclidean distance
"d4" 2D steps between side neighbours: \(\lvert dx\rvert + \lvert dy\rvert\)
"d8" 2D diagonal steps allowed: \(\max(\lvert dx\rvert, \lvert dy\rvert)\)
"d6" 3D steps between face neighbours: \(\lvert dx\rvert + \lvert dy\rvert + \lvert dz\rvert\)
"d18" 3D steps along a face or an edge
"d26" 3D steps along a face, an edge or a corner: \(\max(\lvert dx\rvert, \lvert dy\rvert, \lvert dz\rvert)\)

The result is a new int32 array. The squared Euclidean distance is computed with the algorithm of Meijster et al. (2000); the other distances are shortest paths with the neighbours and weights of Pink's ldist and lchamfrein. The squared Euclidean distance is also the default priority of the sequential skeletons.

The code below is taken from docs/examples/scripts/distance_maps.py, which makes the figure. The whole script is at the end of the page. The checks against SciPy need SciPy.

In 2D

# A disk with a square notch, in a 2D image.
r, c = np.mgrid[:61, :61]
shape = (r - 30) ** 2 + (c - 30) ** 2 <= 26**2
shape[24:37, 40:] = False

maps2d = {kind: distance.distance_map(shape, kind)
          for kind in ("squared_euclidean", "chamfer", "d4", "d8")}
for kind, values in maps2d.items():
    print(f"2D {kind:17s} dtype {values.dtype}, maximum {values.max()}")
2D squared_euclidean dtype int32, maximum 324
2D chamfer           dtype int32, maximum 90
2D d4                dtype int32, maximum 18
2D d8                dtype int32, maximum 16

The largest squared Euclidean distance is 324, a distance of 18 pixels.

Comparison with SciPy

scipy.ndimage measures the distance to the nearest background pixel inside the array only. Pad the image with one pixel of background before comparing, so that the outside counts as background as in digitopo.

# The outside of the array is background: pad before calling SciPy.
padded = np.pad(shape, 1)
inner = (slice(1, -1), slice(1, -1))
edt = ndi.distance_transform_edt(padded)[inner]
taxicab = ndi.distance_transform_cdt(padded, metric="taxicab")[inner]
chessboard = ndi.distance_transform_cdt(padded, metric="chessboard")[inner]
print("squared_euclidean == edt**2:", bool((maps2d["squared_euclidean"] == np.round(edt**2)).all()))
print("d4 == taxicab:", bool((maps2d["d4"] == taxicab).all()))
print("d8 == chessboard:", bool((maps2d["d8"] == chessboard).all()))
squared_euclidean == edt**2: True
d4 == taxicab: True
d8 == chessboard: True

In 3D

# A ball with a cylindrical tunnel, in a 3D image (depth, rows, columns).
z, y, x = np.mgrid[:41, :41, :41]
ball = (z - 20) ** 2 + (y - 20) ** 2 + (x - 20) ** 2 <= 18**2
ball &= (y - 20) ** 2 + (x - 20) ** 2 > 5**2
maps3d = {kind: distance.distance_map(ball, kind)
          for kind in ("squared_euclidean", "d6", "d18", "d26")}
for kind, values in maps3d.items():
    print(f"3D {kind:17s} dtype {values.dtype}, maximum {values.max()}")
padded3d = np.pad(ball, 1)
inner3d = (slice(1, -1),) * 3
print("d6 == taxicab:", bool((maps3d["d6"] == ndi.distance_transform_cdt(
    padded3d, metric="taxicab")[inner3d]).all()))
print("d26 == chessboard:", bool((maps3d["d26"] == ndi.distance_transform_cdt(
    padded3d, metric="chessboard")[inner3d]).all()))
print("squared_euclidean == edt**2:", bool((maps3d["squared_euclidean"] == np.round(
    ndi.distance_transform_edt(padded3d)[inner3d] ** 2)).all()))
3D squared_euclidean dtype int32, maximum 45
3D d6                dtype int32, maximum 9
3D d18               dtype int32, maximum 6
3D d26               dtype int32, maximum 6
d6 == taxicab: True
d26 == chessboard: True
squared_euclidean == edt**2: True

Distance maps of the seven kinds: four of a 2D shape, four of a slice of a 3D ball with a tunnel

In the figure, each map has its own colour scale, from white (the background) to dark blue (the largest value of that map). The lines of equal distance are close to circles for the squared Euclidean distance, and polygons for the path distances, which follow the grid.

Overflow

A squared Euclidean distance of \(2^{31}\) or more does not fit in int32: distance_map then raises DigitopoError. This happens only for images of tens of thousands of pixels per side.

The whole script
# SPDX-License-Identifier: CECILL-2.1
# Figures of docs/examples/distance-maps.md. This script is the source of truth:
# the page includes parts of it with pymdownx.snippets. Run it from the
# repository root (it needs SciPy):
#     python docs/examples/scripts/distance_maps.py
from pathlib import Path

import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
from digitopo import distance
from scipy import ndimage as ndi

FIGURES = Path(__file__).resolve().parents[2] / "figures"
TEXT = "#222222"

# A disk with a square notch, in a 2D image.
r, c = np.mgrid[:61, :61]
shape = (r - 30) ** 2 + (c - 30) ** 2 <= 26**2
shape[24:37, 40:] = False

maps2d = {kind: distance.distance_map(shape, kind)
          for kind in ("squared_euclidean", "chamfer", "d4", "d8")}
for kind, values in maps2d.items():
    print(f"2D {kind:17s} dtype {values.dtype}, maximum {values.max()}")

# The outside of the array is background: pad before calling SciPy.
padded = np.pad(shape, 1)
inner = (slice(1, -1), slice(1, -1))
edt = ndi.distance_transform_edt(padded)[inner]
taxicab = ndi.distance_transform_cdt(padded, metric="taxicab")[inner]
chessboard = ndi.distance_transform_cdt(padded, metric="chessboard")[inner]
print("squared_euclidean == edt**2:", bool((maps2d["squared_euclidean"] == np.round(edt**2)).all()))
print("d4 == taxicab:", bool((maps2d["d4"] == taxicab).all()))
print("d8 == chessboard:", bool((maps2d["d8"] == chessboard).all()))

# A ball with a cylindrical tunnel, in a 3D image (depth, rows, columns).
z, y, x = np.mgrid[:41, :41, :41]
ball = (z - 20) ** 2 + (y - 20) ** 2 + (x - 20) ** 2 <= 18**2
ball &= (y - 20) ** 2 + (x - 20) ** 2 > 5**2
maps3d = {kind: distance.distance_map(ball, kind)
          for kind in ("squared_euclidean", "d6", "d18", "d26")}
for kind, values in maps3d.items():
    print(f"3D {kind:17s} dtype {values.dtype}, maximum {values.max()}")
padded3d = np.pad(ball, 1)
inner3d = (slice(1, -1),) * 3
print("d6 == taxicab:", bool((maps3d["d6"] == ndi.distance_transform_cdt(
    padded3d, metric="taxicab")[inner3d]).all()))
print("d26 == chessboard:", bool((maps3d["d26"] == ndi.distance_transform_cdt(
    padded3d, metric="chessboard")[inner3d]).all()))
print("squared_euclidean == edt**2:", bool((maps3d["squared_euclidean"] == np.round(
    ndi.distance_transform_edt(padded3d)[inner3d] ** 2)).all()))

fig, axes = plt.subplots(2, 4, figsize=(8.8, 4.8), facecolor="white", edgecolor="#bbbbbb",
                         linewidth=1)
rows = ((maps2d, "2D", lambda a: a), (maps3d, "3D, z=20", lambda a: a[20]))
for row, (maps, label, view) in zip(axes, rows):
    for ax, (kind, values) in zip(row, maps.items()):
        image = view(values).astype(float)
        image[view(values) == 0] = np.nan          # background shown in white
        ax.imshow(image, cmap="Blues", interpolation="nearest")
        ax.set_title(f"{label}: {kind}", fontsize=9, color=TEXT)
        ax.set_xticks([])
        ax.set_yticks([])
        for spine in ax.spines.values():
            spine.set_color("#dddddd")
fig.tight_layout()
fig.savefig(FIGURES / "distance-maps.png", dpi=100)
plt.close(fig)

Reference

A. Meijster, J. B. T. M. Roerdink, W. H. Hesselink, "A general algorithm for computing distance transforms in linear time", in Mathematical Morphology and its Applications to Image and Signal Processing, Springer, 2000, pp. 331-340.