{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Comparison of segmentation and superpixel algorithms\n\nThis example compares four popular low-level image segmentation methods.  As\nit is difficult to obtain good segmentations, and the definition of \"good\"\noften depends on the application, these methods are usually used for obtaining\nan oversegmentation, also known as superpixels. These superpixels then serve as\na basis for more sophisticated algorithms such as conditional random fields\n(CRF).\n\n\n## Felzenszwalb's efficient graph based segmentation\nThis fast 2D image segmentation algorithm, proposed in [1]_ is popular in the\ncomputer vision community.\nThe algorithm has a single ``scale`` parameter that influences the segment\nsize. The actual size and number of segments can vary greatly, depending on\nlocal contrast.\n\n.. [1] Efficient graph-based image segmentation, Felzenszwalb, P.F. and\n       Huttenlocher, D.P.  International Journal of Computer Vision, 2004\n\n\n## Quickshift image segmentation\n\nQuickshift is a relatively recent 2D image segmentation algorithm, based on an\napproximation of kernelized mean-shift. Therefore it belongs to the family of\nlocal mode-seeking algorithms and is applied to the 5D space consisting of\ncolor information and image location [2]_.\n\nOne of the benefits of quickshift is that it actually computes a\nhierarchical segmentation on multiple scales simultaneously.\n\nQuickshift has two main parameters: ``sigma`` controls the scale of the local\ndensity approximation, ``max_dist`` selects a level in the hierarchical\nsegmentation that is produced. There is also a trade-off between distance in\ncolor-space and distance in image-space, given by ``ratio``.\n\n.. [2] Quick shift and kernel methods for mode seeking,\n       Vedaldi, A. and Soatto, S.\n       European Conference on Computer Vision, 2008\n\n\n## SLIC - K-Means based image segmentation\n\nThis algorithm simply performs K-means in the 5d space of color information and\nimage location and is therefore closely related to quickshift. As the\nclustering method is simpler, it is very efficient. It is essential for this\nalgorithm to work in Lab color space to obtain good results.  The algorithm\nquickly gained momentum and is now widely used. See [3]_ for details.  The\n``compactness`` parameter trades off color-similarity and proximity, as in the\ncase of Quickshift, while ``n_segments`` chooses the number of centers for\nkmeans.\n\n.. [3] Radhakrishna Achanta, Appu Shaji, Kevin Smith, Aurelien Lucchi,\n    Pascal Fua, and Sabine Suesstrunk, SLIC Superpixels Compared to\n    State-of-the-art Superpixel Methods, TPAMI, May 2012.\n\n\n## Compact watershed segmentation of gradient images\n\nInstead of taking a color image as input, watershed requires a grayscale\n*gradient* image, where bright pixels denote a boundary between regions.\nThe algorithm views the image as a landscape, with bright pixels forming high\npeaks. This landscape is then flooded from the given *markers*, until separate\nflood basins meet at the peaks. Each distinct basin then forms a different\nimage segment. [4]_\n\nAs with SLIC, there is an additional *compactness* argument that makes it\nharder for markers to flood faraway pixels. This makes the watershed regions\nmore regularly shaped. [5]_\n\n.. [4] https://en.wikipedia.org/wiki/Watershed_%28image_processing%29\n\n.. [5] Peer Neubert & Peter Protzel (2014). Compact Watershed and\n       Preemptive SLIC: On Improving Trade-offs of Superpixel Segmentation\n       Algorithms. ICPR 2014, pp 996-1001. :DOI:`10.1109/ICPR.2014.181`\n       https://www.tu-chemnitz.de/etit/proaut/publications/cws_pSLIC_ICPR.pdf\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import matplotlib.pyplot as plt\nimport numpy as np\n\nfrom skimage.data import astronaut\nfrom skimage.color import rgb2gray\nfrom skimage.filters import sobel\nfrom skimage.segmentation import felzenszwalb, slic, quickshift, watershed\nfrom skimage.segmentation import mark_boundaries\nfrom skimage.util import img_as_float\n\nimg = img_as_float(astronaut()[::2, ::2])\n\nsegments_fz = felzenszwalb(img, scale=100, sigma=0.5, min_size=50)\nsegments_slic = slic(img, n_segments=250, compactness=10, sigma=1, start_label=1)\nsegments_quick = quickshift(img, kernel_size=3, max_dist=6, ratio=0.5)\ngradient = sobel(rgb2gray(img))\nsegments_watershed = watershed(gradient, markers=250, compactness=0.001)\n\nprint(f'Felzenszwalb number of segments: {len(np.unique(segments_fz))}')\nprint(f'SLIC number of segments: {len(np.unique(segments_slic))}')\nprint(f'Quickshift number of segments: {len(np.unique(segments_quick))}')\nprint(f'Watershed number of segments: {len(np.unique(segments_watershed))}')\n\nfig, ax = plt.subplots(2, 2, figsize=(10, 10), sharex=True, sharey=True)\n\nax[0, 0].imshow(mark_boundaries(img, segments_fz))\nax[0, 0].set_title(\"Felzenszwalbs's method\")\nax[0, 1].imshow(mark_boundaries(img, segments_slic))\nax[0, 1].set_title('SLIC')\nax[1, 0].imshow(mark_boundaries(img, segments_quick))\nax[1, 0].set_title('Quickshift')\nax[1, 1].imshow(mark_boundaries(img, segments_watershed))\nax[1, 1].set_title('Compact watershed')\n\nfor a in ax.ravel():\n    a.set_axis_off()\n\nplt.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
}