Triangle mesh filled contour in MATLAB

Alec Jacobson

December 06, 2010

weblog/

Here is matlab snippet that takes a 2D triangle mesh and a function and produces a pretty, filled contour plot in MATLAB. If your mesh vertices are stored in V, and your triangles in F, then use my previously posted code to get the boundary/outline edges of your mesh in O. Then you can create a contour plot of some function W defined over V using:
% resample W with a grid, THIS IS VERY SLOW if V is large
[Xr,Yr,Wr] = griddata(V(:,1),V(:,2),W,unique(V(:,1)),unique(V(:,2))');
% find all points inside the mesh, THIS IS VERY SLOW if V is large
IN = inpolygon(Xr,Yr,V(O,1),V(O,2));
% don't draw points outside the mesh
Wr(~IN) = NaN;
contourf(Xr,Yr,Wr)
And for a mesh like this one: gingerbread man mesh plot You get something like this: gingerbread man contour 10 level sets You can also approach a continuous contour with this:
contourf(Xr,Yr,Wr,200)
shading flat
gingerbread man contour 200 level sets Compare this to what you can get from the much faster:
trisurf(F,V(:,1),V(:,2),W,'FaceColor','interp','EdgeColor','interp')
view(2)
which produces: gingerbread man colored plot The only problem with this method is that the boundary looks a little nasty because of the resampling. Nothing that can't be fixed quickly in photoshop... Or even in MATLAB with something like:
line(V([O(:);O(1)],1),V([O(:);O(1)],2),'Color','k','LineWidth',6)
Which puts an ugly thick outline around the contour, but makes it look a little better... gingerbread man contour 10 level sets with outline Source