{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Comparing edge-based and region-based segmentation\n\nIn this example, we will see how to segment objects from a background. We use\nthe ``coins`` image from ``skimage.data``, which shows several coins outlined\nagainst a darker background.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import numpy as np\nimport matplotlib.pyplot as plt\n\nimport skimage as ski\n\ncoins = ski.data.coins()\nhist, hist_centers = ski.exposure.histogram(coins)\n\nfig, axes = plt.subplots(1, 2, figsize=(8, 3))\naxes[0].imshow(coins, cmap=plt.cm.gray)\naxes[0].set_axis_off()\naxes[1].plot(hist_centers, hist, lw=2)\naxes[1].set_title('histogram of gray values')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Thresholding\n\nA simple way to segment the coins is to choose a threshold based on the\nhistogram of gray values. Unfortunately, thresholding this image gives a\nbinary image that either misses significant parts of the coins or merges\nparts of the background with the coins:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "fig, axes = plt.subplots(1, 2, figsize=(8, 3), sharey=True)\n\naxes[0].imshow(coins > 100, cmap=plt.cm.gray)\naxes[0].set_title('coins > 100')\n\naxes[1].imshow(coins > 150, cmap=plt.cm.gray)\naxes[1].set_title('coins > 150')\n\nfor a in axes:\n    a.set_axis_off()\n\nfig.tight_layout()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Edge-based segmentation\n\nNext, we try to delineate the contours of the coins using edge-based\nsegmentation. To do this, we first get the edges of features using the\nCanny edge-detector.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "edges = ski.feature.canny(coins)\n\nfig, ax = plt.subplots(figsize=(4, 3))\nax.imshow(edges, cmap=plt.cm.gray)\nax.set_title('Canny detector')\nax.set_axis_off()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "These contours are then filled using mathematical morphology.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from scipy import ndimage as ndi\n\nfill_coins = ndi.binary_fill_holes(edges)\n\nfig, ax = plt.subplots(figsize=(4, 3))\nax.imshow(fill_coins, cmap=plt.cm.gray)\nax.set_title('filling the holes')\nax.set_axis_off()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Small spurious objects are easily removed by setting a minimum size for\nvalid objects.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "coins_cleaned = ski.morphology.remove_small_objects(fill_coins, max_size=20)\n\nfig, ax = plt.subplots(figsize=(4, 3))\nax.imshow(coins_cleaned, cmap=plt.cm.gray)\nax.set_title('removing small objects')\nax.set_axis_off()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "However, this method is not very robust, since contours that are not\nperfectly closed are not filled correctly, as is the case for one unfilled\ncoin above.\n\n## Region-based segmentation\n\nWe therefore try a region-based method using the watershed transform.\nFirst, we find an elevation map using the Sobel gradient of the image.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "elevation_map = ski.filters.sobel(coins)\n\nfig, ax = plt.subplots(figsize=(4, 3))\nax.imshow(elevation_map, cmap=plt.cm.gray)\nax.set_title('elevation map')\nax.set_axis_off()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Next we find markers of the background and the coins based on the extreme\nparts of the histogram of gray values.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "markers = np.zeros_like(coins)\nmarkers[coins < 30] = 1\nmarkers[coins > 150] = 2\n\nfig, ax = plt.subplots(figsize=(4, 3))\nax.imshow(markers, cmap=plt.cm.nipy_spectral)\nax.set_title('markers')\nax.set_axis_off()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Finally, we use the watershed transform to fill regions of the elevation\nmap starting from the markers determined above:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "segmentation_coins = ski.segmentation.watershed(elevation_map, markers)\n\nfig, ax = plt.subplots(figsize=(4, 3))\nax.imshow(segmentation_coins, cmap=plt.cm.gray)\nax.set_title('segmentation')\nax.set_axis_off()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "This last method works even better, and the coins can be segmented and\nlabeled individually.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "segmentation_coins = ndi.binary_fill_holes(segmentation_coins - 1)\nlabeled_coins, _ = ndi.label(segmentation_coins)\nimage_label_overlay = ski.color.label2rgb(labeled_coins, image=coins, bg_label=0)\n\nfig, axes = plt.subplots(1, 2, figsize=(8, 3), sharey=True)\naxes[0].imshow(coins, cmap=plt.cm.gray)\naxes[0].contour(segmentation_coins, [0.5], linewidths=1.2, colors='y')\naxes[1].imshow(image_label_overlay)\n\nfor a in axes:\n    a.set_axis_off()\n\nfig.tight_layout()\n\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
}