{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Segment human cells (in mitosis)\n\nIn this example, we analyze a microscopy image of human cells. We use data\nprovided by Jason Moffat [1]_ through\n[CellProfiler](https://cellprofiler.org/examples/#human-cells).\n\n.. [1] Moffat J, Grueneberg DA, Yang X, Kim SY, Kloepfer AM, Hinkle G, Piqani\n       B, Eisenhaure TM, Luo B, Grenier JK, Carpenter AE, Foo SY, Stewart SA,\n       Stockwell BR, Hacohen N, Hahn WC, Lander ES, Sabatini DM, Root DE\n       (2006) \"A lentiviral RNAi library for human and mouse genes applied to\n       an arrayed viral high-content screen\" Cell, 124(6):1283-98.\n       PMID: 16564017\n       :DOI:`10.1016/j.cell.2006.01.040`\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\n\nimport skimage as ski\n\nimage = ski.data.human_mitosis()\n\nfig, ax = plt.subplots()\nax.imshow(image, cmap='gray')\nax.set_title('Microscopy image of human cells stained for nuclear DNA')\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We can see many cell nuclei on a dark background. Most of them are smooth\nand have an elliptical shape. However, we can distinguish some brighter\nspots corresponding to nuclei undergoing\n[mitosis](https://en.wikipedia.org/wiki/Mitosis) (cell division).\n\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Another way of visualizing a grayscale image is contour plotting:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "fig, ax = plt.subplots(figsize=(5, 5))\nqcs = ax.contour(image, origin='image')\nax.set_title('Contour plot of the same raw image')\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "The contour lines are drawn at these levels:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "qcs.levels"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Each level has, respectively, the following number of segments:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# Levels without segments still contain one empty array, account for that\n[len(seg) if seg[0].size else 0 for seg in qcs.allsegs]"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Estimate the mitotic index\nCell biology uses the\n[mitotic index](https://en.wikipedia.org/wiki/Mitotic_index)\nto quantify cell division and,\nhence, cell proliferation. By definition, it is the ratio of cells in\nmitosis over the total number of cells. To analyze the above image,\nwe are thus interested in two thresholds: one separating the nuclei from the\nbackground, the other separating the dividing nuclei (brighter spots) from\nthe non-dividing nuclei.\nTo separate these three different classes of pixels, we\nresort to `sphx_glr_auto_examples_segmentation_plot_multiotsu.py`.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "thresholds = ski.filters.threshold_multiotsu(image, classes=3)\nregions = np.digitize(image, bins=thresholds)\n\nfig, ax = plt.subplots(ncols=2, figsize=(10, 5))\nax[0].imshow(image)\nax[0].set_title('Original')\nax[0].set_axis_off()\nax[1].imshow(regions)\nax[1].set_title('Multi-Otsu thresholding')\nax[1].set_axis_off()\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Since there are overlapping nuclei, thresholding is not enough to segment\nall the nuclei.\nIf it were, we could readily compute a mitotic index for this\nsample:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "cells = image > thresholds[0]\ndividing = image > thresholds[1]\nlabeled_cells = ski.measure.label(cells)\nlabeled_dividing = ski.measure.label(dividing)\nnaive_mi = labeled_dividing.max() / labeled_cells.max()\nprint(naive_mi)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Whoa, this can't be! The number of dividing nuclei\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "print(labeled_dividing.max())"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "is overestimated, while the total number of cells\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "print(labeled_cells.max())"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "is underestimated.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "fig, ax = plt.subplots(ncols=3, figsize=(15, 5))\nax[0].imshow(image)\nax[0].set_title('Original')\nax[0].set_axis_off()\nax[1].imshow(dividing)\nax[1].set_title('Dividing nuclei?')\nax[1].set_axis_off()\nax[2].imshow(cells)\nax[2].set_title('All nuclei?')\nax[2].set_axis_off()\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Count dividing nuclei\nClearly, not all connected regions in the middle plot are dividing nuclei.\nOn one hand, the second threshold (value of ``thresholds[1]``) appears to be\ntoo low to separate those very bright areas corresponding to dividing nuclei\nfrom relatively bright pixels otherwise present in many nuclei. On the other\nhand, we want a smoother image, removing small spurious objects and,\npossibly, merging clusters of neighboring objects (some could correspond to\ntwo nuclei emerging from one cell division). In a way, the segmentation\nchallenge we are facing with dividing nuclei is the opposite of that with\n(touching) cells.\n\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "To find suitable values for thresholds and filtering parameters, we proceed\nby dichotomy, visually and manually.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "higher_threshold = 125\ndividing = image > higher_threshold\n\nsmoother_dividing = ski.filters.rank.mean(\n    ski.util.img_as_ubyte(dividing), ski.morphology.disk(4)\n)\n\nbinary_smoother_dividing = smoother_dividing > 20\n\nfig, ax = plt.subplots(figsize=(5, 5))\nax.imshow(binary_smoother_dividing)\nax.set_title('Dividing nuclei')\nax.set_axis_off()\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We are left with\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "cleaned_dividing = ski.measure.label(binary_smoother_dividing)\nprint(cleaned_dividing.max())"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "dividing nuclei in this sample.\n\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Segment nuclei\nTo separate overlapping nuclei, we resort to\n`sphx_glr_auto_examples_segmentation_plot_watershed.py`.\nThe idea of the algorithm is to find watershed basins as if flooded from\na set of `markers`. We generate these markers as the local maxima of the\ndistance function to the background. Given the typical size of the nuclei,\nwe pass ``min_distance=7`` so that local maxima and, hence, markers will lie\nat least 7 pixels away from one another.\nWe also use ``exclude_border=False`` so that all nuclei touching the image\nborder will be included.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "distance = ndi.distance_transform_edt(cells)\n\nlocal_max_coords = ski.feature.peak_local_max(\n    distance, min_distance=7, exclude_border=False\n)\nlocal_max_mask = np.zeros(distance.shape, dtype=bool)\nlocal_max_mask[tuple(local_max_coords.T)] = True\nmarkers = ski.measure.label(local_max_mask)\n\nsegmented_cells = ski.segmentation.watershed(-distance, markers, mask=cells)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "To visualize the segmentation conveniently, we colour-code the labelled\nregions using the `color.label2rgb` function, specifying the background\nlabel with argument `bg_label=0`.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "fig, ax = plt.subplots(ncols=2, figsize=(10, 5))\nax[0].imshow(cells, cmap='gray')\nax[0].set_title('Overlapping nuclei')\nax[0].set_axis_off()\nax[1].imshow(ski.color.label2rgb(segmented_cells, bg_label=0))\nax[1].set_title('Segmented nuclei')\nax[1].set_axis_off()\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Make sure that the watershed algorithm has led to identifying more nuclei:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "assert segmented_cells.max() > labeled_cells.max()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Finally, we find a total number of\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "print(segmented_cells.max())"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "cells in this sample. Therefore, we estimate the mitotic index to be:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "print(cleaned_dividing.max() / segmented_cells.max())"
      ]
    }
  ],
  "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
}