Search code examples
matlabplot3dmeshpoint-clouds

How to plot a 3D triangle mesh shape with a specific colormap in MATLAB?


A 3D triangle mesh shape is represented by vertices and triangle faces. For example, shape in matlab which has shape.X, shape.Y, shape.Z(the vertices) and shape.TRIV(the triangle faces) can be seen as a 3D triangle mesh shape.

My question is how to visualize such a shape in MATLAB with a specific colormap.

(for example, the colormap can be defined as a distance vector of length(shape.X) whose elements are Euclidean distances of all vertices to a single vertex M, in this situation, the cooler colors related to the smaller distances, and the hotter colors related to the larger distances.)


Solution

  • Based on @Suever's answer, I add some extra code to make the shape plot smoother and add a camera light. By the way, if the shape is a point cloud without faces, it's better to choose scatter3 instead of plot3.

    vertices = cat(2, shape.X(:), shape.Y(:), shape.Z(:));
    
    %// Compute distance of each vertex from the origin
    distances = sqrt(sum(bsxfun(@minus, vertices, [0 0 0]).^2, 2)); 
    
    %// Create the patch object
    h = patch('Vertices', vertices, 'Faces', shape.TRIV);
    
    %// Set the vertex colors and use interpolation to shade the faces
    set(h, 'FaceColor', 'interp', 'FaceVertexCData', distances,'EdgeColor', 'none');
    %or use shading interp instead of setting 'EdgeColor'=='none' to make the shape smooth;
    
    %// Scale the color limits to your data
    set(gca, 'clim', [min(distances(:)), max(distances(:))])
    
    % add a colorbar
    colorbar
    
    % change the colormap
    colormap(jet(64))
    
    %use the same unit length along each axis  and fit the axes box tightly around the data.
    axis image 
    
    % turn off the coordinate
    axis off
    
    % set the camlight strength, trial and error
    set(h, 'AmbientStrength',0.25, 'SpecularStrength',0.0,'DiffuseStrength',0.5);
    lighting phong;
    camlight left; %left,right,head
    set(gcf,'Renderer','opengl');  %‘opengl’,'zbuffer'
    

    If it's a point cloud:

    h2=scatter3(X,Y,Z,'.');
    view([0,90]);
    h2.CData=distances;
    axis image;
    set(gca, 'clim', [min(distances(:)), max(distances(:))]);
    colormap(jet(64));