{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Thresholding\n\nThresholding is used to create a binary image from a grayscale image [1]_.\nIt is the simplest way to segment objects from a background.\n\nThresholding algorithms implemented in scikit-image can be separated in two\ncategories:\n\n- Histogram-based. The histogram of the pixels' intensity is used and\n  certain assumptions are made on the properties of this histogram (e.g. bimodal).\n- Local. To process a pixel, only the neighboring pixels are used.\n  These algorithms often require more computation time.\n\n\nIf you are not familiar with the details of the different algorithms and the\nunderlying assumptions, it is often difficult to know which algorithm will give\nthe best results. Therefore, Scikit-image includes a function to evaluate\nthresholding algorithms provided by the library. At a glance, you can select\nthe best algorithm for you data without a deep understanding of their\nmechanisms.\n\n.. [1] https://en.wikipedia.org/wiki/Thresholding_%28image_processing%29\n\n.. seealso::\n   Presentation on\n   `sphx_glr_auto_examples_applications_plot_rank_filters.py`.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import matplotlib.pyplot as plt\n\nimport skimage as ski\n\nimg = ski.data.page()\n\nfig, ax = ski.filters.try_all_threshold(img, figsize=(10, 8), verbose=False)\n\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## How to apply a threshold?\n\nNow, we illustrate how to apply one of these thresholding algorithms.\nThis example uses the mean value of pixel intensities. It is a simple\nand naive threshold value, which is sometimes used as a guess value.\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "image = ski.data.camera()\nthresh = ski.filters.threshold_mean(image)\nbinary = image > thresh\n\nfig, axes = plt.subplots(ncols=2, figsize=(8, 3))\nax = axes.ravel()\n\nax[0].imshow(image, cmap=plt.cm.gray)\nax[0].set_title('Original image')\n\nax[1].imshow(binary, cmap=plt.cm.gray)\nax[1].set_title('Result')\n\nfor a in ax:\n    a.set_axis_off()\n\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Bimodal histogram\n\nFor pictures with a bimodal histogram, more specific algorithms can be used.\nFor instance, the minimum algorithm takes a histogram of the image and smooths it\nrepeatedly until there are only two peaks in the histogram.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "image = ski.data.camera()\n\nthresh_min = ski.filters.threshold_minimum(image)\nbinary_min = image > thresh_min\n\nfig, ax = plt.subplots(2, 2, figsize=(10, 10))\n\nax[0, 0].imshow(image, cmap=plt.cm.gray)\nax[0, 0].set_title('Original')\n\nax[0, 1].hist(image.ravel(), bins=256)\nax[0, 1].set_title('Histogram')\n\nax[1, 0].imshow(binary_min, cmap=plt.cm.gray)\nax[1, 0].set_title('Thresholded (min)')\n\nax[1, 1].hist(image.ravel(), bins=256)\nax[1, 1].axvline(thresh_min, color='r')\n\nfor a in ax[:, 0]:\n    a.set_axis_off()\n\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Otsu's method [2]_ calculates an \"optimal\" threshold (marked by a red line in the\nhistogram below) by maximizing the variance between two classes of pixels,\nwhich are separated by the threshold. Equivalently, this threshold minimizes\nthe intra-class variance.\n\n.. [2] https://en.wikipedia.org/wiki/Otsu's_method\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "image = ski.data.camera()\nthresh = ski.filters.threshold_otsu(image)\nbinary = image > thresh\n\nfig, ax = plt.subplots(ncols=3, figsize=(8, 2.5))\n\nax[0].imshow(image, cmap=plt.cm.gray)\nax[0].set_title('Original')\nax[0].axis('off')\n\nax[1].hist(image.ravel(), bins=256)\nax[1].set_title('Histogram')\nax[1].axvline(thresh, color='r')\n\nax[2].imshow(binary, cmap=plt.cm.gray)\nax[2].set_title('Thresholded')\nax[2].set_axis_off()\n\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Local thresholding\n\nIf the image background is relatively uniform, then you can use a global\nthreshold value as presented above. However, if there is large variation in the\nbackground intensity, adaptive thresholding (a.k.a. local or dynamic\nthresholding) may produce better results. Note that local is much slower than\nglobal thresholding.\n\nHere, we binarize an image using the `threshold_local` function, which\ncalculates thresholds in regions with a characteristic size `block_size` surrounding\neach pixel (i.e. local neighborhoods). Each threshold value is the weighted mean\nof the local neighborhood minus an offset value.\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "image = ski.data.page()\n\nglobal_thresh = ski.filters.threshold_otsu(image)\nbinary_global = image > global_thresh\n\nblock_size = 35\nlocal_thresh = ski.filters.threshold_local(image, block_size, offset=10)\nbinary_local = image > local_thresh\n\nfig, axes = plt.subplots(nrows=3, figsize=(7, 8))\nax = axes.ravel()\nplt.gray()\n\nax[0].imshow(image)\nax[0].set_title('Original')\n\nax[1].imshow(binary_global)\nax[1].set_title('Global thresholding')\n\nax[2].imshow(binary_local)\nax[2].set_title('Local thresholding')\n\nfor a in ax:\n    a.set_axis_off()\n\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Now, we show how Otsu's threshold [2]_ method can be applied locally. For\neach pixel, an \"optimal\" threshold is determined by maximizing the variance\nbetween two classes of pixels of the local neighborhood defined by a\nstructuring element.\n\nThe example compares the local threshold with the global threshold.\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "img = ski.util.img_as_ubyte(ski.data.page())\n\nradius = 15\nfootprint = ski.morphology.disk(radius)\n\nlocal_otsu = ski.filters.rank.otsu(img, footprint)\nthreshold_global_otsu = ski.filters.threshold_otsu(img)\nglobal_otsu = img >= threshold_global_otsu\n\nfig, axes = plt.subplots(2, 2, figsize=(8, 5), sharex=True, sharey=True)\nax = axes.ravel()\nfig.tight_layout()\n\nfig.colorbar(ax[0].imshow(img, cmap=plt.cm.gray), ax=ax[0], orientation='horizontal')\nax[0].set_title('Original')\nax[0].set_axis_off()\n\nfig.colorbar(\n    ax[1].imshow(local_otsu, cmap=plt.cm.gray), ax=ax[1], orientation='horizontal'\n)\nax[1].set_title(f'Local Otsu (radius={radius})')\nax[1].set_axis_off()\n\nax[2].imshow(img >= local_otsu, cmap=plt.cm.gray)\nax[2].set_title('Original >= Local Otsu')\nax[2].set_axis_off()\n\nax[3].imshow(global_otsu, cmap=plt.cm.gray)\nax[3].set_title(f'Global Otsu (threshold = {threshold_global_otsu})')\nax[3].set_axis_off()\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
}