marching cubes in matlab

Marching Cubes is a popular algorithm for surface reconstruction of isosurfaces from volumetric data. Here's how you can implement it in MATLAB:

  1. Load your volumetric data into MATLAB. You can use load_nii function to read data from a NIfTI file, or load_mhd function to read data from a MetaImage file. Alternatively, you can create a volumetric data using rand function.
main.m
data = rand(64,64,64);
23 chars
2 lines
  1. Set an isovalue - a threshold value that defines the surface you want to extract from the volumetric data.
main.m
isovalue = 0.5;
16 chars
2 lines
  1. Create a meshgrid to represent the volumetric data as a set of cubes.
main.m
[X,Y,Z] = meshgrid(1:size(data,1), 1:size(data,2), 1:size(data,3));
68 chars
2 lines
  1. Run the isosurface function to extract the isosurface from the volumetric data.
main.m
P = isosurface(X,Y,Z,data,isovalue);
37 chars
2 lines
  1. Visualize the results using patch function to create a surface mesh.
main.m
patch(P,'FaceColor',[0.8 0.8 1.0],'EdgeColor','none');
axis equal; view(3);
camlight; lighting gouraud;
104 chars
4 lines

You can also use isosurface function with optional input arguments to adjust the isovalue and to create smoother surfaces.

main.m
P = isosurface(X,Y,Z,data,isovalue,'verbose');
P = reducepatch(P,0.1);   % reduces the number of patches to make the mesh smoother
131 chars
3 lines

Another option is to use isosurface function with patch function to create a patch object from the isosurface data.

main.m
[F,V,C] = isosurface(X,Y,Z,data,isovalue);
p = patch('Faces',F,'Vertices',V,'FaceColor',[0.8 0.8 1.0],'EdgeColor','none');
123 chars
3 lines

Finally, you can use isonormals function to compute the normal vectors at each vertex of the surface mesh, which can be used for lighting and shading effects.

main.m
n = isonormals(X,Y,Z,data,p.Vertices);
set(p,'VertexNormals',-n);
66 chars
3 lines

gistlibby LogSnag