{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Watershed segmentation\n\nThe watershed is a classical algorithm used for **segmentation**, that\nis, for separating different objects in an image.\n\nStarting from user-defined markers, the watershed algorithm treats\npixels values as a local topography (elevation). The algorithm floods\nbasins from the markers until basins attributed to different markers\nmeet on watershed lines.  In many cases, markers are chosen as local\nminima of the image, from which basins are flooded.\n\nIn the example below, two overlapping circles are to be separated. To\ndo so, one computes an image that is the distance to the\nbackground. The maxima of this distance (i.e., the minima of the\nopposite of the distance) are chosen as markers and the flooding of\nbasins from such markers separates the two circles along a watershed\nline.\n\nSee Wikipedia_ for more details on the algorithm.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import ndimage as ndi\n\nfrom skimage.segmentation import watershed\nfrom skimage.feature import peak_local_max\n\n\n# Generate an initial image with two overlapping circles\nx, y = np.indices((80, 80))\nx1, y1, x2, y2 = 28, 28, 44, 52\nr1, r2 = 16, 20\nmask_circle1 = (x - x1) ** 2 + (y - y1) ** 2 < r1**2\nmask_circle2 = (x - x2) ** 2 + (y - y2) ** 2 < r2**2\nimage = np.logical_or(mask_circle1, mask_circle2)\n\n# Now we want to separate the two objects in image\n# Generate the markers as local maxima of the distance to the background\ndistance = ndi.distance_transform_edt(image)\ncoords = peak_local_max(distance, footprint=np.ones((3, 3)), labels=image)\nmask = np.zeros(distance.shape, dtype=bool)\nmask[tuple(coords.T)] = True\nmarkers, _ = ndi.label(mask)\nlabels = watershed(-distance, markers, mask=image)\n\nfig, axes = plt.subplots(ncols=3, figsize=(9, 3), sharex=True, sharey=True)\nax = axes.ravel()\n\nax[0].imshow(image, cmap=plt.cm.gray)\nax[0].set_title('Overlapping objects')\nax[1].imshow(-distance, cmap=plt.cm.gray)\nax[1].set_title('Distances')\nax[2].imshow(labels, cmap=plt.cm.nipy_spectral)\nax[2].set_title('Separated objects')\n\nfor a in ax:\n    a.set_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
}