{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Flood Fill\n\nFlood fill is an algorithm to identify and/or change adjacent values in an\nimage based on their similarity to an initial seed point [1]_. The conceptual\nanalogy is the 'paint bucket' tool in many graphic editors.\n\n.. [1] https://en.wikipedia.org/wiki/Flood_fill\n\n## Basic example\n\nFirst, a basic example where we will change a checkerboard square from white\nto mid-gray.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import numpy as np\nimport matplotlib.pyplot as plt\nfrom skimage import data, filters, color, morphology\nfrom skimage.segmentation import flood, flood_fill\n\n\ncheckers = data.checkerboard()\n\n# Fill a square near the middle with value 127, starting at index (76, 76)\nfilled_checkers = flood_fill(checkers, (76, 76), 127)\n\nfig, ax = plt.subplots(ncols=2, figsize=(10, 5))\n\nax[0].imshow(checkers, cmap=plt.cm.gray)\nax[0].set_title('Original')\n\nax[1].imshow(filled_checkers, cmap=plt.cm.gray)\nax[1].plot(76, 76, 'wo')  # seed point\nax[1].set_title('After flood fill')\n\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Advanced example\n\nBecause standard flood filling requires the neighbors to be strictly equal,\nits use is limited on real-world images with color gradients and noise.\nThe `tolerance` keyword argument widens the permitted range about the initial\nvalue, allowing use on real-world images.\n\nHere we will experiment a bit on the cameraman.  First, turning his coat from\ndark to light.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "cameraman = data.camera()\n\n# Change the cameraman's coat from dark to light (255).  The seed point is\n# chosen as (155, 150)\nlight_coat = flood_fill(cameraman, (155, 150), 255, tolerance=10)\nfig, ax = plt.subplots(ncols=2, figsize=(10, 5))\n\nax[0].imshow(cameraman, cmap=plt.cm.gray)\nax[0].set_title('Original')\nax[0].axis('off')\n\nax[1].imshow(light_coat, cmap=plt.cm.gray)\nax[1].plot(150, 155, 'ro')  # seed point\nax[1].set_title('After flood fill')\nax[1].axis('off')\n\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "The cameraman's  coat is in varying shades of gray. Only the parts of the coat\nmatching the shade near the seed value is changed.\n\n## Experimentation with tolerance\n\nTo get a better intuitive understanding of how the tolerance parameter\nworks, here is a set of images progressively increasing the parameter with\nseed point in the upper left corner.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "output = []\n\nfor i in range(8):\n    tol = 5 + 20 * i\n    output.append(flood_fill(cameraman, (0, 0), 255, tolerance=tol))\n\n# Initialize plot and place original image\nfig, ax = plt.subplots(nrows=3, ncols=3, figsize=(12, 12))\nax[0, 0].imshow(cameraman, cmap=plt.cm.gray)\nax[0, 0].set_title('Original')\nax[0, 0].axis('off')\n\n# Plot all eight different tolerances for comparison.\nfor i in range(8):\n    m, n = np.unravel_index(i + 1, (3, 3))\n    ax[m, n].imshow(output[i], cmap=plt.cm.gray)\n    ax[m, n].set_title(f'Tolerance {5 + 20 * i}')\n    ax[m, n].axis('off')\n    ax[m, n].plot(0, 0, 'bo')  # seed point\n\nfig.tight_layout()\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Flood as mask\n\nA sister function, `flood`, is available which returns a mask identifying\nthe flood rather than modifying the image itself.  This is useful for\nsegmentation purposes and more advanced analysis pipelines.\n\nHere we segment the nose of a cat.  However, multi-channel images are not\nsupported by flood[_fill].  Instead we Sobel filter the red channel to\nenhance edges, then flood the nose with a tolerance.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "cat = data.chelsea()\ncat_sobel = filters.sobel(cat[..., 0])\ncat_nose = flood(cat_sobel, (240, 265), tolerance=0.03)\n\nfig, ax = plt.subplots(nrows=3, figsize=(10, 20))\n\nax[0].imshow(cat)\nax[0].set_title('Original')\nax[0].axis('off')\n\nax[1].imshow(cat_sobel)\nax[1].set_title('Sobel filtered')\nax[1].axis('off')\n\nax[2].imshow(cat)\nax[2].imshow(cat_nose, cmap=plt.cm.gray, alpha=0.3)\nax[2].plot(265, 240, 'wo')  # seed point\nax[2].set_title('Nose segmented with `flood`')\nax[2].axis('off')\n\nfig.tight_layout()\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Flood-fill in HSV space and mask post-processing\n\nSince flood fill operates on single-channel images, we transform here the\nimage to the HSV (Hue Saturation Value) space in order to flood pixels of\nsimilar hue.\n\nIn this example we also show that it is possible to post-process the binary\nmask returned by :func:`skimage.segmentation.flood` thanks to the functions\nof :mod:`skimage.morphology`.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "img = data.astronaut()\nimg_hsv = color.rgb2hsv(img)\nimg_hsv_copy = np.copy(img_hsv)\n\n# flood function returns a mask of flooded pixels\nmask = flood(img_hsv[..., 0], (313, 160), tolerance=0.016)\n# Set pixels of mask to new value for hue channel\nimg_hsv[mask, 0] = 0.5\n# Post-processing in order to improve the result\n# Remove white pixels from flag, using saturation channel\nmask_postprocessed = np.logical_and(mask, img_hsv_copy[..., 1] > 0.4)\n# Remove thin structures with binary opening\nmask_postprocessed = morphology.opening(mask_postprocessed, np.ones((3, 3)))\n# Fill small holes with binary closing\nmask_postprocessed = morphology.closing(mask_postprocessed, morphology.disk(20))\nimg_hsv_copy[mask_postprocessed, 0] = 0.5\n\nfig, ax = plt.subplots(1, 2, figsize=(8, 4))\nax[0].imshow(color.hsv2rgb(img_hsv))\nax[0].axis('off')\nax[0].set_title('After flood fill')\nax[1].imshow(color.hsv2rgb(img_hsv_copy))\nax[1].axis('off')\nax[1].set_title('After flood fill and post-processing')\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
}