{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Demo connected components\n\nExtracting and labeling connected components in a 2D array\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\nimport matplotlib.pyplot as plt" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Generate some binary data\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "x, y = np.indices((100, 100))\nsig = (\n np.sin(2 * np.pi * x / 50.0)\n * np.sin(2 * np.pi * y / 50.0)\n * (1 + x * y / 50.0**2) ** 2\n)\nmask = sig > 1\n\nplt.figure(figsize=(7, 3.5))\nplt.subplot(1, 2, 1)\nplt.imshow(sig)\nplt.axis(\"off\")\nplt.title(\"sig\")\n\nplt.subplot(1, 2, 2)\nplt.imshow(mask, cmap=\"gray\")\nplt.axis(\"off\")\nplt.title(\"mask\")\nplt.subplots_adjust(wspace=0.05, left=0.01, bottom=0.01, right=0.99, top=0.9)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Label connected components\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import scipy as sp\n\nlabels, nb = sp.ndimage.label(mask)\n\nplt.figure(figsize=(3.5, 3.5))\nplt.imshow(labels)\nplt.title(\"label\")\nplt.axis(\"off\")\n\nplt.subplots_adjust(wspace=0.05, left=0.01, bottom=0.01, right=0.99, top=0.9)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Extract the 4th connected component, and crop the array around it\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "sl = sp.ndimage.find_objects(labels == 4)\nplt.figure(figsize=(3.5, 3.5))\nplt.imshow(sig[sl[0]])\nplt.title(\"Cropped connected component\")\nplt.axis(\"off\")\n\nplt.subplots_adjust(wspace=0.05, left=0.01, bottom=0.01, right=0.99, top=0.9)\n\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.11" } }, "nbformat": 4, "nbformat_minor": 0 }