{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Random walker segmentation\n\nThe random walker algorithm [1]_  determines the segmentation of an image from\na set of markers labeling several phases (2 or more). An anisotropic diffusion\nequation is solved with tracers initiated at the markers' position. The local\ndiffusivity coefficient is greater if neighboring pixels have similar values,\nso that diffusion is difficult across high gradients. The label of each unknown\npixel is attributed to the label of the known marker that has the highest\nprobability to be reached first during this diffusion process.\n\nIn this example, two phases are clearly visible, but the data are too\nnoisy to perform the segmentation from the histogram only. We determine\nmarkers of the two phases from the extreme tails of the histogram of gray\nvalues, and use the random walker for the segmentation.\n\n.. [1] *Random walks for image segmentation*, Leo Grady, IEEE Trans. Pattern\n       Anal. Mach. Intell. 2006 Nov; 28(11):1768-83 :DOI:`10.1109/TPAMI.2006.233`\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import numpy as np\nimport matplotlib.pyplot as plt\n\nfrom skimage.segmentation import random_walker\nfrom skimage.data import binary_blobs\nfrom skimage.exposure import rescale_intensity\nimport skimage\n\nrng = np.random.default_rng()\n\n# Generate noisy synthetic data\ndata = skimage.img_as_float(binary_blobs(length=128, rng=1))\nsigma = 0.35\ndata += rng.normal(loc=0, scale=sigma, size=data.shape)\ndata = rescale_intensity(data, in_range=(-sigma, 1 + sigma), out_range=(-1, 1))\n\n# The range of the binary image spans over (-1, 1).\n# We choose the hottest and the coldest pixels as markers.\nmarkers = np.zeros(data.shape, dtype=np.uint)\nmarkers[data < -0.95] = 1\nmarkers[data > 0.95] = 2\n\n# Run random walker algorithm\nlabels = random_walker(data, markers, beta=10, mode='bf')\n\n# Plot results\nfig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(8, 3.2), sharex=True, sharey=True)\nax1.imshow(data, cmap='gray')\nax1.axis('off')\nax1.set_title('Noisy data')\nax2.imshow(markers, cmap='magma')\nax2.axis('off')\nax2.set_title('Markers')\nax3.imshow(labels, cmap='gray')\nax3.axis('off')\nax3.set_title('Segmentation')\n\nfig.tight_layout()\nplt.show()"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.12.12"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}