Skip to content

Evaluating a segmentation

Overlap scores such as Dice barely change when a thin vessel is cut in two, or when two branches are joined, although each of these errors changes what is measured afterwards: number of objects, branches, loops. digitopo.evaluation looks at the topology instead, for any segmentation, including one produced by a neural network. Its two functions are additions of digitopo, with no equivalent in pink26.

  • topology_errors(prediction, reference, connectivity) returns the topology of the prediction minus the topology of the reference: signed differences of the number of objects, holes (2D) or tunnels (3D), cavities and of the Euler characteristic.
  • cl_dice(prediction, reference, connectivity) is the centreline Dice of Shit et al. (2021). With \(S_P\) and \(S_R\) the skeletons of the prediction \(P\) and of the reference \(R\), the topological precision is \(|S_P \cap R| / |S_P|\), the topological sensitivity is \(|S_R \cap P| / |S_R|\), and clDice is their harmonic mean, between 0 and 1.

The skeletons of cl_dice are digitopo's curvilinear skeletons: the symmetric parallel skeleton for connectivity 8 or 26, the sequential one for 4 or 6. The original article used the skeletonization of scikit-image, so the values may differ slightly from other implementations.

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

A reference vessel tree

# A vessel tree: segments drawn one pixel wide, then thickened to 5 pixels.
segments = [((5, 60), (40, 60)), ((40, 60), (75, 25)), ((40, 60), (75, 95)),
            ((60, 40), (60, 10)), ((58, 77), (30, 110)), ((75, 25), (90, 30)),
            ((75, 95), (92, 100))]
centre = np.zeros((96, 120), bool)
for (r0, c0), (r1, c1) in segments:
    centre[line(r0, c0, r1, c1)] = True
reference = ndi.binary_dilation(centre, np.ones((5, 5), bool))
print("reference:", topology.topology(reference, 8))
reference: Topology(objects=1, holes=0, cavities=0, euler=1)

Three wrong segmentations

The first cuts the trunk, the second adds a bridge between two branches, the third is the whole tree moved by two pixels.

cut = reference.copy()
cut[20:24, :] = False                      # the trunk is cut

merged = reference.copy()
merged[68:71, 32:89] = True                # a bridge between two branches

shifted = np.roll(reference, 2, axis=1)    # the whole tree moved by 2 pixels


def dice(a, b):
    return 2 * (a & b).sum() / (a.sum() + b.sum())


for name, prediction in (("cut", cut), ("merged", merged), ("shifted", shifted)):
    errors = evaluation.topology_errors(prediction, reference, 8)
    score = evaluation.cl_dice(prediction, reference, 8)
    print(f"{name:8s} Dice {dice(prediction, reference):.3f}  clDice {score:.3f}  {errors}")
cut      Dice 0.993  clDice 0.991  Topology(objects=1, holes=0, cavities=0, euler=1)
merged   Dice 0.951  clDice 0.908  Topology(objects=0, holes=1, cavities=0, euler=-1)
shifted  Dice 0.770  clDice 1.000  Topology(objects=0, holes=0, cavities=0, euler=0)

The reference tree and three predictions: cut, merged by a bridge, shifted; added pixels in blue, missing pixels in orange

Read the three lines:

  • cut: 4 rows of pixels are missing. Dice (0.993) and clDice (0.991) hardly change, but topology_errors reports one object too many (objects=1): the tree is in two pieces.
  • merged: the bridge closes a loop. topology_errors reports one hole too many (holes=1); clDice drops more than Dice (0.908 against 0.951), because the skeleton of the bridge lies outside the reference.
  • shifted: no topology error, and clDice is 1.000 because the skeleton of each mask lies inside the other mask; Dice drops to 0.770. The topology is right, the position is not.

So no single number is enough. topology_errors says whether the topology is right; an overlap score says whether the objects are in the right place; clDice is in between.

Global counts

The counts of topology_errors are global (Betti numbers of the whole image). They do not say which object is wrong, and an extra object in one place and a missing one in another place cancel out. All fields at 0 does not mean that the objects are in the same place.

The whole script
# SPDX-License-Identifier: CECILL-2.1
# Figures of docs/examples/evaluation.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 scikit-image and SciPy):
#     python docs/examples/scripts/evaluation.py
from pathlib import Path

import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
from digitopo import evaluation, topology
from scipy import ndimage as ndi
from skimage.draw import line

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

# A vessel tree: segments drawn one pixel wide, then thickened to 5 pixels.
segments = [((5, 60), (40, 60)), ((40, 60), (75, 25)), ((40, 60), (75, 95)),
            ((60, 40), (60, 10)), ((58, 77), (30, 110)), ((75, 25), (90, 30)),
            ((75, 95), (92, 100))]
centre = np.zeros((96, 120), bool)
for (r0, c0), (r1, c1) in segments:
    centre[line(r0, c0, r1, c1)] = True
reference = ndi.binary_dilation(centre, np.ones((5, 5), bool))
print("reference:", topology.topology(reference, 8))

cut = reference.copy()
cut[20:24, :] = False                      # the trunk is cut

merged = reference.copy()
merged[68:71, 32:89] = True                # a bridge between two branches

shifted = np.roll(reference, 2, axis=1)    # the whole tree moved by 2 pixels


def dice(a, b):
    return 2 * (a & b).sum() / (a.sum() + b.sum())


for name, prediction in (("cut", cut), ("merged", merged), ("shifted", shifted)):
    errors = evaluation.topology_errors(prediction, reference, 8)
    score = evaluation.cl_dice(prediction, reference, 8)
    print(f"{name:8s} Dice {dice(prediction, reference):.3f}  clDice {score:.3f}  {errors}")

fig, axes = plt.subplots(1, 4, figsize=(9.2, 2.6), facecolor="white", edgecolor="#bbbbbb",
                         linewidth=1)
panels = (("reference", reference), ("cut", cut), ("merged", merged), ("shifted", shifted))
for ax, (title, mask) in zip(axes, panels):
    rgb = np.ones(mask.shape + (3,))
    rgb[mask & reference] = (0.85, 0.85, 0.85)
    rgb[mask & ~reference] = (0.145, 0.490, 0.878)    # added pixels, blue
    rgb[~mask & reference] = (0.957, 0.447, 0.188)    # missing pixels, orange
    ax.imshow(rgb, interpolation="nearest")
    if title == "reference":
        ax.set_title(title, fontsize=9, color=TEXT)
    else:
        e = evaluation.topology_errors(mask, reference, 8)
        ax.set_title(f"{title}: objects {e.objects:+d}, holes {e.holes:+d}\n"
                     f"Dice {dice(mask, reference):.2f}, "
                     f"clDice {evaluation.cl_dice(mask, reference, 8):.2f}",
                     fontsize=9, color=TEXT)
    ax.set_xticks([])
    ax.set_yticks([])
    for spine in ax.spines.values():
        spine.set_color("#dddddd")
handles = [plt.Rectangle((0, 0), 1, 1, color=c) for c in ((0.145, 0.490, 0.878),
                                                          (0.957, 0.447, 0.188))]
fig.legend(handles, ["added pixels", "missing pixels"], loc="lower right", ncol=2, fontsize=8,
           frameon=False)
fig.tight_layout(rect=(0, 0.07, 1, 1))
fig.savefig(FIGURES / "evaluation.png", dpi=100)
plt.close(fig)

Reference

S. Shit, J. C. Paetzold, A. Sekuboyina, I. Ezhov, A. Unger, A. Zhylka, J. P. W. Pluim, U. Bauer, B. H. Menze, "clDice -- a novel topology-preserving loss function for tubular structure segmentation", CVPR 2021, pp. 16560-16569.