{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Decompose flat footprints (structuring elements)\n\nMany footprints (structuring elements) can be decomposed into an equivalent\nseries of smaller structuring elements. The term \"flat\" refers to footprints\nthat only contain values of 0 or 1 (i.e., all methods in\n``skimage.morphology.footprints``). Binary dilation operations have an\nassociative and distributive property that often allows decomposition into\nan equivalent series of smaller footprints. Most often this is done to provide\na performance benefit.\n\nAs a concrete example, dilation with a square footprint of shape (15, 15) is\nequivalent to dilation with a rectangle of shape (15, 1) followed by another\ndilation with a rectangle of shape (1, 15). It is also equivalent to 7\nconsecutive dilations with a square footprint of shape (3, 3).\n\nThere are many possible decompositions and which one performs best may be\narchitecture-dependent.\n\nscikit-image currently provides two forms of automated decomposition. For the\ncases of ``square``, ``rectangle`` and ``cube`` footprints, there is an option\nfor a \"separable\" decomposition (size > 1 along only one axis at a time).\n\nThere is no separable decomposition into 1D operations for some other symmetric\nconvex shapes, e.g., ``diamond``, ``octahedron`` and ``octagon``. However, it\nis possible to provide a \"sequence\" decomposition based on a series of small\nfootprints of shape ``(3,) * ndim``.\n\nFor simplicity of implementation, all decompositions shown below use only\nodd-sized footprints with their origin located at the center of the footprint.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import colors\nfrom mpl_toolkits.mplot3d import Axes3D\n\nimport skimage as ski\n\n\n# Generate 2D and 3D structuring elements.\nfootprint_dict = {\n    \"square 11x11 (separable)\": (\n        ski.morphology.footprint_rectangle((11, 11), decomposition=None),\n        ski.morphology.footprint_rectangle((11, 11), decomposition=\"separable\"),\n    ),\n    \"square 11x11 (sequence)\": (\n        ski.morphology.footprint_rectangle((11, 11), decomposition=None),\n        ski.morphology.footprint_rectangle((11, 11), decomposition=\"sequence\"),\n    ),\n    \"rectangle 7x11 (separable)\": (\n        ski.morphology.footprint_rectangle((7, 11), decomposition=None),\n        ski.morphology.footprint_rectangle((7, 11), decomposition=\"separable\"),\n    ),\n    \"rectangle 7x11 (sequence)\": (\n        ski.morphology.footprint_rectangle((7, 11), decomposition=None),\n        ski.morphology.footprint_rectangle((7, 11), decomposition=\"sequence\"),\n    ),\n    \"diamond(5) (sequence)\": (\n        ski.morphology.diamond(5, decomposition=None),\n        ski.morphology.diamond(5, decomposition=\"sequence\"),\n    ),\n    \"disk(7, strict_radius=False) (sequence)\": (\n        ski.morphology.disk(7, strict_radius=False, decomposition=None),\n        ski.morphology.disk(7, strict_radius=False, decomposition=\"sequence\"),\n    ),\n    \"disk(7, strict_radius=True) (crosses)\": (\n        ski.morphology.disk(7, strict_radius=True, decomposition=None),\n        ski.morphology.disk(7, strict_radius=True, decomposition=\"crosses\"),\n    ),\n    \"ellipse(4, 9) (crosses)\": (\n        ski.morphology.ellipse(4, 9, decomposition=None),\n        ski.morphology.ellipse(4, 9, decomposition=\"crosses\"),\n    ),\n    \"disk(20) (sequence)\": (\n        ski.morphology.disk(20, strict_radius=False, decomposition=None),\n        ski.morphology.disk(20, strict_radius=False, decomposition=\"sequence\"),\n    ),\n    \"octagon(7, 4) (sequence)\": (\n        ski.morphology.octagon(7, 4, decomposition=None),\n        ski.morphology.octagon(7, 4, decomposition=\"sequence\"),\n    ),\n    \"cube 11x11x11 (separable)\": (\n        ski.morphology.footprint_rectangle((11, 11, 11), decomposition=None),\n        ski.morphology.footprint_rectangle((11, 11, 11), decomposition=\"separable\"),\n    ),\n    \"cube 11x11x11 (sequence)\": (\n        ski.morphology.footprint_rectangle((11, 11, 11), decomposition=None),\n        ski.morphology.footprint_rectangle((11, 11, 11), decomposition=\"sequence\"),\n    ),\n    \"octahedron(7) (sequence)\": (\n        ski.morphology.octahedron(7, decomposition=None),\n        ski.morphology.octahedron(7, decomposition=\"sequence\"),\n    ),\n    \"ball(9) (sequence)\": (\n        ski.morphology.ball(9, strict_radius=False, decomposition=None),\n        ski.morphology.ball(9, strict_radius=False, decomposition=\"sequence\"),\n    ),\n}\n\n# Visualize the elements\n\n# binary white / blue colormap\ncmap = colors.ListedColormap(['white', (0.1216, 0.4706, 0.70588)])\n\nfontdict = dict(fontsize=16, fontweight='bold')\nfor title, (footprint, footprint_sequence) in footprint_dict.items():\n    ndim = footprint.ndim\n    num_seq = len(footprint_sequence)\n    approximate_decomposition = 'ball' in title or 'disk' in title or 'ellipse' in title\n    if approximate_decomposition:\n        # Two extra plot in approximate cases to show both:\n        # 1.) decomposition=None idea footprint\n        # 2.) actual composite footprint corresponding to the sequence\n        num_subplots = num_seq + 2\n    else:\n        # composite and decomposition=None are identical so only 1 extra plot\n        num_subplots = num_seq + 1\n    fig = plt.figure(figsize=(4 * num_subplots, 5))\n    if ndim == 2:\n        ax = fig.add_subplot(1, num_subplots, num_subplots)\n        ax.imshow(footprint, cmap=cmap, vmin=0, vmax=1)\n        if approximate_decomposition:\n            ax2 = fig.add_subplot(1, num_subplots, num_subplots - 1)\n            footprint_composite = ski.morphology.footprint_from_sequence(\n                footprint_sequence\n            )\n            ax2.imshow(footprint_composite, cmap=cmap, vmin=0, vmax=1)\n\n    else:\n        ax = fig.add_subplot(1, num_subplots, num_subplots, projection=Axes3D.name)\n        ax.voxels(footprint, cmap=cmap)\n        if approximate_decomposition:\n            ax2 = fig.add_subplot(\n                1, num_subplots, num_subplots - 1, projection=Axes3D.name\n            )\n            footprint_composite = ski.morphology.footprint_from_sequence(\n                footprint_sequence\n            )\n            ax2.voxels(footprint_composite, cmap=cmap)\n\n    title1 = title.split(' (')[0]\n    if approximate_decomposition:\n        # plot decomposition=None on a separate axis from the composite\n        title = title1 + '\\n(decomposition=None)'\n    else:\n        # for exact cases composite and decomposition=None are identical\n        title = title1 + '\\n(composite)'\n    ax.set_title(title, fontdict=fontdict)\n    ax.set_axis_off()\n    if approximate_decomposition:\n        ax2.set_title(title1 + '\\n(composite)', fontdict=fontdict)\n        ax2.set_axis_off()\n\n    for n, (fp, num_reps) in enumerate(footprint_sequence):\n        npad = [((footprint.shape[d] - fp.shape[d]) // 2,) * 2 for d in range(ndim)]\n        fp = np.pad(fp, npad, mode='constant')\n        if ndim == 2:\n            ax = fig.add_subplot(1, num_subplots, n + 1)\n            ax.imshow(fp, cmap=cmap, vmin=0, vmax=1)\n        else:\n            ax = fig.add_subplot(1, num_subplots, n + 1, projection=Axes3D.name)\n            ax.voxels(fp, cmap=cmap)\n        title = f\"element {n + 1} of {num_seq}\\n({num_reps} iteration\"\n        title += \"s)\" if num_reps > 1 else \")\"\n        ax.set_title(title, fontdict=fontdict)\n        ax.set_axis_off()\n        ax.set_xlabel(f'num_reps = {num_reps}')\n    fig.tight_layout()\n\n    # draw a line separating the sequence elements from the composite\n    line_pos = num_seq / num_subplots\n    line = plt.Line2D([line_pos, line_pos], [0, 1], color=\"black\")\n    fig.add_artist(line)\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.12"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}