{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Interact with 3D images (of kidney tissue)\n\nIn this tutorial, we explore interactively a biomedical image which has three\nspatial dimensions and three color dimensions (channels).\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 correspond to kidney tissue which was\nimaged with confocal 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\n\nimport plotly\nimport plotly.express as px\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": [
        "The returned dataset is a 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": [
        "Dimensions are provided in the following order: ``(z, y, x, c)``, i.e.,\n``[plane, row, column, channel]``.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "n_plane, n_row, n_col, n_chan = data.shape"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Let us consider only a slice (2D plane) of the data for now. More\nspecifically, let us consider the slice located halfway in the stack.\nThe `imshow` function can display both grayscale and RGB(A) 2D images.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "_, ax = plt.subplots()\nax.imshow(data[n_plane // 2])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "According to the warning message, the range of values is unexpected. The\nimage rendering is clearly not satisfactory color-wise.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "vmin, vmax = data.min(), data.max()\nprint(f'range: ({vmin}, {vmax})')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We turn to Plotly's implementation of the :func:`plotly.express.imshow` function, for it\nsupports [value ranges](https://plotly.com/python/imshow/#defining-the-data-range-covered-by-the-color-range-with-zmin-and-zmax)\nbeyond ``(0.0, 1.0)`` for floats and ``(0, 255)`` for integers.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "fig = px.imshow(data[n_plane // 2], zmax=vmax)\nplotly.io.show(fig)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Here you go, *fluorescence* microscopy!\n\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Normalize range for each channel\nGenerally speaking, we may want to normalize the value range on a\nper-channel basis. Let us facet our data (slice) along the channel axis.\nThis way, we get three single-channel images, where the max value of each\nimage is used:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "fig = px.imshow(\n    data[n_plane // 2], facet_col=2, binary_string=True, labels={'facet_col': 'channel'}\n)\nplotly.io.show(fig)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "What is the range of values for each color channel?\nWe check by taking the min and max across all non-channel\naxes.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "vmin_0, vmin_1, vmin_2 = np.min(data, axis=(0, 1, 2))\nvmax_0, vmax_1, vmax_2 = np.max(data, axis=(0, 1, 2))\nprint(f'range for channel 0: ({vmin_0}, {vmax_0})')\nprint(f'range for channel 1: ({vmin_1}, {vmax_1})')\nprint(f'range for channel 2: ({vmin_2}, {vmax_2})')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Let us be very specific and pass value ranges on a per-channel basis:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "fig = px.imshow(\n    data[n_plane // 2], zmin=[vmin_0, vmin_1, vmin_2], zmax=[vmax_0, vmax_1, vmax_2]\n)\nplotly.io.show(fig)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Plotly lets you interact with this visualization by panning, zooming in and\nout, and exporting the desired figure as a static image in PNG format.\n\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Explore slices as animation frames\nClick the play button to move along the ``z`` axis, through the stack of all\n16 slices.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "fig = px.imshow(\n    data,\n    zmin=[vmin_0, vmin_1, vmin_2],\n    zmax=[vmax_0, vmax_1, vmax_2],\n    animation_frame=0,\n    binary_string=True,\n    labels={'animation_frame': 'plane'},\n)\nplotly.io.show(fig)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Combine channel facetting and slice animation\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "fig = px.imshow(\n    data,\n    animation_frame=0,\n    facet_col=3,\n    binary_string=True,\n    labels={'facet_col': 'channel', 'animation_frame': 'plane'},\n)\nplotly.io.show(fig)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "The biologist's eye can spot that the two bright blobs (best seen in\n``channel=2``) are kidney glomeruli [2]_.\n\n.. [2] https://en.wikipedia.org/wiki/Glomerulus_(kidney)\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "plt.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
}