{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Measure region properties\n\nThis example shows how to measure properties of labelled image regions. We\nfirst analyze an image with two ellipses. Below we show how to explore\ninteractively the properties of labelled objects.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import math\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\nfrom skimage.draw import ellipse\nfrom skimage.measure import label, regionprops, regionprops_table\nfrom skimage.transform import rotate\n\n\nimage = np.zeros((600, 600))\n\nrr, cc = ellipse(300, 350, 100, 220)\nimage[rr, cc] = 1\n\nimage = rotate(image, angle=15, order=0)\n\nrr, cc = ellipse(100, 100, 60, 50)\nimage[rr, cc] = 1\n\nlabel_img = label(image)\nregions = regionprops(label_img)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We use the :py:func:`skimage.measure.regionprops` result to draw certain\nproperties on each region. For example, in red, we plot the major and minor\naxes of each ellipse.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "fig, ax = plt.subplots()\nax.imshow(image, cmap=plt.cm.gray)\n\nfor props in regions:\n    y0, x0 = props.centroid\n    orientation = props.orientation\n    x1 = x0 + math.cos(orientation) * 0.5 * props.axis_minor_length\n    y1 = y0 - math.sin(orientation) * 0.5 * props.axis_minor_length\n    x2 = x0 - math.sin(orientation) * 0.5 * props.axis_major_length\n    y2 = y0 - math.cos(orientation) * 0.5 * props.axis_major_length\n\n    ax.plot((x0, x1), (y0, y1), '-r', linewidth=2.5)\n    ax.plot((x0, x2), (y0, y2), '-r', linewidth=2.5)\n    ax.plot(x0, y0, '.g', markersize=15)\n\n    minr, minc, maxr, maxc = props.bbox\n    bx = (minc, maxc, maxc, minc, minc)\n    by = (minr, minr, maxr, maxr, minr)\n    ax.plot(bx, by, '-b', linewidth=2.5)\n\nax.axis((0, 600, 600, 0))\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We use the :py:func:`skimage.measure.regionprops_table` function to compute\n(selected) properties for each region. Note that\n``skimage.measure.regionprops_table`` actually computes the properties,\nwhereas ``skimage.measure.regionprops`` computes them when they come in use\n(lazy evaluation).\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "props = regionprops_table(\n    label_img,\n    properties=('centroid', 'orientation', 'axis_major_length', 'axis_minor_length'),\n)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We now display a table of these selected properties (one region per row),\nthe ``skimage.measure.regionprops_table`` result being a pandas-compatible\ndict.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "pd.DataFrame(props)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "It is also possible to explore interactively the properties of labelled\nobjects by visualizing them in the hover information of the labels.\nThis example uses plotly in order to display properties when\nhovering over the objects.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import plotly\nimport plotly.express as px\nimport plotly.graph_objects as go\nfrom skimage import data, filters, measure, morphology\n\nimg = data.coins()\n# Binary image, post-process the binary mask and compute labels\nthreshold = filters.threshold_otsu(img)\nmask = img > threshold\nmask = morphology.remove_small_objects(mask, max_size=49)\nmask = morphology.remove_small_holes(mask, max_size=49)\nlabels = measure.label(mask)\n\nfig = px.imshow(img, binary_string=True)\nfig.update_traces(hoverinfo='skip')  # hover is only for label info\n\nprops = measure.regionprops(labels, img)\nproperties = ['area', 'eccentricity', 'perimeter', 'intensity_mean']\n\n# For each label, add a filled scatter trace for its contour,\n# and display the properties of the label in the hover of this trace.\nfor index in range(1, labels.max()):\n    label_i = props[index].label\n    contour = measure.find_contours(labels == label_i, 0.5)[0]\n    y, x = contour.T\n    hoverinfo = ''\n    for prop_name in properties:\n        hoverinfo += f'<b>{prop_name}: {getattr(props[index], prop_name):.2f}</b><br>'\n    fig.add_trace(\n        go.Scatter(\n            x=x,\n            y=y,\n            name=label_i,\n            mode='lines',\n            fill='toself',\n            showlegend=False,\n            hovertemplate=hoverinfo,\n            hoveron='points+fills',\n        )\n    )\n\nplotly.io.show(fig)"
      ]
    }
  ],
  "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
}