Skip to content

Skeletons

This page computes homotopic skeletons of a 2D shape and of a 3D volume: sequential skeletons (ultimate and curvilinear), parallel skeletons (symmetric and asymmetric), the effect of priority and inhibit, and a 3D skeleton shown as maximum projections. The terms are defined on the concepts page.

The code below is taken from docs/examples/scripts/skeletons.py, which makes the figures. The whole script is at the end of the page.

The shape

A disk with a hole and two arms; the object is 8-connected.

# A disk with a hole, and two arms.
r, c = np.mgrid[:80, :120]
shape = ((r - 40) ** 2 + (c - 40) ** 2 <= 28**2) & ((r - 40) ** 2 + (c - 36) ** 2 > 9**2)
shape |= (np.abs(r - 40) <= 5) & (c >= 60) & (c <= 112)
shape |= (np.abs((r - 40) + (c - 70)) <= 6) & (c >= 60) & (c <= 95) & (r < 40)
print("shape:", int(shape.sum()), "pixels,", topology.topology(shape, 8))
shape: 2954 pixels, Topology(objects=1, holes=1, cavities=0, euler=0)

Sequential skeletons: ultimate and curvilinear

ultimate = skeleton.ultimate_skeleton(shape, 8)
curvilinear = skeleton.curvilinear_skeleton(shape, 8)
for name, result in (("ultimate", ultimate), ("curvilinear", curvilinear)):
    print(f"{name:11s}", int(result.sum()), "pixels,", topology.topology(result, 8))
ultimate    104 pixels, Topology(objects=1, holes=1, cavities=0, euler=0)
curvilinear 169 pixels, Topology(objects=1, holes=1, cavities=0, euler=0)

The shape, its ultimate skeleton (a closed curve) and its curvilinear skeleton (the closed curve and the two arms)

Both skeletons have the topology of the shape: one object, one hole. The ultimate skeleton removes every simple point it can, so the arms disappear and only the closed curve around the hole remains. The curvilinear skeleton keeps the points where the object is locally a curve, so the arms remain as branches.

The ends of the branches

As in Pink, the ends of the curves of curvilinear_skeleton may move inward, and the transformation is not idempotent: on a curve one pixel thick, the end points are simple and are removed. To keep given points, use inhibit (below).

Parallel skeletons: symmetric or asymmetric

parallel_skeleton removes points in parallel steps, with critical kernels. It accepts connectivity 8 (2D) or 26 (3D) only.

square = np.zeros((14, 14), bool)
square[3:11, 3:11] = True                     # a square of even side
results = {
    "symmetric": skeleton.parallel_skeleton(square, 8),
    "asymmetric": skeleton.parallel_skeleton(square, 8, symmetric=False),
}
for name, result in results.items():
    print(f"square, {name:10s}", int(result.sum()), "pixels")

symmetric_curve = skeleton.parallel_skeleton(shape, 8, "curvilinear")
asymmetric = skeleton.parallel_skeleton(shape, 8, symmetric=False)
print("shape, symmetric curvilinear:", int(symmetric_curve.sum()), "pixels,",
      topology.topology(symmetric_curve, 8))
print("shape, asymmetric ultimate:  ", int(asymmetric.sum()), "pixels,",
      topology.topology(asymmetric, 8))
square, symmetric  4 pixels
square, asymmetric 1 pixels
shape, symmetric curvilinear: 229 pixels, Topology(objects=1, holes=1, cavities=0, euler=0)
shape, asymmetric ultimate:   98 pixels, Topology(objects=1, holes=1, cavities=0, euler=0)

A square of even side: the symmetric skeleton keeps a 2 x 2 block, the asymmetric one a single pixel; the symmetric curvilinear and asymmetric ultimate skeletons of the shape

The symmetric version treats all the points of a critical configuration alike. Its result is unchanged, up to the same rotation or mirror, when the object is rotated by 90 degrees or mirrored; the price is a small core for some shapes, here a 2 x 2 block for a square of even side. The asymmetric version keeps one point per configuration, with a fixed rule, and reaches one pixel. The symmetric curvilinear skeleton can be two pixels thick in places; measure.branches thins it before measuring (see branches and spurs).

In 2D, digitopo provides shape="ultimate" (symmetric or not) and shape="curvilinear" (symmetric). In 3D it provides "ultimate" and "curvilinear" (symmetric or not) and "surface" (symmetric). The other combinations raise DigitopoError, as in pink26.

Classic thinnings

skeleton.zhang_wang_thinning and skeleton.guo_hall_thinning are two classic 2D parallel thinnings, given to compare with the critical kernels. They have no topology proof: they may disconnect an object or erase a small part of it.

The effect of priority and inhibit

A sequential skeleton removes first the simple point with the lowest priority. The default priority is the squared Euclidean distance to the background: the object is peeled from its boundary inwards, and the skeleton is centred. Any other array of the shape of the image can be used; only the order of the values matters (in 2D, and for the ultimate skeleton in 3D).

# Default priority: squared Euclidean distance to the background.
default = skeleton.ultimate_skeleton(shape, 8)
# Another priority: the column index. The points on the left are removed first.
columns = np.broadcast_to(np.arange(shape.shape[1]), shape.shape)
by_column = skeleton.ultimate_skeleton(shape, 8, priority=columns)
for name, result in (("default", default), ("by column", by_column)):
    print(f"priority {name:9s}", int(result.sum()), "pixels,", topology.topology(result, 8))
priority default   104 pixels, Topology(objects=1, holes=1, cavities=0, euler=0)
priority by column 101 pixels, Topology(objects=1, holes=1, cavities=0, euler=0)

With the column index as priority, the shape is eaten from the left: the closed curve runs along the left side of the hole and ends in a point on the right. The topology is the same, the place of the skeleton is not.

The points of inhibit are never removed. The ultimate skeleton then keeps the paths that link them to the rest of the skeleton, which gives a skeleton with chosen end points:

# Points that must stay: the tips of the two arms and one point of the disk.
anchors = np.zeros_like(shape)
anchors[40, 111] = anchors[25, 85] = anchors[66, 40] = True
kept = skeleton.ultimate_skeleton(shape, 8, inhibit=anchors)
print("inhibit:", int(kept.sum()), "pixels,", topology.topology(kept, 8),
      "anchors kept:", bool(kept[anchors].all()))
inhibit: 176 pixels, Topology(objects=1, holes=1, cavities=0, euler=0) anchors kept: True

Ultimate skeleton with the default priority, with the column index as priority, and with three inhibited points (orange)

Priorities in 3D

For curvilinear_skeleton in 3D, Pink orders the points by 30 * priority + d, where d codes the background face neighbours: the differences between the priority values matter, not only their order.

A 3D skeleton

A volume made of a ring, a tube and a flat plate. Arrays are (depth, rows, columns); the object is 26-connected. In 3D, holes counts the tunnels: the ring has one.

z, y, x = np.mgrid[:40, :64, :72]
torus = (np.sqrt((x - 40) ** 2 + (y - 32) ** 2) - 16) ** 2 + (z - 20) ** 2 <= 6**2
tube = ((y - 32) ** 2 + (z - 20) ** 2 <= 4**2) & (x >= 52) & (x <= 69)
plate = (np.abs(z - 20) <= 3) & (np.abs(y - 32) <= 14) & (x >= 2) & (x <= 22)
volume = torus | tube | plate
print("volume:", volume.shape, int(volume.sum()), "voxels,", topology.topology(volume, 26))

curves = skeleton.curvilinear_skeleton(volume, 26)
surfaces = skeleton.parallel_skeleton(volume, 26, "surface")
for name, result in (("curvilinear", curves), ("surface", surfaces)):
    print(f"{name:11s}", int(result.sum()), "voxels,", topology.topology(result, 26))
volume: (40, 64, 72) 15219 voxels, Topology(objects=1, holes=1, cavities=0, euler=0)
curvilinear 147 voxels, Topology(objects=1, holes=1, cavities=0, euler=0)
surface     597 voxels, Topology(objects=1, holes=1, cavities=0, euler=0)

A volume is shown here by maximum projections: a pixel of the view is grey if the line of voxels behind it meets the object, blue if it meets the skeleton.

def projection(obj, thin, axis):
    """Maximum projections along one axis: object in grey, skeleton in blue."""
    return overlay(obj.max(axis=axis), thin.max(axis=axis))


show([("volume, seen from above", projection(volume, np.zeros_like(volume), 0)),
      ("curvilinear_skeleton", projection(volume, curves, 0)),
      ("parallel_skeleton, surface", projection(volume, surfaces, 0)),
      ("surface, side view", projection(volume, surfaces, 1))],
     "skeletons-3d.png", width=8.4, height=2.3)

Maximum projections of the volume, its curvilinear skeleton, its surface skeleton from above and from the side

The curvilinear skeleton is made of curves only: the plate becomes a few curves. The surface skeleton keeps the plate as a surface: a filled area seen from above, a line seen from the side. Both have the topology of the volume (one object, one tunnel).

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

import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
from digitopo import skeleton, topology

FIGURES = Path(__file__).resolve().parents[2] / "figures"
BLUE = (0.145, 0.490, 0.878)      # #257de0
ORANGE = (0.957, 0.447, 0.188)    # #f47230
TEXT = "#222222"


def overlay(obj, thin):
    """White background, object in light grey, thin result in blue."""
    rgb = np.ones(obj.shape + (3,))
    rgb[obj != 0] = (0.85, 0.85, 0.85)
    rgb[thin != 0] = BLUE
    return rgb


def show(panels, name, width=7.6, height=2.5, points=None):
    """One image per panel; points (rows, columns) are drawn as orange dots on the last one."""
    fig, axes = plt.subplots(1, len(panels), figsize=(width, height), facecolor="white",
                             edgecolor="#bbbbbb", linewidth=1)
    axes = np.atleast_1d(axes)
    for ax, (title, rgb) in zip(axes, panels):
        ax.imshow(rgb, interpolation="nearest")
        ax.set_title(title, fontsize=9, color=TEXT)
        ax.set_xticks([])
        ax.set_yticks([])
        for spine in ax.spines.values():
            spine.set_color("#dddddd")
    if points is not None:
        axes[-1].plot(points[1], points[0], "o", color=ORANGE, markersize=6,
                      markeredgecolor="white", markeredgewidth=0.8)
    fig.tight_layout()
    fig.savefig(FIGURES / name, dpi=100)
    plt.close(fig)


# A disk with a hole, and two arms.
r, c = np.mgrid[:80, :120]
shape = ((r - 40) ** 2 + (c - 40) ** 2 <= 28**2) & ((r - 40) ** 2 + (c - 36) ** 2 > 9**2)
shape |= (np.abs(r - 40) <= 5) & (c >= 60) & (c <= 112)
shape |= (np.abs((r - 40) + (c - 70)) <= 6) & (c >= 60) & (c <= 95) & (r < 40)
print("shape:", int(shape.sum()), "pixels,", topology.topology(shape, 8))

# 1. Sequential skeletons ------------------------------------------------------
ultimate = skeleton.ultimate_skeleton(shape, 8)
curvilinear = skeleton.curvilinear_skeleton(shape, 8)
for name, result in (("ultimate", ultimate), ("curvilinear", curvilinear)):
    print(f"{name:11s}", int(result.sum()), "pixels,", topology.topology(result, 8))

show([("shape", overlay(shape, np.zeros_like(shape))),
      ("ultimate_skeleton", overlay(shape, ultimate)),
      ("curvilinear_skeleton", overlay(shape, curvilinear))], "skeletons-sequential.png")

# 2. Parallel skeletons: symmetric or not -----------------------------------
square = np.zeros((14, 14), bool)
square[3:11, 3:11] = True                     # a square of even side
results = {
    "symmetric": skeleton.parallel_skeleton(square, 8),
    "asymmetric": skeleton.parallel_skeleton(square, 8, symmetric=False),
}
for name, result in results.items():
    print(f"square, {name:10s}", int(result.sum()), "pixels")

symmetric_curve = skeleton.parallel_skeleton(shape, 8, "curvilinear")
asymmetric = skeleton.parallel_skeleton(shape, 8, symmetric=False)
print("shape, symmetric curvilinear:", int(symmetric_curve.sum()), "pixels,",
      topology.topology(symmetric_curve, 8))
print("shape, asymmetric ultimate:  ", int(asymmetric.sum()), "pixels,",
      topology.topology(asymmetric, 8))

show([("square, symmetric", overlay(square, results["symmetric"])),
      ("square, asymmetric", overlay(square, results["asymmetric"])),
      ("curvilinear, symmetric", overlay(shape, symmetric_curve)),
      ("ultimate, asymmetric", overlay(shape, asymmetric))],
     "skeletons-parallel.png", width=8.4, height=2.4)

# 3. priority and inhibit -------------------------------------------------------
# Default priority: squared Euclidean distance to the background.
default = skeleton.ultimate_skeleton(shape, 8)
# Another priority: the column index. The points on the left are removed first.
columns = np.broadcast_to(np.arange(shape.shape[1]), shape.shape)
by_column = skeleton.ultimate_skeleton(shape, 8, priority=columns)
for name, result in (("default", default), ("by column", by_column)):
    print(f"priority {name:9s}", int(result.sum()), "pixels,", topology.topology(result, 8))

# Points that must stay: the tips of the two arms and one point of the disk.
anchors = np.zeros_like(shape)
anchors[40, 111] = anchors[25, 85] = anchors[66, 40] = True
kept = skeleton.ultimate_skeleton(shape, 8, inhibit=anchors)
print("inhibit:", int(kept.sum()), "pixels,", topology.topology(kept, 8),
      "anchors kept:", bool(kept[anchors].all()))

show([("priority: distance (default)", overlay(shape, default)),
      ("priority: column index", overlay(shape, by_column)),
      ("inhibit: 3 points (orange)", overlay(shape, kept))],
     "skeletons-priority-inhibit.png", points=np.nonzero(anchors))

# 4. A 3D skeleton -----------------------------------------------------------------
z, y, x = np.mgrid[:40, :64, :72]
torus = (np.sqrt((x - 40) ** 2 + (y - 32) ** 2) - 16) ** 2 + (z - 20) ** 2 <= 6**2
tube = ((y - 32) ** 2 + (z - 20) ** 2 <= 4**2) & (x >= 52) & (x <= 69)
plate = (np.abs(z - 20) <= 3) & (np.abs(y - 32) <= 14) & (x >= 2) & (x <= 22)
volume = torus | tube | plate
print("volume:", volume.shape, int(volume.sum()), "voxels,", topology.topology(volume, 26))

curves = skeleton.curvilinear_skeleton(volume, 26)
surfaces = skeleton.parallel_skeleton(volume, 26, "surface")
for name, result in (("curvilinear", curves), ("surface", surfaces)):
    print(f"{name:11s}", int(result.sum()), "voxels,", topology.topology(result, 26))

def projection(obj, thin, axis):
    """Maximum projections along one axis: object in grey, skeleton in blue."""
    return overlay(obj.max(axis=axis), thin.max(axis=axis))


show([("volume, seen from above", projection(volume, np.zeros_like(volume), 0)),
      ("curvilinear_skeleton", projection(volume, curves, 0)),
      ("parallel_skeleton, surface", projection(volume, surfaces, 0)),
      ("surface, side view", projection(volume, surfaces, 1))],
     "skeletons-3d.png", width=8.4, height=2.3)