{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Morphological Snakes\n\n*Morphological Snakes* [1]_ are a family of methods for image segmentation.\nTheir behavior is similar to that of active contours (for example, *Geodesic\nActive Contours* [2]_ or *Active Contours without Edges* [3]_). However,\n*Morphological Snakes* use morphological operators (such as dilation or\nerosion) over a binary array instead of solving PDEs over a floating point\narray, which is the standard approach for active contours. This makes\n*Morphological Snakes* faster and numerically more stable than their\ntraditional counterpart.\n\nThere are two *Morphological Snakes* methods available in this implementation:\n*Morphological Geodesic Active Contours* (**MorphGAC**, implemented in the\nfunction ``morphological_geodesic_active_contour``) and *Morphological Active\nContours without Edges* (**MorphACWE**, implemented in the function\n``morphological_chan_vese``).\n\n**MorphGAC** is suitable for images with visible contours, even when these\ncontours might be noisy, cluttered, or partially unclear. It requires, however,\nthat the image is preprocessed to highlight the contours. This can be done\nusing the function ``inverse_gaussian_gradient``, although the user might want\nto define their own version. The quality of the **MorphGAC** segmentation\ndepends greatly on this preprocessing step.\n\nOn the contrary, **MorphACWE** works well when the pixel values of the inside\nand the outside regions of the object to segment have different averages.\nUnlike **MorphGAC**, **MorphACWE** does not require that the contours of the\nobject are well defined, and it works over the original image without any\npreceding processing. This makes **MorphACWE** easier to use and tune than\n**MorphGAC**.\n\n## References\n\n.. [1] A Morphological Approach to Curvature-based Evolution of Curves and\n       Surfaces, Pablo M\u00e1rquez-Neila, Luis Baumela and Luis \u00c1lvarez. In IEEE\n       Transactions on Pattern Analysis and Machine Intelligence (PAMI),\n       2014, :DOI:`10.1109/TPAMI.2013.106`\n.. [2] Geodesic Active Contours, Vicent Caselles, Ron Kimmel and Guillermo\n       Sapiro. In International Journal of Computer Vision (IJCV), 1997,\n       :DOI:`10.1023/A:1007979827043`\n.. [3] Active Contours without Edges, Tony Chan and Luminita Vese. In IEEE\n       Transactions on Image Processing, 2001, :DOI:`10.1109/83.902291`\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.lines as mlines\nimport skimage as ski\n\n\ndef store_evolution_in(lst):\n    \"\"\"Returns a callback function to store the evolution of the level sets in\n    the given list.\n    \"\"\"\n\n    def _store(x):\n        lst.append(np.copy(x))\n\n    return _store\n\n\n# Morphological ACWE\nimage = ski.util.img_as_float(ski.data.camera())\n\n# Initial level set\ninit_ls = ski.segmentation.checkerboard_level_set(image.shape, 6)\n# List with intermediate results for plotting the evolution\nevolution = []\ncallback = store_evolution_in(evolution)\nls = ski.segmentation.morphological_chan_vese(\n    image, num_iter=35, init_level_set=init_ls, smoothing=3, iter_callback=callback\n)\n\nfig, axes = plt.subplots(2, 2, figsize=(8, 8))\nax = axes.flatten()\n\nax[0].imshow(image, cmap=\"gray\")\nax[0].set_axis_off()\nax[0].contour(ls, [0.5], colors='r')\nax[0].set_title(\"Morphological ACWE segmentation\", fontsize=12)\n\nax[1].imshow(ls, cmap=\"gray\")\nax[1].set_axis_off()\nax[1].set_title(\"Morphological ACWE evolution\", fontsize=12)\n\ncontour_labels = []\nfor n, color in ((2, 'g'), (7, 'y'), (35, 'r')):\n    ax[1].contour(evolution[n], [0.5], colors=color)\n\n    # Use empty line to represent this contour in the legend\n    legend_line = mlines.Line2D([], [], color=color, label=f\"Iteration {n}\")\n    contour_labels.append(legend_line)\n\nax[1].legend(handles=contour_labels, loc=\"upper right\")\n\n# Morphological GAC\nimage = ski.util.img_as_float(ski.data.coins())\ngimage = ski.segmentation.inverse_gaussian_gradient(image)\n\n# Initial level set\ninit_ls = np.zeros(image.shape, dtype=np.int8)\ninit_ls[10:-10, 10:-10] = 1\n# List with intermediate results for plotting the evolution\nevolution = []\ncallback = store_evolution_in(evolution)\nls = ski.segmentation.morphological_geodesic_active_contour(\n    gimage,\n    num_iter=230,\n    init_level_set=init_ls,\n    smoothing=1,\n    balloon=-1,\n    threshold=0.69,\n    iter_callback=callback,\n)\n\nax[2].imshow(image, cmap=\"gray\")\nax[2].set_axis_off()\nax[2].contour(ls, [0.5], colors='r')\nax[2].set_title(\"Morphological GAC segmentation\", fontsize=12)\n\nax[3].imshow(ls, cmap=\"gray\")\nax[3].set_axis_off()\nax[3].set_title(\"Morphological GAC evolution\", fontsize=12)\n\ncontour_labels = []\nfor n, color in ((0, 'g'), (100, 'y'), (230, 'r')):\n    ax[3].contour(evolution[n], [0.5], colors=color)\n\n    # Use empty line to represent this contour in the legend\n    legend_line = mlines.Line2D([], [], color=color, label=f\"Iteration {n}\")\n    contour_labels.append(legend_line)\n\nax[3].legend(handles=contour_labels, loc=\"upper right\")\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
}