{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Euler number\n\nThis example shows an illustration of the computation of the Euler number [1]_\nin 2D and 3D objects.\n\nFor 2D objects, the Euler number is the number of objects minus the number of\nholes. Notice that if a neighborhood of 8 connected pixels (2-connectivity)\nis considered for objects, then this amounts to considering a neighborhood\nof 4 connected pixels (1-connectivity) for the complementary set (holes,\nbackground) , and conversely. It is also possible to compute the number of\nobjects using :func:`skimage.measure.label`, and to deduce the number of holes\nfrom the difference between the two numbers.\n\nFor 3D objects, the Euler number is obtained as the number of objects plus the\nnumber of holes, minus the number of tunnels, or loops. If one uses\n3-connectivity for an object (considering the 26 surrounding voxels as its\nneighborhood), this corresponds to using 1-connectivity for the complementary\nset (holes, background), that is considering only 6 neighbors for a given\nvoxel. The voxels are represented here with blue transparent surfaces.\nInner porosities are represented in red.\n\n.. [1] https://en.wikipedia.org/wiki/Euler_characteristic\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import skimage as ski\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\n# Sample image.\nSAMPLE = np.array(\n    [\n        [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0],\n        [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0],\n        [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0],\n        [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0],\n        [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0],\n        [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0],\n        [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0],\n        [1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0],\n        [0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1],\n        [0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1],\n    ]\n)\nSAMPLE = np.pad(SAMPLE, 1, mode='constant')\n\nfig, ax = plt.subplots()\nax.imshow(SAMPLE, cmap=plt.cm.gray)\nax.axis('off')\ne4 = ski.measure.euler_number(SAMPLE, connectivity=1)\nobject_nb_4 = ski.measure.label(SAMPLE, connectivity=1).max()\nholes_nb_4 = object_nb_4 - e4\ne8 = ski.measure.euler_number(SAMPLE, connectivity=2)\nobject_nb_8 = ski.measure.label(SAMPLE, connectivity=2).max()\nholes_nb_8 = object_nb_8 - e8\nax.set_title(\n    f'Euler number for N4: {e4} ({object_nb_4} objects, {holes_nb_4} '\n    f'holes), \\n for N8: {e8} ({object_nb_8} objects, '\n    f'{holes_nb_8} holes)'\n)\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 3-D objects\n\nIn this example, a 3-D cube is generated, then holes and\ntunnels are added. Euler number is evaluated with 6 and 26 neighborhood\nconfiguration. This code is inspired by\nhttps://matplotlib.org/devdocs/gallery/mplot3d/voxels_numpy_logo.html\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "def make_ax(grid=False):\n    fig, ax = plt.subplots(subplot_kw={'projection': '3d'})\n    ax.grid(grid)\n    ax.set_axis_off()\n    return fig, ax\n\n\ndef explode(data):\n    \"\"\"visualization to separate voxels\n\n    Data voxels are separated by 0-valued ones so that they appear\n    separated in the matplotlib figure.\n    \"\"\"\n    size = np.array(data.shape) * 2\n    data_e = np.zeros(size - 1, dtype=data.dtype)\n    data_e[::2, ::2, ::2] = data\n    return data_e\n\n\n# shrink the gaps between voxels\n\n\ndef expand_coordinates(indices):\n    \"\"\"\n    This collapses together pairs of indices, so that\n    the gaps in the volume array will have a zero width.\n    \"\"\"\n    x, y, z = indices\n    x[1::2, :, :] += 1\n    y[:, 1::2, :] += 1\n    z[:, :, 1::2] += 1\n    return x, y, z\n\n\ndef display_voxels(volume):\n    \"\"\"\n    volume: (N,M,P) array\n            Represents a binary set of pixels: objects are marked with 1,\n            complementary (porosities) with 0.\n\n    The voxels are actually represented with blue transparent surfaces.\n    Inner porosities are represented in red.\n    \"\"\"\n\n    # define colors\n    red = '#ff0000ff'\n    blue = '#1f77b410'\n\n    # upscale the above voxel image, leaving gaps\n    filled = explode(np.ones(volume.shape))\n\n    fcolors = explode(np.where(volume, blue, red))\n\n    # Shrink the gaps\n    x, y, z = expand_coordinates(np.indices(np.array(filled.shape) + 1))\n\n    # Define 3D figure and place voxels\n    _, ax = make_ax()\n    ax.voxels(x, y, z, filled, facecolors=fcolors)\n    # Compute Euler number in 6 and 26 neighborhood configuration, that\n    # correspond to 1 and 3 connectivity, respectively\n    e26 = ski.measure.euler_number(volume, connectivity=3)\n    e6 = ski.measure.euler_number(volume, connectivity=1)\n    ax.set_title(f'Euler number for N26: {e26}, for N6: {e6}')\n    plt.show()\n\n\n# Define a volume of 7x7x7 voxels\nn = 7\ncube = np.ones((n, n, n), dtype=bool)\n# Add a tunnel\nc = int(n / 2)\ncube[c, :, c] = False\n# Add a new hole\ncube[int(3 * n / 4), c - 1, c - 1] = False\n# Add a hole in neighborhood of previous one\ncube[int(3 * n / 4), c, c] = False\n# Add a second tunnel\ncube[:, c, int(3 * n / 4)] = False\ndisplay_voxels(cube)"
      ]
    }
  ],
  "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
}