{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Explore and visualize region properties with pandas\n\nThis toy example shows how to compute the size of every labelled region in a\nseries of 10 images. We use 2D images and then 3D images. The blob-like\nregions are generated synthetically. As the volume fraction (i.e., ratio of\npixels or voxels covered by the blobs) increases, the number of blobs\n(regions) decreases, and the size (area or volume) of a single region can get\nlarger and larger. The area (size) values are available in a pandas-compatible\nformat, which makes for convenient data analysis and visualization.\n\nBesides area, many other region properties are available.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\n\nfrom skimage import data, measure\n\n\nfractions = np.linspace(0.05, 0.5, 10)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 2D images\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "images = [data.binary_blobs(volume_fraction=f) for f in fractions]\n\nlabeled_images = [measure.label(image) for image in images]\n\nproperties = ['label', 'area']\n\ntables = [\n    measure.regionprops_table(image, properties=properties) for image in labeled_images\n]\ntables = [pd.DataFrame(table) for table in tables]\n\nfor fraction, table in zip(fractions, tables):\n    table['volume fraction'] = fraction\n\nareas = pd.concat(tables, axis=0)\n\n# Create custom grid of subplots\ngrid = plt.GridSpec(2, 2)\nax1 = plt.subplot(grid[0, 0])\nax2 = plt.subplot(grid[0, 1])\nax = plt.subplot(grid[1, :])\n# Show image with lowest volume fraction\nax1.imshow(images[0], cmap='gray_r')\nax1.set_axis_off()\nax1.set_title(f'fraction {fractions[0]}')\n# Show image with highest volume fraction\nax2.imshow(images[-1], cmap='gray_r')\nax2.set_axis_off()\nax2.set_title(f'fraction {fractions[-1]}')\n# Plot area vs volume fraction\nareas.plot(x='volume fraction', y='area', kind='scatter', ax=ax)\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "In the scatterplot, many points seem to be overlapping at low area values.\nTo get a better sense of the distribution, we may want to add some 'jitter'\nto the visualization. To this end, we use :obj:`seaborn.stripplot` (from\n[seaborn library](https://seaborn.pydata.org/) for statistical data visualization)\nwith argument ``jitter=True``.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "fig, ax = plt.subplots()\nsns.stripplot(x='volume fraction', y='area', data=areas, jitter=True, ax=ax)\n# Fix floating point rendering\nax.set_xticklabels([f'{frac:.2f}' for frac in fractions])\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 3D images\nDoing the same analysis in 3D, we find a much more dramatic behaviour: blobs\ncoalesce into a single, giant piece as the volume fraction crosses ~0.25.\nThis corresponds to the [percolation threshold](https://en.wikipedia.org/wiki/Percolation_threshold) in statistical\nphysics and graph theory.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "images = [data.binary_blobs(length=128, n_dim=3, volume_fraction=f) for f in fractions]\n\nlabeled_images = [measure.label(image) for image in images]\n\nproperties = ['label', 'area']\n\ntables = [\n    measure.regionprops_table(image, properties=properties) for image in labeled_images\n]\ntables = [pd.DataFrame(table) for table in tables]\n\nfor fraction, table in zip(fractions, tables):\n    table['volume fraction'] = fraction\n\nblob_volumes = pd.concat(tables, axis=0)\n\nfig, ax = plt.subplots()\nsns.stripplot(x='volume fraction', y='area', data=blob_volumes, jitter=True, ax=ax)\nax.set_ylabel('blob size (3D)')\n# Fix floating point rendering\nax.set_xticklabels([f'{frac:.2f}' for frac in fractions])\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
}