{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Shape Index\n\nThe shape index is a single valued measure of local curvature,\nderived from the eigen values of the Hessian,\ndefined by Koenderink & van Doorn [1]_.\n\nIt can be used to find structures based on their apparent local shape.\n\nThe shape index maps to values from -1 to 1,\nrepresenting different kind of shapes (see the documentation for details).\n\nIn this example, a random image with spots is generated,\nwhich should be detected.\n\nA shape index of 1 represents 'spherical caps',\nthe shape of the spots we want to detect.\n\nThe leftmost plot shows the generated image, the center shows a 3D render\nof the image, taking intensity values as height of a 3D surface,\nand the right one shows the shape index (s).\n\nAs visible, the shape index readily amplifies the local shape of noise as well,\nbut is insusceptible to global phenomena (e.g. uneven illumination).\n\nThe blue and green marks are points which deviate no more than 0.05\nfrom the desired shape. To attenuate noise in the signal, the\ngreen marks are taken from the shape index (s)\nafter another Gaussian blur pass (yielding s').\n\nNote how spots interjoined too closely are *not* detected,\nas they do not posses the desired shape.\n\n.. [1] Koenderink, J. J. & van Doorn, A. J.,\n       \"Surface shape and curvature scales\",\n       Image and Vision Computing, 1992, 10, 557-564.\n       :DOI:`10.1016/0262-8856(92)90076-F`\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import ndimage as ndi\nfrom skimage.feature import shape_index\nfrom skimage.draw import disk\n\n\ndef create_test_image(image_size=256, spot_count=30, spot_radius=5, cloud_noise_size=4):\n    \"\"\"\n    Generate a test image with random noise, uneven illumination and spots.\n    \"\"\"\n    rng = np.random.default_rng()\n    image = rng.normal(loc=0.25, scale=0.25, size=(image_size, image_size))\n\n    for _ in range(spot_count):\n        rr, cc = disk(\n            (rng.integers(image.shape[0]), rng.integers(image.shape[1])),\n            spot_radius,\n            shape=image.shape,\n        )\n        image[rr, cc] = 1\n\n    image *= rng.normal(loc=1.0, scale=0.1, size=image.shape)\n\n    image *= ndi.zoom(\n        rng.normal(loc=1.0, scale=0.5, size=(cloud_noise_size, cloud_noise_size)),\n        image_size / cloud_noise_size,\n    )\n\n    return ndi.gaussian_filter(image, sigma=2.0)\n\n\n# First create the test image and its shape index\n\nimage = create_test_image()\n\ns = shape_index(image)\n\n# In this example we want to detect 'spherical caps',\n# so we threshold the shape index map to\n# find points which are 'spherical caps' (~1)\n\ntarget = 1\ndelta = 0.05\n\npoint_y, point_x = np.where(np.abs(s - target) < delta)\npoint_z = image[point_y, point_x]\n\n# The shape index map relentlessly produces the shape, even that of noise.\n# In order to reduce the impact of noise, we apply a Gaussian filter to it,\n# and show the results once in\n\ns_smooth = ndi.gaussian_filter(s, sigma=0.5)\n\npoint_y_s, point_x_s = np.where(np.abs(s_smooth - target) < delta)\npoint_z_s = image[point_y_s, point_x_s]\n\n\nfig = plt.figure(figsize=(12, 4))\nax1 = fig.add_subplot(1, 3, 1)\n\nax1.imshow(image, cmap=plt.cm.gray)\nax1.axis('off')\nax1.set_title('Input image')\n\nscatter_settings = dict(alpha=0.75, s=10, linewidths=0)\n\nax1.scatter(point_x, point_y, color='blue', **scatter_settings)\nax1.scatter(point_x_s, point_y_s, color='green', **scatter_settings)\n\nax2 = fig.add_subplot(1, 3, 2, projection='3d', sharex=ax1, sharey=ax1)\n\nx, y = np.meshgrid(np.arange(0, image.shape[0], 1), np.arange(0, image.shape[1], 1))\n\nax2.plot_surface(x, y, image, linewidth=0, alpha=0.5)\n\nax2.scatter(\n    point_x, point_y, point_z, color='blue', label='$|s - 1|<0.05$', **scatter_settings\n)\n\nax2.scatter(\n    point_x_s,\n    point_y_s,\n    point_z_s,\n    color='green',\n    label='$|s\\' - 1|<0.05$',\n    **scatter_settings,\n)\n\nax2.legend(loc='lower left')\n\nax2.axis('off')\nax2.set_title('3D visualization')\n\nax3 = fig.add_subplot(1, 3, 3, sharex=ax1, sharey=ax1)\n\nax3.imshow(s, cmap=plt.cm.gray)\nax3.axis('off')\nax3.set_title(r'Shape index, $\\sigma=1$')\n\nfig.tight_layout()\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
}