write_ply

Write mesh data to ply format mesh file

Contents

Syntax

write_ply(filename,face,vertex)
write_ply(filename,face,vertex,color)

Description

filename: string, file to read.
face    : double array, nf x 3 array specifying the connectivity of the mesh.
vertex  : double array, nv x 3 array specifying the position of the vertices.
color   : double array, nv x 3 or nf x 3 array specifying the color of the vertices or faces.

Example

write_ply('cube.ply',face,vertex);
write_ply('cube.ply',face,vertex,color);

Contribution

Author : Meng Bin
Created: 2014/03/05
Revised: 2014/03/07 by Meng Bin, block write to enhance writing speed
Revised: 2014/03/17 by Meng Bin, modify doc format
Copyright 2014 Computational Geometry Group
Department of Mathematics, CUHK
http://www.math.cuhk.edu.hk/~lmlui
function write_ply(filename,face,vertex,color)

fid = fopen(filename,'wt');
if( fid==-1 )
    error('Can''t open the file.');
end

nvert = size(vertex, 1);
nface = size(face, 1);
nvert_face = size(face, 2);


ncolor =0;
if nargin < 4
    color = [];
end
if ~isempty(color)
    ncolor = size(color, 1);
	if size(color, 2) < 3
		error('color matrix dimension must > 3');
	end
end

%write header
fprintf (fid, 'ply\n');
fprintf (fid, 'format ascii 1.0\n');
fprintf (fid, 'comment generated by geometric processing package\n');
fprintf (fid, 'element vertex %d\n',nvert);
fprintf (fid, 'property float x\n');
fprintf (fid, 'property float y\n');
fprintf (fid, 'property float z\n');
if ~isempty(color) && ncolor == nvert
    fprintf (fid, 'property red uchar\n');
	fprintf (fid, 'property green uchar\n');
	fprintf (fid, 'property blue uchar\n');
end
fprintf (fid, 'element face %d\n',nface);
fprintf (fid, 'property list uchar int vertex_indices\n');
if ~isempty(color) && ncolor == nface && ncolor ~= nvert
    fprintf (fid, 'property red uchar\n');
	fprintf (fid, 'property green uchar\n');
	fprintf (fid, 'property blue uchar\n');
end
fprintf (fid, 'end_header\n');

if nvert == ncolor
	vertex = [vertex';color']';
end
if nface == ncolor && nvert ~= ncolor
	face =[zeros(1,nface)+nvert_face; face'-1;color']';
else
	face =[zeros(1,nface)+nvert_face;face'-1]';
end
%write vertex
dlmwrite(filename,vertex,'-append',...
         'delimiter',' ',...
         'precision', 6,...
         'newline','pc');
%write face
dlmwrite(filename,face,'-append',...
         'delimiter',' ',...
         'newline','pc');

fclose(fid);