{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Use pixel graphs to find an object's geodesic center\n\nIn various image analysis situations, it is useful to think of the pixels of an\nimage, or of a region of an image, as a network or graph, in which each pixel\nis connected to its neighbors (with or without diagonals). One such situation\nis finding the *geodesic center* of an object, which is the point closest to\nall other points *if you are only allowed to travel on the pixels of the\nobject*, rather than in a straight line. This point is the one with maximal\n*closeness centrality* [1]_ in the network.\n\nIn this example, we create such a *pixel graph* of a skeleton and find\nthe central pixel of that skeleton. This demonstrates its utility in contrast\nwith the centroid (also known as the center of mass) which may actually fall\noutside the object.\n\n## References\n.. [1] Linton C. Freeman: Centrality in networks: I.\n       Conceptual clarification. Social Networks 1:215-239, 1979.\n       :DOI:`10.1016/0378-8733(78)90021-7`\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy import ndimage as ndi\nimport skimage as ski"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We start by loading the data: an image of a human retina.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "retina_source = ski.data.retina()\n\n_, ax = plt.subplots()\nax.imshow(retina_source)\nax.set_axis_off()\n_ = ax.set_title('Human retina')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We convert the image to grayscale, then use the\n`Sato vesselness filter <skimage.filters.sato>` to better distinguish the\nmain vessels in the image.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "retina = ski.color.rgb2gray(retina_source)\nt0, t1 = ski.filters.threshold_multiotsu(retina, classes=3)\nmask = retina > t0\nvessels = ski.filters.sato(retina, sigmas=range(1, 10)) * mask\n\n_, axes = plt.subplots(nrows=1, ncols=2)\naxes[0].imshow(retina, cmap='gray')\naxes[0].set_axis_off()\naxes[0].set_title('grayscale')\naxes[1].imshow(vessels, cmap='magma')\naxes[1].set_axis_off()\n_ = axes[1].set_title('Sato vesselness')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Based on the observed vesselness values, we use\n`hysteresis thresholding <skimage.filters.apply_hysteresis_threshold>` to\ndefine the main vessels.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "thresholded = ski.filters.apply_hysteresis_threshold(vessels, 0.01, 0.03)\nlabeled = ndi.label(thresholded)[0]\n\n_, ax = plt.subplots()\nax.imshow(ski.color.label2rgb(labeled, retina))\nax.set_axis_off()\n_ = ax.set_title('Thresholded vesselness')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Finally, we can `skeletonize <skimage.morphology.skeletonize>` this label\nimage and use that as the basis to find the\n`central pixel <skimage.graph.central_pixel>` in that skeleton. Compare that\nto the position of the centroid!\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "largest_nonzero_label = np.argmax(np.bincount(labeled[labeled > 0]))\nbinary = labeled == largest_nonzero_label\nskeleton = ski.morphology.skeletonize(binary)\ng, nodes = ski.graph.pixel_graph(skeleton, connectivity=2)\npx, distances = ski.graph.central_pixel(\n    g, nodes=nodes, shape=skeleton.shape, partition_size=100\n)\n\ncentroid = ski.measure.centroid(labeled > 0)\n\n_, ax = plt.subplots()\nax.imshow(ski.color.label2rgb(skeleton, retina))\nax.scatter(px[1], px[0], label='graph center')\nax.scatter(centroid[1], centroid[0], label='centroid')\nax.legend()\nax.set_axis_off()\nax.set_title('Vessel graph center vs centroid')\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
}