{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Marching Cubes\n\nMarching cubes is an algorithm to extract a 2D surface mesh from a 3D volume.\nThis can be conceptualized as a 3D generalization of isolines on topographical\nor weather maps. It works by iterating across the volume, looking for regions\nwhich cross the level of interest. If such regions are found, triangulations\nare generated and added to an output mesh. The final result is a set of\nvertices and a set of triangular faces.\n\nThe algorithm requires a data volume and an isosurface value. For example, in\nCT imaging Hounsfield units of +700 to +3000 represent bone. So, one potential\ninput would be a reconstructed CT set of data and the value +700, to extract\na mesh for regions of bone or bone-like density.\n\nThis implementation also works correctly on anisotropic datasets, where the\nvoxel spacing is not equal for every spatial dimension, through use of the\n`spacing` kwarg.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d.art3d import Poly3DCollection\n\nfrom skimage import measure\nfrom skimage.draw import ellipsoid\n\n\n# Generate a level set about zero of two identical ellipsoids in 3D\nellip_base = ellipsoid(6, 10, 16, levelset=True)\nellip_double = np.concatenate((ellip_base[:-1, ...], ellip_base[2:, ...]), axis=0)\n\n# Use marching cubes to obtain the surface mesh of these ellipsoids\nverts, faces, normals, values = measure.marching_cubes(ellip_double, 0)\n\n# Display resulting triangular mesh using Matplotlib. This can also be done\n# with mayavi (see skimage.measure.marching_cubes docstring).\nfig = plt.figure(figsize=(10, 10))\nax = fig.add_subplot(111, projection='3d')\n\n# Fancy indexing: `verts[faces]` to generate a collection of triangles\nmesh = Poly3DCollection(verts[faces])\nmesh.set_edgecolor('k')\nax.add_collection3d(mesh)\n\nax.set_xlabel(\"x-axis: a = 6 per ellipsoid\")\nax.set_ylabel(\"y-axis: b = 10\")\nax.set_zlabel(\"z-axis: c = 16\")\n\nax.set_xlim(0, 24)  # a = 6 (times two for 2nd ellipsoid)\nax.set_ylim(0, 20)  # b = 10\nax.set_zlim(0, 32)  # c = 16\n\nplt.tight_layout()\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
}