digitopo with NumPy, SciPy and scikit-image¶
digitopo keeps the conventions of pink26, so that code written for one runs with the other. Some of them differ from those of scikit-image and SciPy. This page lists the differences, and how to go from one library to the other.
The code below is taken from
docs/examples/scripts/scikit_image.py. The
whole script is at the end of the page. It needs SciPy and scikit-image
(installed by the docs and test extras).
The differences¶
| Topic | scikit-image, SciPy | digitopo | How to convert |
|---|---|---|---|
| Connectivity | connectivity from 1 to ndim: the number of coordinates in which a neighbour may differ; often a default value |
the number of neighbours: 4 or 8 in 2D, 6 or 26 in 3D (18 for the watershed); always given | digitopo.connectivity(ndim, c) and digitopo.skimage_connectivity(ndim, n) |
| Connectivity of the grey-level operators | none | the connectivity of the minima (the dark regions), not of the bright ones | see below |
| Grey-level images | floats in [0, 1] accepted everywhere | uint8 only, as in pink26 |
convert=True, or digitopo.interop.as_uint8 |
| Watershed | segmentation.watershed(image, markers): labelled markers, returns labels |
watershed_lines: a bool mask of markers, returns the lines |
digitopo.watershed.watershed_labels |
| Distance map | ndi.distance_transform_edt: Euclidean distance (floats) to the zeros of the array, with sampling |
distance_map: squared distance (int32); the outside of the array is background; no physical spacing |
np.sqrt, and pad the mask with zeros for SciPy |
What is the same:
- the order of the axes,
(rows, columns)and(depth, rows, columns); - the masks: any nonzero value is an object point, and the results are
bool; digitopo.topology.euler_characteristicisskimage.measure.euler_numberfor the same connectivity;- the physical spacing of
digitopo.measure, calledspacingas inskimage.measure.regionprops; digitopo.DigitopoErroris aValueError;- the functions release the GIL, and none modifies its input.
Connectivity¶
scikit-image and scipy.ndimage.generate_binary_structure count as
neighbours the points that differ by at most c coordinates, each by 1.
digitopo gives the number of these neighbours:
ndim |
scikit-image | digitopo |
|---|---|---|
| 2 | 1, 2 | 4, 8 |
| 3 | 1, 2, 3 | 6, 18, 26 |
rng = np.random.default_rng(0)
mask = ndi.gaussian_filter(rng.random((128, 128)), 3) > 0.5
for value in (4, 8):
rank = digitopo.skimage_connectivity(2, value) # 1 for 4, 2 for 8
objects = measure.label(mask, connectivity=rank).max()
euler = measure.euler_number(mask, connectivity=rank)
print(f"digitopo {value} = scikit-image {rank}:",
"objects", topology.topology(mask, value).objects, objects,
"| Euler", topology.euler_characteristic(mask, value), euler)
print("scikit-image 2 in 3D =", digitopo.connectivity(3, 2))
digitopo 4 = scikit-image 1: objects 19 19 | Euler 14 14
digitopo 8 = scikit-image 2: objects 17 17 | Euler 11 11
scikit-image 2 in 3D = 18
The default values of scikit-image
skimage.measure.label, skimage.measure.euler_number and
skimage.morphology.local_minima use ndim by default (8 in 2D), but
skimage.segmentation.watershed, skimage.morphology.remove_small_objects
and remove_small_holes use 1 (4 in 2D). digitopo has no default: give
the connectivity in both libraries, and convert it.
Grey levels: the connectivity of the minima¶
In digitopo.grayscale and digitopo.watershed, connectivity is the
connectivity of the minima, as in Pink: the bright regions use the
complementary one. On a 0/255 image, connectivity=4 thins the object as
an 8-connected object:
# On a 0/255 image, the grey-level connectivity is the one of the minima,
# that is of the background: 4 thins the object as an 8-connected one.
object_mask = mask.copy()
kernel = grayscale.homotopic_kernel(object_mask, 4, convert=True)
print("kernel (minima 4) keeps the 8-topology of the object:",
topology.topology(kernel > 0, 8) == topology.topology(object_mask, 8))
Grey levels: uint8 and floats¶
The grey-level functions take uint8 images, as in pink26. With
convert=True, they also take the images of scikit-image, through
digitopo.interop.as_uint8:
- floats in [0, 1]:
vbecomesrint(255 * v), as withskimage.util.img_as_ubyte; bool: 0 and 255;- other integers: kept, if they lie between 0 and 255.
NaN, floats outside [0, 1] and integers outside 0..255 raise
DigitopoError instead of being clipped. The result stays uint8.
coins = data.coins() / 255.0 # floats in [0, 1], as in scikit-image
gradient = filters.sobel(coins)
print("sobel: float", gradient.dtype, "from", round(float(gradient.min()), 3),
"to", round(float(gradient.max()), 3))
lowered = watershed.topological_watershed(gradient, 4, convert=True)
print("same as as_uint8 first:", bool((lowered == watershed.topological_watershed(
interop.as_uint8(gradient), 4)).all()))
try:
watershed.topological_watershed(gradient, 4)
except TypeError as error:
print("without convert:", error)
sobel: float float64 from 0.0 to 0.59
same as as_uint8 first: True
without convert: unsupported dtype float64: expected uint8
The 256 levels merge close values of a float image. On the plateaus that this creates, the place of a crest line depends on the order in which digitopo visits the points.
Watershed: labels, as in scikit-image¶
watershed_labels(image, markers, connectivity) takes the labelled markers
of skimage.segmentation.watershed and returns labels, 0 on the lines, as
watershed_line=True does. The image may be a float image in [0, 1]. The
lines are those of the topological watershed. Every connected region of
markers gets its own basin; the basins of the same label are then joined
through their lines, so that the lines left separate different labels
only.
Here, the coins of the scikit-image gallery: markers from two thresholds, and the watershed of the gradient.
# The coins of the scikit-image gallery: markers from two thresholds, and
# the watershed of the gradient (the "elevation map").
markers = np.zeros(coins.shape, dtype=np.int32)
markers[coins < 30 / 255] = 1 # background
markers[coins > 150 / 255] = 2 # coins
ours = watershed.watershed_labels(gradient, markers, 4)
theirs = segmentation.watershed(gradient, markers, connectivity=1, watershed_line=True)
print("same label on", f"{np.mean(ours == theirs):.1%}", "of the points;",
"coins:", measure.label(ours == 2, connectivity=1).max(), "and",
measure.label(theirs == 2, connectivity=1).max())
print("line points:", int((ours == 0).sum()), "and", int((theirs == 0).sum()))
Two choices differ from watershed_lines, which follows pink26:
- the markers are the only points at level 0: two markers joined through points at 0 get two basins, separated by a line;
- the points of a marker that touch a marker of another label are no longer
markers, since two touching markers would form one minimum, hence one
basin. The line between the two basins runs through their contact. A
label whose points all touch other labels raises
DigitopoError.
scikit-image has a mask argument; watershed_labels has none. To
separate touching objects, give the background a marker of its own, then
drop it:
# Touching discs: one marker per centre, and one marker for the background.
discs = np.zeros((80, 120), dtype=bool)
yy, xx = np.mgrid[:80, :120]
for cy, cx in ((40, 30), (40, 72), (36, 98)):
discs |= (yy - cy) ** 2 + (xx - cx) ** 2 < 21**2
depth = ndi.distance_transform_edt(discs)
relief = 1.0 - depth / depth.max() # floats in [0, 1]
markers = np.zeros(discs.shape, dtype=np.int32)
markers[~ndi.binary_dilation(discs, iterations=2)] = 1 # the background
for label, (y, x) in enumerate(feature.peak_local_max(depth, min_distance=10,
labels=discs), start=2):
markers[y, x] = label
cells = watershed.watershed_labels(relief, markers, 4)
cells[(cells == 1) | ~discs] = 0 # drop the background
print("cells:", len(np.unique(cells)) - 1, "| each one 4-connected component:",
all(measure.label(cells == k, connectivity=1).max() == 1 for k in np.unique(cells)[1:]))
Distance maps¶
digitopo.distance.distance_map returns squared distances, in int32,
and the outside of the array is background: a point on the side of the
array is at distance 1. scipy.ndimage.distance_transform_edt only looks
at the zeros of the array. Pad the mask with zeros to get the same values:
square = np.zeros((7, 9), dtype=bool)
square[:, 2:7] = True # touches the top and bottom sides
ours = distance.distance_map(square) # squared distances, int32
plain = ndi.distance_transform_edt(square) # only the zeros of the array
framed = ndi.distance_transform_edt(np.pad(square, 1))[1:-1, 1:-1]
print("sqrt(distance_map) == edt:", bool(np.allclose(np.sqrt(ours), plain)))
print("sqrt(distance_map) == edt of the padded mask:", bool(np.allclose(np.sqrt(ours), framed)))
For a physical spacing, use ndi.distance_transform_edt(..., sampling=...);
the lengths of digitopo.measure.branches take a spacing.
The whole script
# SPDX-License-Identifier: CECILL-2.1
# Examples of docs/examples/scikit-image.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/scikit_image.py
import digitopo
import numpy as np
from digitopo import distance, grayscale, interop, topology, watershed
from scipy import ndimage as ndi
from skimage import data, feature, filters, measure, segmentation
rng = np.random.default_rng(0)
mask = ndi.gaussian_filter(rng.random((128, 128)), 3) > 0.5
for value in (4, 8):
rank = digitopo.skimage_connectivity(2, value) # 1 for 4, 2 for 8
objects = measure.label(mask, connectivity=rank).max()
euler = measure.euler_number(mask, connectivity=rank)
print(f"digitopo {value} = scikit-image {rank}:",
"objects", topology.topology(mask, value).objects, objects,
"| Euler", topology.euler_characteristic(mask, value), euler)
print("scikit-image 2 in 3D =", digitopo.connectivity(3, 2))
# On a 0/255 image, the grey-level connectivity is the one of the minima,
# that is of the background: 4 thins the object as an 8-connected one.
object_mask = mask.copy()
kernel = grayscale.homotopic_kernel(object_mask, 4, convert=True)
print("kernel (minima 4) keeps the 8-topology of the object:",
topology.topology(kernel > 0, 8) == topology.topology(object_mask, 8))
coins = data.coins() / 255.0 # floats in [0, 1], as in scikit-image
gradient = filters.sobel(coins)
print("sobel: float", gradient.dtype, "from", round(float(gradient.min()), 3),
"to", round(float(gradient.max()), 3))
lowered = watershed.topological_watershed(gradient, 4, convert=True)
print("same as as_uint8 first:", bool((lowered == watershed.topological_watershed(
interop.as_uint8(gradient), 4)).all()))
try:
watershed.topological_watershed(gradient, 4)
except TypeError as error:
print("without convert:", error)
# The coins of the scikit-image gallery: markers from two thresholds, and
# the watershed of the gradient (the "elevation map").
markers = np.zeros(coins.shape, dtype=np.int32)
markers[coins < 30 / 255] = 1 # background
markers[coins > 150 / 255] = 2 # coins
ours = watershed.watershed_labels(gradient, markers, 4)
theirs = segmentation.watershed(gradient, markers, connectivity=1, watershed_line=True)
print("same label on", f"{np.mean(ours == theirs):.1%}", "of the points;",
"coins:", measure.label(ours == 2, connectivity=1).max(), "and",
measure.label(theirs == 2, connectivity=1).max())
print("line points:", int((ours == 0).sum()), "and", int((theirs == 0).sum()))
# Touching discs: one marker per centre, and one marker for the background.
discs = np.zeros((80, 120), dtype=bool)
yy, xx = np.mgrid[:80, :120]
for cy, cx in ((40, 30), (40, 72), (36, 98)):
discs |= (yy - cy) ** 2 + (xx - cx) ** 2 < 21**2
depth = ndi.distance_transform_edt(discs)
relief = 1.0 - depth / depth.max() # floats in [0, 1]
markers = np.zeros(discs.shape, dtype=np.int32)
markers[~ndi.binary_dilation(discs, iterations=2)] = 1 # the background
for label, (y, x) in enumerate(feature.peak_local_max(depth, min_distance=10,
labels=discs), start=2):
markers[y, x] = label
cells = watershed.watershed_labels(relief, markers, 4)
cells[(cells == 1) | ~discs] = 0 # drop the background
print("cells:", len(np.unique(cells)) - 1, "| each one 4-connected component:",
all(measure.label(cells == k, connectivity=1).max() == 1 for k in np.unique(cells)[1:]))
square = np.zeros((7, 9), dtype=bool)
square[:, 2:7] = True # touches the top and bottom sides
ours = distance.distance_map(square) # squared distances, int32
plain = ndi.distance_transform_edt(square) # only the zeros of the array
framed = ndi.distance_transform_edt(np.pad(square, 1))[1:-1, 1:-1]
print("sqrt(distance_map) == edt:", bool(np.allclose(np.sqrt(ours), plain)))
print("sqrt(distance_map) == edt of the padded mask:", bool(np.allclose(np.sqrt(ours), framed)))