Branches and spurs¶
A skeleton is often measured: number of branches, their lengths, the
junctions. measure.branches cuts a thin skeleton into branches and
measures them; measure.prune removes the short terminal branches
(spurs) that small bumps of the boundary create. Both are additions of
digitopo, with no equivalent in pink26.
The code below is taken from
docs/examples/scripts/branches.py, which makes
the figures. The whole script is at the end of the page.
Words¶
- An end point of a skeleton has exactly one skeleton neighbour.
- A junction is a connected group of points with three skeleton neighbours or more.
- A branch is the chain of points between two nodes (end points or
junctions), both included. Its kind (
measure.BranchKind) is TERMINAL (from an end point to a junction), INTERNAL (between two junctions, possibly the same one), ISOLATED (between two end points, or a single point) or CYCLE (a closed curve with no end point and no junction). - The length of a branch is the sum of the Euclidean distances between
the centres of its successive points, in the units of
spacing.
Two skeleton points are linked when they are neighbours and no other skeleton point lies in the box that they span (the m-adjacency of Gonzalez and Woods, extended to 3D), so that a staircase is a chain and not a row of junctions.
Branches of a skeleton¶
The shape is a thick "Y" with a ring, and six small bumps on its boundary. Its sequential curvilinear skeleton has a spur for most bumps.
# A thick "Y" with a ring, and six small bumps on its boundary.
r, c = np.mgrid[:80, :140]
shape = (np.abs(r - 55) <= 6) & (c >= 8) & (c <= 132)
shape |= (np.abs((r - 55) + (c - 75)) <= 6) & (r >= 8) & (r <= 55)
shape |= (r - 55) ** 2 + (c - 32) ** 2 <= 15**2
shape &= (r - 55) ** 2 + (c - 32) ** 2 > 5**2
for row, col in [(48, 60), (62, 95), (62, 115), (48, 110), (40, 30), (31, 96)]:
shape[row - 1:row + 2, col - 1:col + 2] = True
print("shape:", topology.topology(shape, 8))
curve = skeleton.curvilinear_skeleton(shape, 8)
b = measure.branches(curve, 8)
print(len(b), "branches:", {k.name: b.count(k) for k in measure.BranchKind})
for k in range(len(b)):
kind = measure.BranchKind(b.kind[k]).name
print(f" {k:2d} {kind:8s} length {b.length[k]:5.1f} from {b.start[k]} to {b.end[k]}")
shape: Topology(objects=1, holes=1, cavities=0, euler=0)
14 branches: {'TERMINAL': 7, 'INTERNAL': 7, 'ISOLATED': 0, 'CYCLE': 0}
0 TERMINAL length 54.5 from [ 13 117] to [53 82]
1 TERMINAL length 5.0 from [49 60] to [54 60]
2 TERMINAL length 5.0 from [ 49 110] to [ 54 110]
3 TERMINAL length 4.0 from [55 15] to [55 19]
4 TERMINAL length 10.4 from [ 55 125] to [ 56 115]
5 TERMINAL length 5.0 from [61 95] to [56 95]
6 TERMINAL length 5.0 from [ 61 115] to [ 56 115]
7 INTERNAL length 23.2 from [53 82] to [54 60]
8 INTERNAL length 14.2 from [53 82] to [56 95]
9 INTERNAL length 15.4 from [54 60] to [55 45]
10 INTERNAL length 15.8 from [ 54 110] to [56 95]
11 INTERNAL length 5.8 from [ 54 110] to [ 56 115]
12 INTERNAL length 36.6 from [55 19] to [55 45]
13 INTERNAL length 35.5 from [55 19] to [55 45]
The result b is a measure.Branches: b.start and b.end hold the
(row, column) coordinates of the ends of each branch (a TERMINAL branch
starts at its end point), b.length the lengths, b.kind the codes of
BranchKind, b.paths the coordinates of the points of each branch in
order, and b.labels an image: 0 outside the skeleton, k on branch
k - 1, -1 on the junctions. b.skeleton is the skeleton that was
measured.
The two halves of the ring are the INTERNAL branches 12 and 13, between the junctions at columns 19 and 45. Four TERMINAL branches of length 5 (1, 2, 5 and 6) are spurs made by the bumps; the two other bumps made no spur. Branch 3 (length 4) is the short end of the bar, on the left of the ring; branch 4 is the right end of the bar, and branch 0 the diagonal arm.
thin=True
By default, branches first thins the skeleton: it removes its simple
points, except its end points (ultimate_skeleton with the end points
inhibited). The topology and the end points are kept; the points that
make a curve two points thick, or a 2 x 2 block, go. The symmetric
parallel skeletons keep such points, which would otherwise appear as
junctions or small cycles. Use thin=False for a skeleton that is
already thin.
Pruning the spurs¶
measure.prune removes, in one pass, every TERMINAL branch shorter than
min_length, except its junction point. The other kinds are kept:
removing an ISOLATED branch would delete an object, removing an INTERNAL
or CYCLE branch would cut the network or open a loop. So the topology of
the skeleton does not change.
pruned = measure.prune(curve, 8, min_length=8)
again = measure.branches(pruned, 8)
print("after prune:", len(again), "branches:", {k.name: again.count(k) for k in measure.BranchKind})
print("topology before:", topology.topology(b.skeleton, 8))
print("topology after: ", topology.topology(pruned, 8))
after prune: 4 branches: {'TERMINAL': 2, 'INTERNAL': 2, 'ISOLATED': 0, 'CYCLE': 0}
topology before: Topology(objects=1, holes=1, cavities=0, euler=0)
topology after: Topology(objects=1, holes=1, cavities=0, euler=0)

The four spurs and the short end of the bar (length 4) are removed. The diagonal arm (54.5) and the right end of the bar (10.4) are longer than 8 and stay. Once the spurs are gone their junctions are no longer junctions, so 4 branches remain: the two arms, the bar between the ring and the "Y", and the ring, now one INTERNAL branch that starts and ends at the same junction.
Two points to keep in mind:
min_lengthmust be smaller than the real branches you want to keep: here the end of the bar, a real part of the shape, is shorter than 8 and is removed with the spurs.- With
thin=True(the default), the junction point of an 8-connected line is simple and the thinning removes it first: the junction moves one pixel into the spur, and a bump of one pixel remains after pruning (it can be seen where the spurs were, on the right of the figure). A branch that becomes terminal after a pass can be removed by callingpruneagain.
Physical lengths with spacing¶
The length is counted in the units of spacing, the size of a step along
each axis: a step along an axis counts spacing[axis], a diagonal step
the square root of the sum of the squares. For a volume, spacing is the
voxel size (dz, dy, dx). The topology never uses spacing.
Here the same ring, of median radius 30 µm, is imaged twice: with square pixels of 1 µm, and with pixels of 2 µm along the rows and 1 µm along the columns.
# A ring of median radius 30 um, imaged twice: with square pixels of 1 um, and
# with pixels of 2 um (rows) x 1 um (columns).
def ring_image(step):
rows, cols = np.mgrid[:int(100 / step[0]), :int(100 / step[1])]
y = (rows - rows.shape[0] // 2) * step[0]
x = (cols - cols.shape[1] // 2) * step[1]
return (x**2 + y**2 <= 34**2) & (x**2 + y**2 >= 26**2)
expected = 2 * np.pi * 30
results = {}
for step in [(1.0, 1.0), (2.0, 1.0)]:
image = ring_image(step)
centre = skeleton.parallel_skeleton(image, 8, "curvilinear")
ring = measure.branches(centre, 8, spacing=step)
results[step] = (image, ring)
kinds = [measure.BranchKind(k).name for k in ring.kind]
error = 100 * (ring.length[0] - expected) / expected
print(f"spacing {step}: {kinds}, length {ring.length[0]:.1f} um, "
f"circle {expected:.1f} um, {error:+.1f} %")
spacing (1.0, 1.0): ['CYCLE'], length 197.8 um, circle 188.5 um, +4.9 %
spacing (2.0, 1.0): ['CYCLE'], length 204.1 um, circle 188.5 um, +8.3 %

With spacing, both images give a length in micrometres, close to the
perimeter of the circle. The length is a raw chain length: it
overestimates oblique curves by a few percent, more on a coarse grid. The
module documentation gives up to about 8 % for a straight line at 22.5
degrees in 2D, with square pixels. There is no correction of the Kulpa
type.
The whole script
# SPDX-License-Identifier: CECILL-2.1
# Figures of docs/examples/branches.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/branches.py
from pathlib import Path
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
from digitopo import measure, skeleton, topology
from matplotlib.colors import ListedColormap
FIGURES = Path(__file__).resolve().parents[2] / "figures"
TEXT = "#222222"
# Fixed order of categorical colours, one per branch kind.
KIND_COLOURS = {
measure.BranchKind.TERMINAL: "#f47230",
measure.BranchKind.INTERNAL: "#257de0",
measure.BranchKind.ISOLATED: "#00b894",
measure.BranchKind.CYCLE: "#ee7fac",
}
# A thick "Y" with a ring, and six small bumps on its boundary.
r, c = np.mgrid[:80, :140]
shape = (np.abs(r - 55) <= 6) & (c >= 8) & (c <= 132)
shape |= (np.abs((r - 55) + (c - 75)) <= 6) & (r >= 8) & (r <= 55)
shape |= (r - 55) ** 2 + (c - 32) ** 2 <= 15**2
shape &= (r - 55) ** 2 + (c - 32) ** 2 > 5**2
for row, col in [(48, 60), (62, 95), (62, 115), (48, 110), (40, 30), (31, 96)]:
shape[row - 1:row + 2, col - 1:col + 2] = True
print("shape:", topology.topology(shape, 8))
curve = skeleton.curvilinear_skeleton(shape, 8)
b = measure.branches(curve, 8)
print(len(b), "branches:", {k.name: b.count(k) for k in measure.BranchKind})
for k in range(len(b)):
kind = measure.BranchKind(b.kind[k]).name
print(f" {k:2d} {kind:8s} length {b.length[k]:5.1f} from {b.start[k]} to {b.end[k]}")
pruned = measure.prune(curve, 8, min_length=8)
again = measure.branches(pruned, 8)
print("after prune:", len(again), "branches:", {k.name: again.count(k) for k in measure.BranchKind})
print("topology before:", topology.topology(b.skeleton, 8))
print("topology after: ", topology.topology(pruned, 8))
def kind_image(shape, branches):
"""0 background, 1 object, 2 + kind on each branch, 7 on the junctions."""
out = shape.astype(np.uint8)
for path, kind in zip(branches.paths, branches.kind):
out[tuple(path.T)] = 2 + int(kind)
out[branches.labels == -1] = 7
return out
cmap = ListedColormap(["white", "#d9d9d9", "white"] + list(KIND_COLOURS.values()) + ["#222222"])
fig, axes = plt.subplots(1, 2, figsize=(8.4, 3.0), facecolor="white", edgecolor="#bbbbbb",
linewidth=1)
for ax, (title, result) in zip(axes, (("measure.branches(curve, 8)", b),
("after measure.prune(curve, 8, min_length=8)", again))):
ax.imshow(kind_image(shape, result), cmap=cmap, vmin=0, vmax=7, 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")
present = [k for k in KIND_COLOURS if b.count(k)] # the legend lists the kinds shown
handles = [plt.Rectangle((0, 0), 1, 1, color=KIND_COLOURS[k]) for k in present]
handles.append(plt.Rectangle((0, 0), 1, 1, color="#222222"))
fig.legend(handles, [k.name.lower() for k in present] + ["junction"], loc="lower center",
ncol=len(handles), fontsize=8, frameon=False)
fig.tight_layout(rect=(0, 0.08, 1, 1))
fig.savefig(FIGURES / "branches-prune.png", dpi=100)
plt.close(fig)
# A ring of median radius 30 um, imaged twice: with square pixels of 1 um, and
# with pixels of 2 um (rows) x 1 um (columns).
def ring_image(step):
rows, cols = np.mgrid[:int(100 / step[0]), :int(100 / step[1])]
y = (rows - rows.shape[0] // 2) * step[0]
x = (cols - cols.shape[1] // 2) * step[1]
return (x**2 + y**2 <= 34**2) & (x**2 + y**2 >= 26**2)
expected = 2 * np.pi * 30
results = {}
for step in [(1.0, 1.0), (2.0, 1.0)]:
image = ring_image(step)
centre = skeleton.parallel_skeleton(image, 8, "curvilinear")
ring = measure.branches(centre, 8, spacing=step)
results[step] = (image, ring)
kinds = [measure.BranchKind(k).name for k in ring.kind]
error = 100 * (ring.length[0] - expected) / expected
print(f"spacing {step}: {kinds}, length {ring.length[0]:.1f} um, "
f"circle {expected:.1f} um, {error:+.1f} %")
fig, axes = plt.subplots(1, 2, figsize=(5.6, 2.9), facecolor="white", edgecolor="#bbbbbb",
linewidth=1)
for ax, (step, (image, ring)) in zip(axes, results.items()):
view = image.astype(np.uint8) + ring.skeleton
# aspect = row step / column step: the image is shown in micrometres.
ax.imshow(view, cmap=ListedColormap(["white", "#d9d9d9", "#257de0"]), vmin=0, vmax=2,
aspect=step[0] / step[1], interpolation="nearest")
ax.set_title(f"spacing={step}: {image.shape[0]} x {image.shape[1]} pixels",
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 / "branches-spacing.png", dpi=100)
plt.close(fig)