Skip to content

Grey-level operators

This page simplifies a noisy grey-level image with the homotopic kernel, which keeps the topology of every section, and with the lambda-kernel, which also removes the minima and peaks of small contrast. The terms (sections, destructible points) are defined on the concepts page.

The code below is taken from docs/examples/scripts/grayscale.py, which makes the figure. The whole script is at the end of the page. It needs SciPy and scikit-image.

The image

Nine dark cells separated by bright walls, with noise. The functions of digitopo.grayscale take a uint8 image (any other dtype, bool included, raises TypeError).

# Nine dark cells separated by bright walls, with noise.
rng = np.random.default_rng(3)
r, c = np.mgrid[:96, :128]
centres = rng.uniform([8, 8], [88, 120], size=(9, 2))
distance = np.min([np.hypot(r - y, c - x) for y, x in centres], axis=0)
noisy = np.clip(40 + 8 * distance + rng.normal(0, 12, distance.shape), 0, 255)
image = ndi.uniform_filter(noisy.astype(np.uint8), 3)


def count_minima(a):
    """Number of regional minima, 4-connected (the connectivity of the minima)."""
    return int(skmeasure.label(morphology.local_minima(a, connectivity=1), connectivity=1).max())


print("image:", image.shape, image.dtype, "minima:", count_minima(image))
image: (96, 128) uint8 minima: 43

The noise makes 43 regional minima, much more than the nine cells.

Connectivity of the minima

For the grey-level operators, connectivity is the connectivity of the minima (the dark regions), as in Pink. The sections (the bright regions) use the complementary connectivity. This is not the convention of the binary functions, where connectivity is that of the object. The minima are therefore counted here with 4-connectivity (connectivity=1 in scikit-image).

Homotopic kernel

homotopic_kernel lowers the destructible points, lowest level first, until none is left. Every section of the result has the topology of the same section of the image; in particular the number of minima does not change.

kernel = grayscale.homotopic_kernel(image, 4)
print("homotopic_kernel: minima:", count_minima(kernel),
      " kernel <= image:", bool((kernel <= image).all()))
homotopic_kernel: minima: 43  kernel <= image: True

The minima spread as much as they can and end separated by thin crest lines (second panel of the figure). The 43 minima of the noise are all kept.

Lambda-kernel

lambda_kernel(image, 4, lambda_) also lowers the peaks and the passes of contrast at most lambda_. The minima and the peaks of small contrast disappear: it is a filter, not a homotopic operator (except for lambda_=0). Only connectivity 4 and 2D images are available, as in Pink.

filtered = {}
for lam in (0, 5, 10, 20):
    filtered[lam] = grayscale.lambda_kernel(image, 4, lam)
    print(f"lambda_kernel, lambda_={lam:2d}: minima: {count_minima(filtered[lam])}")
print("lambda_=0 equals homotopic_kernel:", bool((filtered[0] == kernel).all()))
for lam in (5, 20):
    labels = skmeasure.label(morphology.local_minima(filtered[lam], connectivity=1),
                             connectivity=1)
    cells = {int(labels[int(round(y)), int(round(x))]) for y, x in centres}
    print(f"lambda_={lam}: the 9 cell centres lie in {len(cells)} different minima")
lambda_kernel, lambda_= 0: minima: 43
lambda_kernel, lambda_= 5: minima: 9
lambda_kernel, lambda_=10: minima: 9
lambda_kernel, lambda_=20: minima: 8
lambda_=0 equals homotopic_kernel: False
lambda_=5: the 9 cell centres lie in 9 different minima
lambda_=20: the 9 cell centres lie in 8 different minima

The noisy image, its homotopic kernel, and its lambda-kernels for lambda 5 and 20

With lambda_=5, 9 minima are left, one per cell: the minima made by the noise are merged into the minimum of their cell. With lambda_=20, two cells separated by a wall of low contrast are merged too, and 8 minima are left. The choice of lambda_ is the choice of the smallest contrast that counts.

With lambda_=0, the lambda-kernel keeps the 43 minima, as the homotopic kernel does, but the two results are not equal point by point. Both are homotopic simplifications of the image with no destructible point left off the border; such a result is not unique, and the two functions, ported from two different Pink programs, reach different ones.

Border and difference with Pink

The points on the border of the image (its first and last rows and columns) are never modified, as in Pink and pink26. To have the border processed too, pad the image and crop the result: np.pad(image, 1, mode="edge"), then [1:-1, 1:-1]. The lambda-kernel gives the results of pink26, which corrects Pink's lambdaskel command; see the documentation of lambda_kernel.

Thinning and thickening step by step

homotopic_thinning(image, connectivity, max_steps=k) lowers the destructible points step by step; each step shrinks the bright regions by about one point. homotopic_thickening is its dual: it raises the constructible points. Both accept a condition image that bounds the change. See their reference for examples.

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

import matplotlib

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

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

# Nine dark cells separated by bright walls, with noise.
rng = np.random.default_rng(3)
r, c = np.mgrid[:96, :128]
centres = rng.uniform([8, 8], [88, 120], size=(9, 2))
distance = np.min([np.hypot(r - y, c - x) for y, x in centres], axis=0)
noisy = np.clip(40 + 8 * distance + rng.normal(0, 12, distance.shape), 0, 255)
image = ndi.uniform_filter(noisy.astype(np.uint8), 3)


def count_minima(a):
    """Number of regional minima, 4-connected (the connectivity of the minima)."""
    return int(skmeasure.label(morphology.local_minima(a, connectivity=1), connectivity=1).max())


print("image:", image.shape, image.dtype, "minima:", count_minima(image))

kernel = grayscale.homotopic_kernel(image, 4)
print("homotopic_kernel: minima:", count_minima(kernel),
      " kernel <= image:", bool((kernel <= image).all()))

filtered = {}
for lam in (0, 5, 10, 20):
    filtered[lam] = grayscale.lambda_kernel(image, 4, lam)
    print(f"lambda_kernel, lambda_={lam:2d}: minima: {count_minima(filtered[lam])}")
print("lambda_=0 equals homotopic_kernel:", bool((filtered[0] == kernel).all()))
for lam in (5, 20):
    labels = skmeasure.label(morphology.local_minima(filtered[lam], connectivity=1),
                             connectivity=1)
    cells = {int(labels[int(round(y)), int(round(x))]) for y, x in centres}
    print(f"lambda_={lam}: the 9 cell centres lie in {len(cells)} different minima")

fig, axes = plt.subplots(1, 4, figsize=(9.2, 2.3), facecolor="white", edgecolor="#bbbbbb",
                         linewidth=1)
panels = ((f"image ({count_minima(image)} minima)", image),
          (f"homotopic_kernel ({count_minima(kernel)})", kernel),
          (f"lambda_kernel, 5 ({count_minima(filtered[5])})", filtered[5]),
          (f"lambda_kernel, 20 ({count_minima(filtered[20])})", filtered[20]))
for ax, (title, view) in zip(axes, panels):
    ax.imshow(view, cmap="gray", vmin=0, vmax=255, interpolation="nearest")
    ax.set_title(title, fontsize=9, color=TEXT)
    ax.set_xticks([])
    ax.set_yticks([])
fig.tight_layout()
fig.savefig(FIGURES / "grayscale.png", dpi=100)
plt.close(fig)

References

  • G. Bertrand, J.-C. Everat, M. Couprie, "Image segmentation through operators based upon topology", Journal of Electronic Imaging 6(4):395-405, 1997.
  • M. Couprie, F. N. Bezerra, G. Bertrand, "Topological operators for grayscale image processing", Journal of Electronic Imaging 10(4):1003-1015, 2001.