{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Label image regions\n\nThis example shows how to segment an image with image labelling. The following\nsteps are applied:\n\n1. Thresholding with automatic Otsu method\n2. Close small holes with binary closing\n3. Remove artifacts touching image border\n4. Measure image regions to filter small objects\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import matplotlib.pyplot as plt\nimport matplotlib.patches as mpatches\n\nfrom skimage import data\nfrom skimage.filters import threshold_otsu\nfrom skimage.segmentation import clear_border\nfrom skimage.measure import label, regionprops\nfrom skimage.morphology import closing, footprint_rectangle\nfrom skimage.color import label2rgb\n\n\nimage = data.coins()[50:-50, 50:-50]\n\n# apply threshold\nthresh = threshold_otsu(image)\nbw = closing(image > thresh, footprint_rectangle((3, 3)))\n\n# remove artifacts connected to image border\ncleared = clear_border(bw)\n\n# label image regions\nlabel_image = label(cleared)\n# to make the background transparent, pass the value of `bg_label`,\n# and leave `bg_color` as `None` and `kind` as `overlay`\nimage_label_overlay = label2rgb(label_image, image=image, bg_label=0)\n\nfig, ax = plt.subplots(figsize=(10, 6))\nax.imshow(image_label_overlay)\n\nfor region in regionprops(label_image):\n    # take regions with large enough areas\n    if region.area >= 100:\n        # draw rectangle around segmented coins\n        minr, minc, maxr, maxc = region.bbox\n        rect = mpatches.Rectangle(\n            (minc, minr),\n            maxc - minc,\n            maxr - minr,\n            fill=False,\n            edgecolor='red',\n            linewidth=2,\n        )\n        ax.add_patch(rect)\n\nax.set_axis_off()\nplt.tight_layout()\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
}