{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Markers for watershed transform\n\nThe watershed is a classical algorithm used for **segmentation**, that\nis, for separating different objects in an image.\n\nHere a marker image is built from the region of low gradient inside the image.\nIn a gradient image, the areas of high values provide barriers that help to\nsegment the image.\nUsing markers on the lower values will ensure that the segmented objects are\nfound.\n\nSee Wikipedia_ for more details on the algorithm.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from scipy import ndimage as ndi\nimport matplotlib.pyplot as plt\n\nfrom skimage.morphology import disk\nfrom skimage.segmentation import watershed\nfrom skimage import data\nfrom skimage.filters import rank\nfrom skimage.util import img_as_ubyte\n\n\nimage = img_as_ubyte(data.eagle())\n\n# denoise image\ndenoised = rank.median(image, disk(2))\n\n# find continuous region (low gradient -\n# where less than 10 for this image) --> markers\n# disk(5) is used here to get a more smooth image\nmarkers = rank.gradient(denoised, disk(5)) < 10\nmarkers = ndi.label(markers)[0]\n\n# local gradient (disk(2) is used to keep edges thin)\ngradient = rank.gradient(denoised, disk(2))\n\n# process the watershed\nlabels = watershed(gradient, markers)\n\n# display results\nfig, axes = plt.subplots(nrows=2, ncols=2, figsize=(8, 8), sharex=True, sharey=True)\nax = axes.ravel()\n\nax[0].imshow(image, cmap=plt.cm.gray)\nax[0].set_title(\"Original\")\n\nax[1].imshow(gradient, cmap=plt.cm.nipy_spectral)\nax[1].set_title(\"Local Gradient\")\n\nax[2].imshow(markers, cmap=plt.cm.nipy_spectral)\nax[2].set_title(\"Markers\")\n\nax[3].imshow(image, cmap=plt.cm.gray)\nax[3].imshow(labels, cmap=plt.cm.nipy_spectral, alpha=0.5)\nax[3].set_title(\"Segmented\")\n\nfor a in ax:\n    a.axis('off')\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
}