{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Skeletonize\n\nSkeletonization reduces binary objects to 1 pixel wide representations. This\ncan be useful for feature extraction, and/or representing an object's topology.\n\n``skeletonize`` works by making successive passes of the image. On each pass,\nborder pixels are identified and removed on the condition that they do not\nbreak the connectivity of the corresponding object.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from skimage.morphology import skeletonize\nfrom skimage import data\nimport matplotlib.pyplot as plt\nfrom skimage.util import invert\n\n# Invert the horse image\nimage = invert(data.horse())\n\n# perform skeletonization\nskeleton = skeletonize(image)\n\n# display results\nfig, axes = plt.subplots(nrows=1, ncols=2, figsize=(8, 4), sharex=True, sharey=True)\n\nax = axes.ravel()\n\nax[0].imshow(image, cmap=plt.cm.gray)\nax[0].axis('off')\nax[0].set_title('original', fontsize=20)\n\nax[1].imshow(skeleton, cmap=plt.cm.gray)\nax[1].axis('off')\nax[1].set_title('skeleton', fontsize=20)\n\nfig.tight_layout()\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "**Zhang's method vs Lee's method**\n\n``skeletonize`` [Zha84]_ works by making successive passes of\nthe image, removing pixels on object borders. This continues until no\nmore pixels can be removed.  The image is correlated with a\nmask that assigns each pixel a number in the range [0...255]\ncorresponding to each possible pattern of its 8 neighboring\npixels. A look up table is then used to assign the pixels a\nvalue of 0, 1, 2 or 3, which are selectively removed during\nthe iterations.\n\n``skeletonize(..., method='lee')`` [Lee94]_ uses an octree data structure\nto examine a 3x3x3 neighborhood of a pixel. The algorithm proceeds by\niteratively sweeping over the image, and removing pixels at each iteration\nuntil the image stops changing. Each iteration consists of two steps: first,\na list of candidates for removal is assembled; then pixels from this list\nare rechecked sequentially, to better preserve connectivity of the image.\n\nNote that Lee's method [Lee94]_ is designed to be used on 3-D images, and\nis selected automatically for those. For illustrative purposes, we apply\nthis algorithm to a 2-D image.\n\n.. [Zha84] A fast parallel algorithm for thinning digital patterns,\n           T. Y. Zhang and C. Y. Suen, Communications of the ACM,\n           March 1984, Volume 27, Number 3.\n\n.. [Lee94] T.-C. Lee, R.L. Kashyap and C.-N. Chu, Building skeleton models\n           via 3-D medial surface/axis thinning algorithms.\n           Computer Vision, Graphics, and Image Processing, 56(6):462-478,\n           1994.\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import matplotlib.pyplot as plt\nfrom skimage.morphology import skeletonize\n\nblobs = data.binary_blobs(200, blob_size_fraction=0.2, volume_fraction=0.35, rng=1)\n\nskeleton = skeletonize(blobs)\nskeleton_lee = skeletonize(blobs, method='lee')\n\nfig, axes = plt.subplots(1, 3, figsize=(8, 4), sharex=True, sharey=True)\nax = axes.ravel()\n\nax[0].imshow(blobs, cmap=plt.cm.gray)\nax[0].set_title('original')\nax[0].axis('off')\n\nax[1].imshow(skeleton, cmap=plt.cm.gray)\nax[1].set_title('skeletonize')\nax[1].axis('off')\n\nax[2].imshow(skeleton_lee, cmap=plt.cm.gray)\nax[2].set_title('skeletonize (Lee 94)')\nax[2].axis('off')\n\nfig.tight_layout()\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "**Medial axis skeletonization**\n\nThe medial axis of an object is the set of all points having more than one\nclosest point on the object's boundary. It is often called the *topological\nskeleton*, because it is a 1-pixel wide skeleton of the object, with the same\nconnectivity as the original object.\n\nHere, we use the medial axis transform to compute the width of the foreground\nobjects. As the function ``medial_axis`` returns the distance transform in\naddition to the medial axis (with the keyword argument ``return_distance=True``),\nit is possible to compute the distance to the background for all points of\nthe medial axis with this function. This gives an estimate of the local width\nof the objects.\n\nFor a skeleton with fewer branches, ``skeletonize`` should be preferred.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from skimage.morphology import medial_axis, skeletonize\n\n# Generate the data\nblobs = data.binary_blobs(200, blob_size_fraction=0.2, volume_fraction=0.35, rng=1)\n\n# Compute the medial axis (skeleton) and the distance transform\nskel, distance = medial_axis(blobs, return_distance=True)\n\n# Compare with other skeletonization algorithms\nskeleton = skeletonize(blobs)\nskeleton_lee = skeletonize(blobs, method='lee')\n\n# Distance to the background for pixels of the skeleton\ndist_on_skel = distance * skel\n\nfig, axes = plt.subplots(2, 2, figsize=(8, 8), sharex=True, sharey=True)\nax = axes.ravel()\n\nax[0].imshow(blobs, cmap=plt.cm.gray)\nax[0].set_title('original')\nax[0].axis('off')\n\nax[1].imshow(dist_on_skel, cmap='magma')\nax[1].contour(blobs, [0.5], colors='w')\nax[1].set_title('medial_axis')\nax[1].axis('off')\n\nax[2].imshow(skeleton, cmap=plt.cm.gray)\nax[2].set_title('skeletonize')\nax[2].axis('off')\n\nax[3].imshow(skeleton_lee, cmap=plt.cm.gray)\nax[3].set_title(\"skeletonize (Lee 94)\")\nax[3].axis('off')\n\nfig.tight_layout()\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "**Morphological thinning**\n\nMorphological thinning, implemented in the `thin` function, works on the\nsame principle as `skeletonize`: remove pixels from the borders at each\niteration until none can be removed without altering the connectivity. The\ndifferent rules of removal can speed up skeletonization and result in\ndifferent final skeletons.\n\nThe `thin` function also takes an optional `max_num_iter` keyword argument to\nlimit the number of thinning iterations, and thus produce a relatively\nthicker skeleton.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from skimage.morphology import skeletonize, thin\n\nskeleton = skeletonize(image)\nthinned = thin(image)\nthinned_partial = thin(image, max_num_iter=25)\n\nfig, axes = plt.subplots(2, 2, figsize=(8, 8), sharex=True, sharey=True)\nax = axes.ravel()\n\nax[0].imshow(image, cmap=plt.cm.gray)\nax[0].set_title('original')\nax[0].axis('off')\n\nax[1].imshow(skeleton, cmap=plt.cm.gray)\nax[1].set_title('skeleton')\nax[1].axis('off')\n\nax[2].imshow(thinned, cmap=plt.cm.gray)\nax[2].set_title('thinned')\nax[2].axis('off')\n\nax[3].imshow(thinned_partial, cmap=plt.cm.gray)\nax[3].set_title('partially thinned')\nax[3].axis('off')\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
}