# 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

# --8<-- [start:connectivity]
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))
# --8<-- [end:connectivity]

# --8<-- [start:minima]
# 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))
# --8<-- [end:minima]

# --8<-- [start:floats]
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)
# --8<-- [end:floats]

# --8<-- [start:labels]
# 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()))
# --8<-- [end:labels]

# --8<-- [start:touching]
# 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:]))
# --8<-- [end:touching]

# --8<-- [start:distance]
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)))
# --8<-- [end:distance]
