Skip to content

Watershed

This page computes the topological watershed of a grey-level image, the watershed lines from markers, and compares these lines with those of skimage.segmentation.watershed. The terms (lakes, W-destructible points) are defined on the concepts page.

The code below is taken from docs/examples/scripts/watershed.py, which makes the figure. The whole script is at the end of the page. It needs SciPy and scikit-image (installed by the docs and test extras).

The image

The functions of digitopo.watershed take a uint8 image. Here, a smooth random relief:

# A smooth random relief, rescaled to 0..255.
rng = np.random.default_rng(0)
smooth = ndi.gaussian_filter(rng.standard_normal((96, 128)), 6)
image = np.round(255 * (smooth - smooth.min()) / np.ptp(smooth)).astype(np.uint8)

connectivity is the adjacency of the lakes, the basins and the minima: 4 or 8 in 2D, 6, 18 or 26 in 3D. Unlike the binary functions, the image has no frame: a minimum that touches the side of the image is a minimum like any other.

Topological watershed

topological_watershed lowers the W-destructible points until none is left. The result is at most the image at every point, with the same minima, the same number of lakes at every level and the same level of passes between the minima.

lowered = watershed.topological_watershed(image, 4)
minima = morphology.local_minima(image, connectivity=1)          # 4-connected minima
minima_after = morphology.local_minima(lowered, connectivity=1)
print("lowered <= image everywhere:", bool((lowered <= image).all()))
print("regional minima before:", skmeasure.label(minima, connectivity=1).max(),
      "after:", skmeasure.label(minima_after, connectivity=1).max())
print("points outside the minima after:", int((~minima_after).sum()), "of", image.size)
lowered <= image everywhere: True
regional minima before: 24 after: 24
points outside the minima after: 763 of 12288

The 24 minima of the image fill their basins; the 763 points left outside the minima form thin crest lines, at the level of the passes (second panel of the figure). On a plateau, the place of a crest line depends on the order in which the points are visited, which is Pink's order.

Watershed lines from markers

watershed_lines takes markers: each connected region of the markers becomes the only minimum of its basin. The result is True on the lines. Here the markers are the regional minima of the image, so that the result can be compared with scikit-image given the same markers.

# Markers: the regional minima of the image (any binary mask can be used).
lines = watershed.watershed_lines(image, minima, 4)
labels = skmeasure.label(minima, connectivity=1)
basins = segmentation.watershed(image, labels, connectivity=1, watershed_line=True)
lines_skimage = basins == 0

near = ndi.binary_dilation(lines_skimage, np.ones((3, 3), bool))
print("line pixels, digitopo:", int(lines.sum()), " scikit-image:", int(lines_skimage.sum()))
print("common:", int((lines & lines_skimage).sum()),
      " digitopo within 1 pixel of scikit-image:", int((lines & near).sum()))
print("basins (4-connected), digitopo:", skmeasure.label(~lines, connectivity=1).max(),
      " scikit-image:", skmeasure.label(~lines_skimage, connectivity=1).max())
line pixels, digitopo: 778  scikit-image: 830
common: 380  digitopo within 1 pixel of scikit-image: 701
basins (4-connected), digitopo: 24  scikit-image: 24

The image, its topological watershed, the watershed lines of digitopo on the image, and the lines of digitopo and scikit-image compared

Both methods give 24 basins, one per marker. The lines are not the same pixels: 380 of the 778 line pixels of digitopo are also line pixels of scikit-image, and 701 are at most one pixel away from one. The two algorithms differ: scikit-image floods the image from the markers with a priority queue, while digitopo computes the topological watershed of the image with the markers imposed at level 0. Where the relief is flat or the crest is wide, the two choose different pixels for the line.

Markers at level 0

The markers are imposed at level 0, so two markers joined through points at level 0 form one region, with no line between them.

The whole script
# SPDX-License-Identifier: CECILL-2.1
# Figures of docs/examples/watershed.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/watershed.py
from pathlib import Path

import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
from digitopo import watershed
from scipy import ndimage as ndi
from skimage import measure as skmeasure
from skimage import morphology, segmentation

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

# A smooth random relief, rescaled to 0..255.
rng = np.random.default_rng(0)
smooth = ndi.gaussian_filter(rng.standard_normal((96, 128)), 6)
image = np.round(255 * (smooth - smooth.min()) / np.ptp(smooth)).astype(np.uint8)

lowered = watershed.topological_watershed(image, 4)
minima = morphology.local_minima(image, connectivity=1)          # 4-connected minima
minima_after = morphology.local_minima(lowered, connectivity=1)
print("lowered <= image everywhere:", bool((lowered <= image).all()))
print("regional minima before:", skmeasure.label(minima, connectivity=1).max(),
      "after:", skmeasure.label(minima_after, connectivity=1).max())
print("points outside the minima after:", int((~minima_after).sum()), "of", image.size)

# Markers: the regional minima of the image (any binary mask can be used).
lines = watershed.watershed_lines(image, minima, 4)
labels = skmeasure.label(minima, connectivity=1)
basins = segmentation.watershed(image, labels, connectivity=1, watershed_line=True)
lines_skimage = basins == 0

near = ndi.binary_dilation(lines_skimage, np.ones((3, 3), bool))
print("line pixels, digitopo:", int(lines.sum()), " scikit-image:", int(lines_skimage.sum()))
print("common:", int((lines & lines_skimage).sum()),
      " digitopo within 1 pixel of scikit-image:", int((lines & near).sum()))
print("basins (4-connected), digitopo:", skmeasure.label(~lines, connectivity=1).max(),
      " scikit-image:", skmeasure.label(~lines_skimage, connectivity=1).max())

grey = np.repeat((image / 255.0)[..., None], 3, axis=2)
compare = np.ones(image.shape + (3,))
compare[lines] = BLUE
compare[lines_skimage] = ORANGE
compare[lines & lines_skimage] = (0.13, 0.13, 0.13)
on_image = grey.copy()
on_image[lines] = BLUE

fig, axes = plt.subplots(1, 4, figsize=(9.2, 2.7), facecolor="white", edgecolor="#bbbbbb",
                         linewidth=1)
panels = (("image", grey), ("topological_watershed", lowered),
          ("watershed_lines (blue)", on_image), ("lines compared", compare))
for ax, (title, view) in zip(axes, panels):
    if view.ndim == 2:
        ax.imshow(view, cmap="gray", vmin=0, vmax=255, interpolation="nearest")
    else:
        ax.imshow(view, 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")
handles = [plt.Rectangle((0, 0), 1, 1, color=c) for c in (BLUE, ORANGE, (0.13, 0.13, 0.13))]
fig.legend(handles, ["digitopo only", "scikit-image only", "both"], loc="lower right",
           ncol=3, fontsize=8, frameon=False)
fig.tight_layout(rect=(0, 0.08, 1, 1))
fig.savefig(FIGURES / "watershed.png", dpi=100)
plt.close(fig)

References

  • M. Couprie, G. Bertrand, "Topological gray-scale watershed transformation", Proc. SPIE Vision Geometry VI, vol. 3168, 1997, pp. 136-146.
  • G. Bertrand, "On topological watersheds", Journal of Mathematical Imaging and Vision 22(2-3):217-230, 2005.
  • M. Couprie, L. Najman, G. Bertrand, "Quasi-linear algorithms for the topological watershed", Journal of Mathematical Imaging and Vision 22(2-3):231-249, 2005.