{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "# Demo mathematical morphology\n",
    "\n",
    "A basic demo of binary opening and closing.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 25972 characters]",
      "text/plain": [
       "<Figure size 1200x350 with 4 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# Generate some binary data\n",
    "import numpy as np\n",
    "\n",
    "np.random.seed(0)\n",
    "a = np.zeros((50, 50))\n",
    "a[10:-10, 10:-10] = 1\n",
    "a += 0.25 * np.random.standard_normal(a.shape)\n",
    "mask = a >= 0.5\n",
    "\n",
    "# Apply mathematical morphology\n",
    "import scipy as sp\n",
    "\n",
    "opened_mask = sp.ndimage.binary_opening(mask)\n",
    "closed_mask = sp.ndimage.binary_closing(opened_mask)\n",
    "\n",
    "# Plot\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "plt.figure(figsize=(12, 3.5))\n",
    "plt.subplot(141)\n",
    "plt.imshow(a, cmap=\"gray\")\n",
    "plt.axis(\"off\")\n",
    "plt.title(\"a\")\n",
    "\n",
    "plt.subplot(142)\n",
    "plt.imshow(mask, cmap=\"gray\")\n",
    "plt.axis(\"off\")\n",
    "plt.title(\"mask\")\n",
    "\n",
    "plt.subplot(143)\n",
    "plt.imshow(opened_mask, cmap=\"gray\")\n",
    "plt.axis(\"off\")\n",
    "plt.title(\"opened_mask\")\n",
    "\n",
    "plt.subplot(144)\n",
    "plt.imshow(closed_mask, cmap=\"gray\")\n",
    "plt.title(\"closed_mask\")\n",
    "plt.axis(\"off\")\n",
    "\n",
    "plt.subplots_adjust(wspace=0.05, left=0.01, bottom=0.01, right=0.99, top=0.99)\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "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": 4
}
