Skip to content
Snippets Groups Projects
erode_dilate_segmentation.ipynb 4.09 KiB
Newer Older
  • Learn to ignore specific revisions
  • fima's avatar
    fima committed
    {
     "cells": [
      {
       "cell_type": "markdown",
       "id": "a17e6d9a",
       "metadata": {},
       "source": [
        "# Erode and dilate masks\n",
        "Notebook author: Thorbjørn Erik Køppen Christensen (tekc@dtu.dk)\n",
        "\n",
        "This notebook can be used to run erosion and dilation on binary masks.\n",
        "This can be useful for removing \"noisy\" attatchments, closing holes and smoothing edges of masks.\n",
        "Can run in either 2D (circle) or 3D (sphere). Note that the 3D version is somewhat more expensive in memory requirements"
       ]
      },
      {
       "cell_type": "markdown",
       "id": "2801d11e",
       "metadata": {},
       "source": [
        "## Import Libraries"
       ]
      },
      {
       "cell_type": "code",
       "execution_count": 31,
       "id": "386d5c86",
       "metadata": {},
       "outputs": [],
       "source": [
        "import numpy as np\n",
        "import h5py\n",
        "import qim3d\n",
        "import scipy.ndimage"
       ]
      },
      {
       "cell_type": "markdown",
       "id": "7e2a79e1",
       "metadata": {},
       "source": [
        "## Define functions"
       ]
      },
      {
       "cell_type": "code",
       "execution_count": 77,
       "id": "90f12d70",
       "metadata": {},
       "outputs": [],
       "source": [
        "def structure_sphere(r,dims=3):\n",
        "    #Creates a sphere of with radius r in dims dimensions\n",
        "    #r is in pixels\n",
        "    \n",
        "    d = 2*r-1 #The \"-1\" is to combat a small offeset from indexing starting at 0\n",
        "    #Define the center for dims dimensions\n",
        "    if r % 2 ==0:\n",
        "        center = (np.s_[r-1:r],)*dims \n",
        "    else:\n",
        "        center = np.s_[(r-1,)*dims]\n",
        "        \n",
        "    #turn everything within r indices of center into 1\n",
        "    vol = np.zeros((d,)*dims)\n",
        "    vol[center] = 1\n",
        "    distance = scipy.ndimage.distance_transform_edt(1-vol)\n",
        "    vol[distance<=r-1] = 1\n",
        "    vol[distance>1] = 0\n",
        "    return vol"
       ]
      },
      {
       "cell_type": "markdown",
       "id": "babfd650",
       "metadata": {},
       "source": [
        "## Load data"
       ]
      },
      {
       "cell_type": "code",
       "execution_count": 71,
       "id": "8a8cec6f",
       "metadata": {},
       "outputs": [],
       "source": [
        "# Load data\n",
        "filename = \"../resources/img3d/shell_225x128x128_bin_mask.h5\"\n",
        "vol = qim3d.io.load(filename) "
       ]
      },
      {
       "cell_type": "markdown",
       "id": "3afb4c6e",
       "metadata": {},
       "source": [
        "## Erode and dilate"
       ]
      },
      {
       "cell_type": "code",
       "execution_count": 80,
       "id": "e30210bd",
       "metadata": {},
       "outputs": [],
       "source": [
        "# Erode and dilate\n",
        "\n",
        "vol = structure_sphere(100)\n",
        "sphere = structure_sphere(5)\n",
        "vol = scipy.ndimage.binary_erosion(vol, structure=sphere.astype(vol.dtype))\n",
        "vol = scipy.ndimage.binary_dilation(vol, structure=sphere.astype(vol.dtype))"
       ]
      },
      {
       "cell_type": "markdown",
       "id": "357a1f48",
       "metadata": {},
       "source": [
        "## Save eroded/dilated volume"
       ]
      },
      {
       "cell_type": "code",
       "execution_count": 81,
       "id": "e3243a93",
       "metadata": {},
       "outputs": [
        {
         "data": {
          "text/plain": [
           "(slice(1, 2, None), slice(1, 2, None), slice(1, 2, None))"
          ]
         },
         "execution_count": 81,
         "metadata": {},
         "output_type": "execute_result"
        }
       ],
       "source": [
        "#Save binary_segmentation\n",
        "save_folder = '../resources/img3d/'\n",
        "save_file = filename.split('/')[-1].split('.')[0] + '_eroded_dilated.h5'\n",
        "with h5py.file(os.path.join(save_folder,save_file),'w') as sfile:\n",
        "    sfile.create_dataset('mask/eroded',data=vol)"
       ]
      },
      {
       "cell_type": "code",
       "execution_count": null,
       "id": "dcfadd98",
       "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.11.5"
      }
     },
     "nbformat": 4,
     "nbformat_minor": 5
    }