{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Estimate anisotropy in a 3D microscopy image\n\nIn this tutorial, we compute the structure tensor of a 3D image.\nFor a general introduction to 3D image processing, please refer to\n`sphx_glr_auto_examples_applications_plot_3d_image_processing.py`.\nThe data we use here are sampled from an image of kidney tissue obtained by\nconfocal fluorescence microscopy (more details at [1]_ under\n``kidney-tissue-fluorescence.tif``).\n\n.. [1] https://gitlab.com/scikit-image/data/#data\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import matplotlib.pyplot as plt\nimport numpy as np\nimport plotly.express as px\nimport plotly.io\n\nimport skimage as ski"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Load image\nThis biomedical image is available through `scikit-image`'s data registry.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "data = ski.data.kidney()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "What exactly are the shape and size of our 3D multichannel image?\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "print(f'number of dimensions: {data.ndim}')\nprint(f'shape: {data.shape}')\nprint(f'dtype: {data.dtype}')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "For the purposes of this tutorial, we shall consider only the second color\nchannel, which leaves us with a 3D single-channel image. What is the range\nof values?\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "n_plane, n_row, n_col, n_chan = data.shape\nv_min, v_max = data[:, :, :, 1].min(), data[:, :, :, 1].max()\nprint(f'range: ({v_min}, {v_max})')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Let us visualize the middle slice of our 3D image.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "fig1 = px.imshow(\n    data[n_plane // 2, :, :, 1],\n    zmin=v_min,\n    zmax=v_max,\n    labels={'x': 'col', 'y': 'row', 'color': 'intensity'},\n)\n\nplotly.io.show(fig1)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Let us pick a specific region, which shows relative X-Y isotropy. In\ncontrast, the gradient is quite different (and, for that matter, weak) along\nZ.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "sample = data[5:13, 380:410, 370:400, 1]\nstep = 3\ncols = sample.shape[0] // step + 1\n_, axes = plt.subplots(nrows=1, ncols=cols, figsize=(16, 8))\n\nfor it, (ax, image) in enumerate(zip(axes.flatten(), sample[::step])):\n    ax.imshow(image, cmap='gray', vmin=v_min, vmax=v_max)\n    ax.set_title(f'Plane = {5 + it * step}')\n    ax.set_xticks([])\n    ax.set_yticks([])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "To view the sample data in 3D, run the following code:\n\n  .. code-block:: python\n     :caption: We import the `plotly.graph_objects` module, upon which\n               `plotly.express` is built.\n\n      import plotly.graph_objects as go\n\n      (n_Z, n_Y, n_X) = sample.shape\n      Z, Y, X = np.mgrid[:n_Z, :n_Y, :n_X]\n\n      fig = go.Figure(\n          data=go.Volume(\n              x=X.flatten(),\n              y=Y.flatten(),\n              z=Z.flatten(),\n              value=sample.flatten(),\n              opacity=0.5,\n              slices_z=dict(show=True, locations=[4])\n          )\n      )\n      fig.show()\n\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Compute structure tensor\nLet us visualize the bottom slice of our sample data and determine the\ntypical size for strong variations. We shall use this size as the\n'width' of the window function.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "fig2 = px.imshow(\n    sample[0, :, :],\n    zmin=v_min,\n    zmax=v_max,\n    labels={'x': 'col', 'y': 'row', 'color': 'intensity'},\n    title='Interactive view of bottom slice of sample data.',\n)\n\nplotly.io.show(fig2)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "About the brightest region (i.e., at row ~ 22 and column ~ 17), we can see\nvariations (and, hence, strong gradients) over 2 or 3 (resp. 1 or 2) pixels\nacross columns (resp. rows). We may thus choose, say, ``sigma = 1.5`` for\nthe window\nfunction. Alternatively, we can pass sigma on a per-axis basis, e.g.,\n``sigma = (1, 2, 3)``. Note that size 1 sounds reasonable along the first\n(Z, plane) axis, since the latter is of size 8 (13 - 5). Viewing slices in\nthe X-Z or Y-Z planes confirms it is reasonable.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "sigma = (1, 1.5, 2.5)\nA_elems = ski.feature.structure_tensor(sample, sigma=sigma)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We can then compute the eigenvalues of the structure tensor.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "eigen = ski.feature.structure_tensor_eigenvalues(A_elems)\neigen.shape"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Where is the largest eigenvalue?\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "coords = np.unravel_index(eigen.argmax(), eigen.shape)\nassert coords[0] == 0  # by definition\ncoords"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "<div class=\"alert alert-info\"><h4>Note</h4><p>The reader may check how robust this result (coordinates\n   ``(plane, row, column) = coords[1:]``) is to varying ``sigma``.</p></div>\n\nLet us view the spatial distribution of the eigenvalues in the X-Y plane\nwhere the maximum eigenvalue is found (i.e., ``Z = coords[1]``).\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "fig3 = px.imshow(\n    eigen[:, coords[1], :, :],\n    facet_col=0,\n    labels={'x': 'col', 'y': 'row', 'facet_col': 'rank'},\n    title=f'Eigenvalues for plane Z = {coords[1]}.',\n)\n\nplotly.io.show(fig3)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We are looking at a local property. Let us consider a tiny neighborhood\naround the maximum eigenvalue in the above X-Y plane.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "eigen[0, coords[1], coords[2] - 2 : coords[2] + 1, coords[3] - 2 : coords[3] + 1]"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "If we examine the second-largest eigenvalues in this neighborhood, we can\nsee that they have the same order of magnitude as the largest ones.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "eigen[1, coords[1], coords[2] - 2 : coords[2] + 1, coords[3] - 2 : coords[3] + 1]"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "In contrast, the third-largest eigenvalues are one order of magnitude\nsmaller.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "eigen[2, coords[1], coords[2] - 2 : coords[2] + 1, coords[3] - 2 : coords[3] + 1]"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Let us visualize the slice of sample data in the X-Y plane where the\nmaximum eigenvalue is found.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "fig4 = px.imshow(\n    sample[coords[1], :, :],\n    zmin=v_min,\n    zmax=v_max,\n    labels={'x': 'col', 'y': 'row', 'color': 'intensity'},\n    title=f'Interactive view of plane Z = {coords[1]}.',\n)\n\nplotly.io.show(fig4)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Let us visualize the slices of sample data in the X-Z (left) and Y-Z (right)\nplanes where the maximum eigenvalue is found. The Z axis is the vertical\naxis in the subplots below. We can see the expected relative invariance\nalong the Z axis (corresponding to longitudinal structures in the kidney\ntissue), especially in the Y-Z plane (``longitudinal=1``).\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "subplots = np.dstack((sample[:, coords[2], :], sample[:, :, coords[3]]))\nfig5 = px.imshow(\n    subplots, zmin=v_min, zmax=v_max, facet_col=2, labels={'facet_col': 'longitudinal'}\n)\n\nplotly.io.show(fig5)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "As a conclusion, the region about voxel\n``(plane, row, column) = coords[1:]`` is\nanisotropic in 3D: There is an order of magnitude between the third-largest\neigenvalues on one hand, and the largest and second-largest eigenvalues on\nthe other hand. We could see this at first glance in figure `Eigenvalues for\nplane Z = 1`.\n\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "The neighborhood in question is 'somewhat isotropic' in a plane (which,\nhere, would be relatively close to the X-Y plane): There is a factor of\nless than 2 between the second-largest and largest eigenvalues.\nThis description is compatible with what we are seeing in the image, i.e., a\nstronger gradient across a direction (which, here, would be relatively close\nto the row axis) and a weaker gradient perpendicular to it.\n\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "In an ellipsoidal representation of the 3D structure tensor [2]_,\nwe would get the pancake situation.\n\n.. [2] https://en.wikipedia.org/wiki/Structure_tensor#Interpretation_2\n\n"
      ]
    }
  ],
  "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
}