{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Explore 3D images (of cells)\n\nThis tutorial is an introduction to three-dimensional image processing.\nFor a quick intro to 3D datasets, please refer to\n`sphx_glr_auto_examples_data_plot_3d.py`.\nImages\nare represented as `numpy` arrays. A single-channel, or grayscale, image is a\n2D matrix of pixel intensities of shape ``(n_row, n_col)``, where ``n_row``\n(resp. ``n_col``) denotes the number of `rows` (resp. `columns`). We can\nconstruct a 3D volume as a series of 2D `planes`, giving 3D images the shape\n``(n_plane, n_row, n_col)``, where ``n_plane`` is the number of planes.\nA multichannel, or RGB(A), image has an additional\n`channel` dimension in the final position containing color information.\n\nThese conventions are summarized in the table below:\n\n=============== =================================\nImage type      Coordinates\n=============== =================================\n2D grayscale    ``[row, column]``\n2D multichannel ``[row, column, channel]``\n3D grayscale    ``[plane, row, column]``\n3D multichannel ``[plane, row, column, channel]``\n=============== =================================\n\nSome 3D images are constructed with equal resolution in each dimension (e.g.,\nsynchrotron tomography or computer-generated rendering of a sphere).\nBut most experimental data are captured\nwith a lower resolution in one of the three dimensions, e.g., photographing\nthin slices to approximate a 3D structure as a stack of 2D images.\nThe distance between pixels in each dimension, called spacing, is encoded as a\ntuple and is accepted as a parameter by some `skimage` functions and can be\nused to adjust contributions to filters.\n\nThe data used in this tutorial were provided by the Allen Institute for Cell\nScience. They were downsampled by a factor of 4 in the `row` and `column`\ndimensions to reduce their size and, hence, computational time. The spacing\ninformation was reported by the microscope used to image the cells.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d.art3d import Poly3DCollection\nimport numpy as np\n\nimport plotly\nimport plotly.express as px\nimport skimage as ski"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Load and display 3D images\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "data = ski.util.img_as_float(ski.data.cells3d()[:, 1, :, :])  # grab just the nuclei\n\nprint(f'shape: {data.shape}')\nprint(f'dtype: {data.dtype}')\nprint(f'range: ({data.min()}, {data.max()})')\n\n# Report spacing from microscope\noriginal_spacing = np.array([0.2900000, 0.0650000, 0.0650000])\n\n# Account for downsampling of slices by 4\nrescaled_spacing = original_spacing * [1, 4, 4]\n\n# Normalize spacing so that pixels are a distance of 1 apart\nspacing = rescaled_spacing / rescaled_spacing[2]\n\nprint(f'microscope spacing: {original_spacing}\\n')\nprint(f'rescaled spacing: {rescaled_spacing} (after downsampling)\\n')\nprint(f'normalized spacing: {spacing}\\n')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Let us try and visualize our 3D image. Unfortunately, many image viewers,\nsuch as matplotlib's `imshow`, are only capable of displaying 2D data. We\ncan see that they raise an error when we try to view 3D data:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "try:\n    fig, ax = plt.subplots()\n    ax.imshow(data, cmap='gray')\nexcept TypeError as e:\n    print(str(e))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "The `imshow` function can only display grayscale and RGB(A) 2D images.\nWe can thus use it to visualize 2D planes. By fixing one axis, we can\nobserve three different views of the image.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "def show_plane(ax, plane, cmap=\"gray\", title=None):\n    ax.imshow(plane, cmap=cmap)\n    ax.set_axis_off()\n\n    if title:\n        ax.set_title(title)\n\n\n(n_plane, n_row, n_col) = data.shape\n_, (a, b, c) = plt.subplots(ncols=3, figsize=(15, 5))\n\nshow_plane(a, data[n_plane // 2], title=f'Plane = {n_plane // 2}')\nshow_plane(b, data[:, n_row // 2, :], title=f'Row = {n_row // 2}')\nshow_plane(c, data[:, :, n_col // 2], title=f'Column = {n_col // 2}')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "As hinted before, a three-dimensional image can be viewed as a series of\ntwo-dimensional planes. Let us write a helper function, `display`, to create\na montage of several planes. By default, every other plane is displayed.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "def display(im3d, cmap='gray', step=2):\n    data_montage = ski.util.montage(im3d[::step], padding_width=4, fill=np.nan)\n    _, ax = plt.subplots(figsize=(16, 14))\n    ax.imshow(data_montage, cmap=cmap)\n    ax.set_axis_off()\n\n\ndisplay(data)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Alternatively, we can explore these planes (slices) interactively using\nJupyter widgets. Let the user select which slice to display and show the\nposition of this slice in the 3D dataset.\nNote that you cannot see the Jupyter widget at work in a static HTML page,\nas is the case in the online version of this example. For the following\npiece of code to work, you need a Jupyter kernel running either locally or\nin the cloud: see the bottom of this page to either download the Jupyter\nnotebook and run it on your computer, or open it directly in Binder. On top\nof an active kernel, you need a web browser: running the code in pure Python\nwill not work either.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "def slice_in_3D(ax, i):\n    # From https://stackoverflow.com/questions/44881885/python-draw-3d-cube\n    Z = np.array(\n        [\n            [0, 0, 0],\n            [1, 0, 0],\n            [1, 1, 0],\n            [0, 1, 0],\n            [0, 0, 1],\n            [1, 0, 1],\n            [1, 1, 1],\n            [0, 1, 1],\n        ]\n    )\n\n    Z = Z * data.shape\n    r = [-1, 1]\n    X, Y = np.meshgrid(r, r)\n\n    # Plot vertices\n    ax.scatter3D(Z[:, 0], Z[:, 1], Z[:, 2])\n\n    # List sides' polygons of figure\n    verts = [\n        [Z[0], Z[1], Z[2], Z[3]],\n        [Z[4], Z[5], Z[6], Z[7]],\n        [Z[0], Z[1], Z[5], Z[4]],\n        [Z[2], Z[3], Z[7], Z[6]],\n        [Z[1], Z[2], Z[6], Z[5]],\n        [Z[4], Z[7], Z[3], Z[0]],\n        [Z[2], Z[3], Z[7], Z[6]],\n    ]\n\n    # Plot sides\n    ax.add_collection3d(\n        Poly3DCollection(\n            verts, facecolors=(0, 1, 1, 0.25), linewidths=1, edgecolors=\"darkblue\"\n        )\n    )\n\n    verts = np.array([[[0, 0, 0], [0, 0, 1], [0, 1, 1], [0, 1, 0]]])\n    verts = verts * (60, 256, 256)\n    verts += [i, 0, 0]\n\n    ax.add_collection3d(\n        Poly3DCollection(verts, facecolors=\"magenta\", linewidths=1, edgecolors=\"black\")\n    )\n\n    ax.set_xlabel(\"plane\")\n    ax.set_xlim(0, 100)\n    ax.set_ylabel(\"row\")\n    ax.set_zlabel(\"col\")\n\n    # Autoscale plot axes\n    scaling = np.array([getattr(ax, f'get_{dim}lim')() for dim in \"xyz\"])\n    ax.auto_scale_xyz(*[[np.min(scaling), np.max(scaling)]] * 3)\n\n\ndef explore_slices(data, cmap=\"gray\"):\n    from ipywidgets import interact\n\n    N = len(data)\n\n    @interact(plane=(0, N - 1))\n    def display_slice(plane=34):\n        fig, ax = plt.subplots(figsize=(20, 5))\n\n        ax_3D = fig.add_subplot(133, projection=\"3d\")\n\n        show_plane(ax, data[plane], title=f'Plane {plane}', cmap=cmap)\n        slice_in_3D(ax_3D, plane)\n\n        plt.show()\n\n    return display_slice\n\n\nexplore_slices(data)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Adjust exposure\nScikit-image's `exposure` module contains a number of functions for\nadjusting image contrast. These functions operate on pixel values.\nGenerally, image dimensionality or pixel spacing doesn't need to be\nconsidered. In local exposure correction, though, one might want to\nadjust the window size to ensure equal size in *real* coordinates along\neach axis.\n\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "[Gamma correction](https://en.wikipedia.org/wiki/Gamma_correction)\nbrightens or darkens an image. A power-law transform, where `gamma` denotes\nthe power-law exponent, is applied to each pixel in the image: `gamma < 1`\nwill brighten an image, while `gamma > 1` will darken an image.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "def plot_hist(ax, data, title=None):\n    # Helper function for plotting histograms\n    ax.hist(data.ravel(), bins=256)\n    ax.ticklabel_format(axis=\"y\", style=\"scientific\", scilimits=(0, 0))\n\n    if title:\n        ax.set_title(title)\n\n\ngamma_low_val = 0.5\ngamma_low = ski.exposure.adjust_gamma(data, gamma=gamma_low_val)\n\ngamma_high_val = 1.5\ngamma_high = ski.exposure.adjust_gamma(data, gamma=gamma_high_val)\n\n_, ((a, b, c), (d, e, f)) = plt.subplots(nrows=2, ncols=3, figsize=(12, 8))\n\nshow_plane(a, data[32], title='Original')\nshow_plane(b, gamma_low[32], title=f'Gamma = {gamma_low_val}')\nshow_plane(c, gamma_high[32], title=f'Gamma = {gamma_high_val}')\n\nplot_hist(d, data)\nplot_hist(e, gamma_low)\nplot_hist(f, gamma_high)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "[Histogram\nequalization](https://en.wikipedia.org/wiki/Histogram_equalization)\nimproves contrast in an image by redistributing pixel intensities. The most\ncommon pixel intensities get spread out, increasing contrast in low-contrast\nareas. One downside of this approach is that it may enhance background\nnoise.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "equalized_data = ski.exposure.equalize_hist(data)\n\ndisplay(equalized_data)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "As before, if we have a Jupyter kernel running, we can explore the above\nslices interactively.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "explore_slices(equalized_data)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Let us now plot the image histogram before and after histogram equalization.\nBelow, we plot the respective cumulative distribution functions (CDF).\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "_, ((a, b), (c, d)) = plt.subplots(nrows=2, ncols=2, figsize=(16, 8))\n\nplot_hist(a, data, title=\"Original histogram\")\nplot_hist(b, equalized_data, title=\"Equalized histogram\")\n\ncdf, bins = ski.exposure.cumulative_distribution(data.ravel())\nc.plot(bins, cdf, \"r\")\nc.set_title(\"Original CDF\")\n\ncdf, bins = ski.exposure.cumulative_distribution(equalized_data.ravel())\nd.plot(bins, cdf, \"r\")\nd.set_title(\"Histogram equalization CDF\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Most experimental images are affected by salt and pepper noise. A few bright\nartifacts can decrease the relative intensity of the pixels of interest. A\nsimple way to improve contrast is to clip the pixel values on the lowest and\nhighest extremes. Clipping the darkest and brightest 0.5% of pixels will\nincrease the overall contrast of the image.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "vmin, vmax = np.percentile(data, q=(0.5, 99.5))\n\nclipped_data = ski.exposure.rescale_intensity(\n    data, in_range=(vmin, vmax), out_range=np.float32\n)\n\ndisplay(clipped_data)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Alternatively, we can explore these planes (slices) interactively using\n[Plotly Express](https://plotly.com/python/sliders/).\nNote that this works in a static HTML page!\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "fig = px.imshow(data, animation_frame=0, binary_string=True)\nfig.update_xaxes(showticklabels=False)\nfig.update_yaxes(showticklabels=False)\nfig.update_layout(autosize=False, width=500, height=500, coloraxis_showscale=False)\n# Drop animation buttons\nfig['layout'].pop('updatemenus')\nplotly.io.show(fig)\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
}