{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Morphological Filtering\n\nMorphological image processing is a collection of non-linear operations related\nto the shape or morphology of features in an image, such as boundaries,\nskeletons, etc. In any given technique, we probe an image with a small shape or\ntemplate called a structuring element, which defines the region of interest or\nneighborhood around a pixel.\n\nIn this document we outline the following basic morphological operations:\n\n1. Erosion\n2. Dilation\n3. Opening\n4. Closing\n5. White Tophat\n6. Black Tophat\n7. Skeletonize\n8. Convex Hull\n\n\nTo get started, let's load an image using ``io.imread``. Note that morphology\nfunctions only work on gray-scale or binary images, so we set ``as_gray=True``.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import matplotlib.pyplot as plt\nimport skimage as ski\n\norig_phantom = ski.util.img_as_ubyte(ski.data.shepp_logan_phantom())\nfig, ax = plt.subplots()\nax.imshow(orig_phantom, cmap=plt.cm.gray)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Let's also define a convenience function for plotting comparisons:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "def plot_comparison(original, filtered, filter_name):\n    fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(8, 4), sharex=True, sharey=True)\n    ax1.imshow(original, cmap=plt.cm.gray)\n    ax1.set_title('original')\n    ax1.set_axis_off()\n    ax2.imshow(filtered, cmap=plt.cm.gray)\n    ax2.set_title(filter_name)\n    ax2.set_axis_off()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Erosion\n\nMorphological ``erosion`` sets a pixel at (i, j) to the *minimum over all\npixels in the neighborhood centered at (i, j)*. The structuring element,\n``footprint``, passed to ``erosion`` is a boolean array that describes this\nneighborhood. Below, we use ``disk`` to create a circular structuring\nelement, which we use for most of the following examples.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "footprint = ski.morphology.disk(6)\neroded = ski.morphology.erosion(orig_phantom, footprint)\nplot_comparison(orig_phantom, eroded, 'erosion')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Notice how the white boundary of the image disappears or gets eroded as we\nincrease the size of the disk. Also notice the increase in size of the two\nblack ellipses in the center and the disappearance of the 3 light gray\npatches in the lower part of the image.\n\n## Dilation\n\nMorphological ``dilation`` sets a pixel at (i, j) to the *maximum over all\npixels in the neighborhood centered at (i, j)*. Dilation enlarges bright\nregions and shrinks dark regions.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "dilated = ski.morphology.dilation(orig_phantom, footprint)\nplot_comparison(orig_phantom, dilated, 'dilation')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Notice how the white boundary of the image thickens, or gets dilated, as we\nincrease the size of the disk. Also notice the decrease in size of the two\nblack ellipses in the center, and the thickening of the light gray circle\nin the center and the 3 patches in the lower part of the image.\n\n## Opening\n\nMorphological ``opening`` on an image is defined as an *erosion followed by\na dilation*. Opening can remove small bright spots (i.e. \"salt\") and\nconnect small dark cracks.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "opened = ski.morphology.opening(orig_phantom, footprint)\nplot_comparison(orig_phantom, opened, 'opening')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Since ``opening`` an image starts with an erosion operation, light regions\nthat are *smaller* than the structuring element are removed. The dilation\noperation that follows ensures that light regions that are *larger* than\nthe structuring element retain their original size. Notice how the light\nand dark shapes in the center retain their original thickness but the 3 lighter\npatches in the bottom get completely eroded. The size dependence is\nhighlighted by the outer white ring: The parts of the ring thinner than the\nstructuring element are completely erased, while the thicker region at the\ntop retains its original thickness.\n\n## Closing\n\nMorphological ``closing`` on an image is defined as a *dilation followed by\nan erosion*. Closing can remove small dark spots (i.e. \"pepper\") and\nconnect small bright cracks.\n\nTo illustrate this more clearly, let's add a small crack to the white\nborder:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "phantom = orig_phantom.copy()\nphantom[10:30, 200:210] = 0\n\nclosed = ski.morphology.closing(phantom, footprint)\nplot_comparison(phantom, closed, 'closing')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Since ``closing`` an image starts with a dilation operation, dark regions\nthat are *smaller* than the structuring element are removed. The erosion\noperation that follows ensures that dark regions that are *larger* than the\nstructuring element retain their original size. Notice how the white\nellipses at the bottom get connected because of dilation, but other dark\nregions retain their original sizes. Also notice how the crack we added is\nmostly removed.\n\n## White tophat\n\nThe ``white_tophat`` of an image is defined as the *image minus its\nmorphological opening*. This operation returns the bright spots of the\nimage that are smaller than the structuring element.\n\nTo make things interesting, we'll add bright and dark spots to the image:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "phantom = orig_phantom.copy()\nphantom[340:350, 200:210] = 255\nphantom[100:110, 200:210] = 0\n\nw_tophat = ski.morphology.white_tophat(phantom, footprint)\nplot_comparison(phantom, w_tophat, 'white tophat')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "As you can see, the 10-pixel wide white square is highlighted since it is\nsmaller than the structuring element. Also, the thin, white edges around\nmost of the ellipse are retained because they're smaller than the\nstructuring element, but the thicker region at the top disappears.\n\n## Black tophat\n\nThe ``black_tophat`` of an image is defined as its morphological **closing\nminus the original image**. This operation returns the *dark spots of the\nimage that are smaller than the structuring element*.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "b_tophat = ski.morphology.black_tophat(phantom, footprint)\nplot_comparison(phantom, b_tophat, 'black tophat')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "As you can see, the 10-pixel wide black square is highlighted since\nit is smaller than the structuring element.\n\n**Duality**\n\nAs you should have noticed, many of these operations are simply the reverse\nof another operation. This duality can be summarized as follows:\n\n  1. Erosion <-> Dilation\n\n  2. Opening <-> Closing\n\n  3. White tophat <-> Black tophat\n\n## Skeletonize\n\nThinning is used to reduce each connected component in a binary image to a\n*single-pixel wide skeleton*. It is important to note that this is\nperformed on binary images only.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "horse = ski.data.horse()\n\nsk = ski.morphology.skeletonize(horse == 0)\nplot_comparison(horse, sk, 'skeletonize')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "As the name suggests, this technique is used to thin the image to 1-pixel\nwide skeleton by applying thinning successively.\n\n## Convex hull\n\nThe ``convex_hull_image`` is the *set of pixels included in the smallest\nconvex polygon that surround all white pixels in the input image*. Again\nnote that this is also performed on binary images.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "hull1 = ski.morphology.convex_hull_image(horse == 0)\nplot_comparison(horse, hull1, 'convex hull')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "As the figure illustrates, ``convex_hull_image`` gives the smallest polygon\nwhich covers the white or True completely in the image.\n\nIf we add a small grain to the image, we can see how the convex hull adapts\nto enclose that grain:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "horse_mask = horse == 0\nhorse_mask[45:50, 75:80] = 1\n\nhull2 = ski.morphology.convex_hull_image(horse_mask)\nplot_comparison(horse_mask, hull2, 'convex hull')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Additional Resources\n\n1. [MathWorks tutorial on morphological processing](https://se.mathworks.com/help/images/morphological-dilation-and-erosion.html)\n\n2. [Auckland university's tutorial on Morphological Image Processing](https://www.cs.auckland.ac.nz/courses/compsci773s1c/lectures/ImageProcessing-html/topic4.htm)\n\n3. https://en.wikipedia.org/wiki/Mathematical_morphology\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "plt.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
}