{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Niblack and Sauvola Thresholding\n\nNiblack and Sauvola thresholds are local thresholding techniques that are\nuseful for images where the background is not uniform, especially for text\nrecognition [1]_, [2]_. Instead of calculating a single global threshold for\nthe entire image, several thresholds are calculated for every pixel by using\nspecific formulae that take into account the mean and standard deviation of the\nlocal neighborhood (defined by a window centered around the pixel).\n\nHere, we binarize an image using these algorithms compare it to a common global\nthresholding technique. Parameter `window_size` determines the size of the\nwindow that contains the surrounding pixels.\n\n.. [1] Niblack, W (1986), An introduction to Digital Image\n       Processing, Prentice-Hall.\n.. [2] J. Sauvola and M. Pietikainen, \"Adaptive document image\n       binarization,\" Pattern Recognition 33(2),\n       pp. 225-236, 2000.\n       :DOI:`10.1016/S0031-3203(99)00055-2`\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import matplotlib\nimport matplotlib.pyplot as plt\n\nfrom skimage.data import page\nfrom skimage.filters import threshold_otsu, threshold_niblack, threshold_sauvola\n\n\nmatplotlib.rcParams['font.size'] = 9\n\n\nimage = page()\nbinary_global = image > threshold_otsu(image)\n\nwindow_size = 25\nthresh_niblack = threshold_niblack(image, window_size=window_size, k=0.8)\nthresh_sauvola = threshold_sauvola(image, window_size=window_size)\n\nbinary_niblack = image > thresh_niblack\nbinary_sauvola = image > thresh_sauvola\n\nfig, axes = plt.subplots(nrows=2, ncols=2, figsize=(8, 7))\n\naxes[0, 0] = plt.subplot(2, 2, 1)\naxes[0, 0].imshow(image, cmap=plt.cm.gray)\naxes[0, 0].set_title('Original')\naxes[0, 0].axis('off')\n\naxes[0, 1] = plt.subplot(2, 2, 2)\naxes[0, 1].imshow(binary_global, cmap=plt.cm.gray)\naxes[0, 1].set_title('Global Threshold')\naxes[0, 1].axis('off')\n\naxes[1, 0] = plt.subplot(2, 2, 3)\naxes[1, 0].imshow(binary_niblack, cmap=plt.cm.gray)\naxes[1, 0].set_title('Niblack Threshold')\naxes[1, 0].axis('off')\n\naxes[1, 1] = plt.subplot(2, 2, 4)\naxes[1, 1].imshow(binary_sauvola, cmap=plt.cm.gray)\naxes[1, 1].set_title('Sauvola Threshold')\naxes[1, 1].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
}