ply_read.m 16.4 KB
Newer Older
Radim Tylecek's avatar
Radim Tylecek committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663
function [ Elements, varargout ] = ply_read ( Path, Str )
%% PLY_READ reads a PLY 3D data file.
%
%   [DATA,COMMENTS] = PLY_READ(FILENAME) reads a version 1.0 PLY file
%   FILENAME and returns a structure DATA.  The fields in this structure
%   are defined by the PLY header; each element type is a field and each
%   element property is a subfield.  If the file contains any comments,
%   they are returned in a cell string array COMMENTS.
%
%   [TRI,PTS] = PLY_READ(FILENAME,'tri') or
%   [TRI,PTS,DATA,COMMENTS] = PLY_READ(FILENAME,'tri') converts vertex
%   and face data into triangular connectivity and vertex arrays.  The
%   mesh can then be displayed using the TRISURF command.
%
%   Note: This function is slow for large mesh files (+50K faces),
%   especially when reading data with list type properties.
%
%   Example:
%   [Tri,Pts] = PLY_READ('cow.ply','tri');
%   trisurf(Tri,Pts(:,1),Pts(:,2),Pts(:,3));
%   colormap(gray); axis equal;
%
%  Discussion:
%
%    The original version of this program had a mistake that meant it
%    did not properly triangulate files whose faces were not already triangular.
%    This has been corrected (JVB, 25 February 2007).
%
%    Glenn Ramsey pointed out and corrected a problem that occurred
%    with an uninitialized value of Type2, 27 August 2012.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    27 August 2012
%
%  Author:
%
%    Pascal Getreuer 2004
%
%  Parameters:
%
%  Local Parameters:
%
%    COMMENTS, any comments from the file.
%
%    ELEMENTCOUNT, the number of each type of element in file.
%
%    ELEMENTS, the element data.
%
%    PROPERTYTYPES, the element property types.
%
%    SIZEOF, size in bytes of each type.
%

%
%  Open the input file in "read text" mode.
%
[ fid, Msg ] = fopen ( Path, 'rt' );

if ( fid == -1 )
  error ( Msg );
end

Buf = fscanf ( fid, '%s', 1 );

if ( ~strcmp ( Buf, 'ply' ) )
  fclose ( fid );
  error('Not a PLY file.');
end
%
%  Read the header.
%
Position = ftell(fid);
Format = '';
NumComments = 0;
Comments = {};
NumElements = 0;
NumProperties = 0;
Elements = [];
ElementCount = [];
PropertyTypes = [];
ElementNames = {};  % list of element names in the order they are stored in the file
PropertyNames = [];  % structure of lists of property names

while ( 1 )
  %
  %  Read a line from the file.
  %
  Buf = fgetl ( fid );
  BufRem = Buf;
  Token = {};
  Count = 0;
  %
  %  Split the line into tokens.
  %
  while ( ~isempty(BufRem) )
    
    [ tmp, BufRem ] = strtok(BufRem);
    %
    %  Count the tokens.
    %
    if ( ~isempty ( tmp ) )
      Count = Count + 1;
      Token{Count} = tmp;
    end
    
  end
  %
  %  Parse the line.
  %
  if ( Count )
    
    switch lower ( Token{1} )
      %
      %  Read the data format.
      %
      case 'format'
        
        if ( 2 <= Count )
          
          Format = lower ( Token{2} );
          
          if ( Count == 3 & ~strcmp ( Token{3}, '1.0' ) )
            fclose ( fid );
            error('Only PLY format version 1.0 supported.');
          end
        end
        %
        %  Read a comment.
        %
      case 'comment'
        
        NumComments = NumComments + 1;
        Comments{NumComments} = '';
        for i = 2 : Count
          Comments{NumComments} = [Comments{NumComments},Token{i},' '];
        end
        %
        %  Read an element name.
        %
      case 'element'
        
        if ( 3 <= Count )
          
          if ( isfield(Elements,Token{2}) )
            fclose ( fid );
            error(['Duplicate element name, ''',Token{2},'''.']);
          end
          
          NumElements = NumElements + 1;
          NumProperties = 0;
          Elements = setfield(Elements,Token{2},[]);
          PropertyTypes = setfield(PropertyTypes,Token{2},[]);
          ElementNames{NumElements} = Token{2};
          PropertyNames = setfield(PropertyNames,Token{2},{});
          CurElement = Token{2};
          ElementCount(NumElements) = str2double(Token{3});
          
          if ( isnan(ElementCount(NumElements)) )
            fclose ( fid );
            error(['Bad element definition: ',Buf]);
          end
          
        else
          
          error(['Bad element definition: ',Buf]);
          
        end
        %
        %  Read an element property.
        %
      case 'property'
        
        if ( ~isempty(CurElement) & Count >= 3 )
          
          NumProperties = NumProperties + 1;
          eval(['tmp=isfield(Elements.',CurElement,',Token{Count});'],...
            'fclose(fid);error([''Error reading property: '',Buf])');
          
          if ( tmp )
            error(['Duplicate property name, ''',CurElement,'.',Token{2},'''.']);
          end
          %
          %  Add property subfield to Elements.
          %
          eval(['Elements.',CurElement,'.',Token{Count},'=[];'], ...
            'fclose(fid);error([''Error reading property: '',Buf])');
          %
          %  Add property subfield to PropertyTypes and save type.
          %
          eval(['PropertyTypes.',CurElement,'.',Token{Count},'={Token{2:Count-1}};'], ...
            'fclose(fid);error([''Error reading property: '',Buf])');
          %
          %  Record property name order.
          %
          eval(['PropertyNames.',CurElement,'{NumProperties}=Token{Count};'], ...
            'fclose(fid);error([''Error reading property: '',Buf])');
          
        else
          
          fclose ( fid );
          
          if ( isempty(CurElement) )
            error(['Property definition without element definition: ',Buf]);
          else
            error(['Bad property definition: ',Buf]);
          end
          
        end
        %
        %  End of header.
        %
      case 'end_header'
        break;
        
    end
  end
end
%
%  Set reading for specified data format.
%
if ( isempty ( Format ) )
  warning('Data format unspecified, assuming ASCII.');
  Format = 'ascii';
end

switch Format
  
  case 'ascii'
    Format = 0;
  case 'binary_little_endian'
    Format = 1;
  case 'binary_big_endian'
    Format = 2;
  otherwise
    fclose ( fid );
    error(['Data format ''',Format,''' not supported.']);
    
end
%
%  Read the rest of the file as ASCII data...
%
if ( ~Format )
  Buf = fscanf ( fid, '%f' );
  BufOff = 1;
else
  %
  %  ...or, close the file, and reopen in "read binary" mode.
  %
  fclose ( fid );
  %
  %  Reopen the binary file as LITTLE_ENDIAN or BIG_ENDIAN.
  %
  if ( Format == 1 )
    fid = fopen ( Path, 'r', 'ieee-le.l64' );
  else
    fid = fopen ( Path, 'r', 'ieee-be.l64' );
  end
  %
  %  Find the end of the header again.
  %  Using ftell on the old handle doesn't give the correct position.
  %
  BufSize = 8192;
  Buf = [ blanks(10), char(fread(fid,BufSize,'uchar')') ];
  i = [];
  tmp = -11;
  
  while ( isempty(i) )
    
    i = findstr(Buf,['end_header',13,10]);   % look for end_header + CR/LF
    i = [i,findstr(Buf,['end_header',10])];  % look for end_header + LF
    
    if ( isempty(i) )
      tmp = tmp + BufSize;
      Buf = [Buf(BufSize+1:BufSize+10),char(fread(fid,BufSize,'uchar')')];
    end
    
  end
  %
  %  seek to just after the line feed
  %
  fseek ( fid, i + tmp + 11 + (Buf(i + 10) == 13), -1 );
  
end
%
%  Read element data.
%
%  PLY and MATLAB data types (for fread)
%
PlyTypeNames = {'char','uchar','short','ushort','int','uint','float','double', ...
  'char8','uchar8','short16','ushort16','int32','uint32','float32','double64'};

MatlabTypeNames = {'schar','uchar','int16','uint16','int32','uint32','single','double'};

SizeOf = [1,1,2,2,4,4,4,8];

for i = 1 : NumElements
  %
  %  get current element property information
  %
  eval(['CurPropertyNames=PropertyNames.',ElementNames{i},';']);
  eval(['CurPropertyTypes=PropertyTypes.',ElementNames{i},';']);
  NumProperties = size(CurPropertyNames,2);
  
  %   fprintf('Reading %s...\n',ElementNames{i});
  %
  %  Read ASCII data.
  %
  if ( ~Format )
    
    for j = 1 : NumProperties
      
      Token = getfield(CurPropertyTypes,CurPropertyNames{j});
      
      if ( strcmpi(Token{1},'list') )
        Type(j) = 1;
      else
        Type(j) = 0;
      end
      %
      %  Glenn Ramsey 20120827
      %  Initialise Type2{} to prevent uninitialised value error.
      %
      Type2{j} = '';
      
    end
    %
    %  Parse the buffer.
    %
    if ( ~any(Type) )
      
      % no list types
      
      Data = reshape ( ...
        Buf(BufOff:BufOff+ElementCount(i)*NumProperties-1), ...
        NumProperties, ElementCount(i) )';
      
      BufOff = BufOff + ElementCount(i) * NumProperties;
      
    else
      
      ListData = cell(NumProperties,1);
      
      for k = 1 : NumProperties
        ListData{k} = cell(ElementCount(i),1);
      end
      %
      % list type
      %
      for j = 1 : ElementCount(i)
        for k = 1 : NumProperties
          
          if ( ~Type(k) )
            Data(j,k) = Buf(BufOff);
            BufOff = BufOff + 1;
          else
            tmp = Buf(BufOff);
            ListData{k}{j} = Buf(BufOff+(1:tmp))';
            BufOff = BufOff + tmp + 1;
          end
          
        end
      end
      
    end
    %
    %  Read binary data.
    %
  else
    % translate PLY data type names to MATLAB data type names
    ListFlag = 0;  % = 1 if there is a list type
    SameFlag = 1;     % = 1 if all types are the same
    
    for j = 1 : NumProperties
      
      Token = getfield(CurPropertyTypes,CurPropertyNames{j});
      %
      %  Non-list type.
      %
      if ( ~strcmp(Token{1},'list' ) )
        
        tmp = rem(strmatch(Token{1},PlyTypeNames,'exact')-1,8)+1;
        
        if ( ~isempty(tmp) )
          
          TypeSize(j) = SizeOf(tmp);
          Type{j} = MatlabTypeNames{tmp};
          TypeSize2(j) = 0;
          Type2{j} = '';
          
          SameFlag = SameFlag & strcmp(Type{1},Type{j});
          
        else
          
          fclose(fid);
          error(['Unknown property data type, ''',Token{1},''', in ', ...
            ElementNames{i},'.',CurPropertyNames{j},'.']);
          
        end
        
      else           % list type
        
        if ( length(Token) == 3 )
          
          ListFlag = 1;
          SameFlag = 0;
          tmp = rem(strmatch(Token{2},PlyTypeNames,'exact')-1,8)+1;
          tmp2 = rem(strmatch(Token{3},PlyTypeNames,'exact')-1,8)+1;
          
          if ( ~isempty(tmp) & ~isempty(tmp2) )
            TypeSize(j) = SizeOf(tmp);
            Type{j} = MatlabTypeNames{tmp};
            TypeSize2(j) = SizeOf(tmp2);
            Type2{j} = MatlabTypeNames{tmp2};
          else
            fclose(fid);
            error(['Unknown property data type, ''list ',Token{2},' ',Token{3},''', in ', ...
              ElementNames{i},'.',CurPropertyNames{j},'.']);
          end
          
        else
          
          fclose(fid);
          error(['Invalid list syntax in ',ElementNames{i},'.',CurPropertyNames{j},'.']);
          
        end
        
      end
      
    end
    
    % read file
    
    if ( ~ListFlag )
      %
      %  No list types, all the same type (fast)
      %
      if ( SameFlag )
        
        Data = fread(fid,[NumProperties,ElementCount(i)],Type{1})';
        %
        %  No list types, mixed type.
        %
      else
        
        Data = zeros(ElementCount(i),NumProperties);
        
        for j = 1 : ElementCount(i)
          for k = 1 : NumProperties
            Data(j,k) = fread(fid,1,Type{k});
          end
        end
        
      end
      
    else
      
      ListData = cell(NumProperties,1);
      
      for k = 1 : NumProperties
        ListData{k} = cell(ElementCount(i),1);
      end
      
      if ( NumProperties == 1 )
        
        BufSize = 512;
        SkipNum = 4;
        j = 0;
        %
        %  List type, one property (fast if lists are usually the same length)
        %
        while ( j < ElementCount(i) )
          
          BufSize = min(ElementCount(i)-j,BufSize);
          Position = ftell(fid);
          %
          %  Read in BufSize count values, assuming all counts = SkipNum
          %
          [Buf,BufSize] = fread(fid,BufSize,Type{1},SkipNum*TypeSize2(1));
          Miss = find(Buf ~= SkipNum);     % find first count that is not SkipNum
          fseek(fid,Position + TypeSize(1),-1);   % seek back to after first count
          
          if ( isempty(Miss) )
            % all counts are SkipNum
            Buf = fread(fid,[SkipNum,BufSize],[int2str(SkipNum),'*',Type2{1}],TypeSize(1))';
            fseek(fid,-TypeSize(1),0);     % undo last skip
            
            for k = 1:BufSize
              ListData{1}{j+k} = Buf(k,:);
            end
            
            j = j + BufSize;
            BufSize = floor(1.5*BufSize);
            
          else
            %
            %  Some counts are SkipNum.
            %
            if ( 1 < Miss(1) )
              
              Buf2 = fread(fid,[SkipNum,Miss(1)-1],[int2str(SkipNum),'*',Type2{1}],TypeSize(1))';
              
              for k = 1:Miss(1)-1
                ListData{1}{j+k} = Buf2(k,:);
              end
              
              j = j + k;
              
            end
            %
            %  Read in the list with the missed count.
            %
            SkipNum = Buf(Miss(1));
            j = j + 1;
            ListData{1}{j} = fread(fid,[1,SkipNum],Type2{1});
            BufSize = ceil(0.6*BufSize);
            
          end
        end
        
      else
        %
        %  List type(s), multiple properties (slow)
        %
        Data = zeros(ElementCount(i),NumProperties);
        
        for j = 1:ElementCount(i)
          for k = 1:NumProperties
            
            if ( isempty(Type2{k}) )
              Data(j,k) = fread(fid,1,Type{k});
            else
              tmp = fread(fid,1,Type{k});
              ListData{k}{j} = fread(fid,[1,tmp],Type2{k});
            end
            
          end
        end
      end
    end
  end
  %
  %  Put data into Elements structure
  %
  if iscell(Type)
    TypeTest = false(size(Type));
  else
    TypeTest = Type;
  end
  for k = 1 : NumProperties
    
    if ( ~exist('ListData','var') || ( ~Format & ~TypeTest(k) ) || (Format & isempty(Type2{k})) )
      eval(['Elements.',ElementNames{i},'.',CurPropertyNames{k},'=Data(:,k);']);
    else
      eval(['Elements.',ElementNames{i},'.',CurPropertyNames{k},'=ListData{k};']);
    end
    
  end
  
end

clear Data
clear ListData;

fclose ( fid );
%
%  Output the data as a triangular mesh pair.
%
if ( ( nargin > 1 && strcmpi(Str,'Tri') ) || nargout > 2 )
  %
  %  Find vertex element field
  %
  Name = {'vertex','Vertex','point','Point','pts','Pts'};
  Names = [];
  
  for i = 1 : length(Name)
    
    if ( any ( strcmp ( ElementNames, Name{i} ) ) )
      Names = getfield(PropertyNames,Name{i});
      Name = Name{i};
      break;
    end
    
  end
  
  if ( any(strcmp(Names,'x')) & any(strcmp(Names,'y')) & any(strcmp(Names,'z')) )
    eval(['varargout{1}=[Elements.',Name,'.x,Elements.',Name,'.y,Elements.',Name,'.z];']);
  else
    varargout{1} = zeros(1,3);
  end
  varargout{1} = varargout{1}';
  
  varargout{2} = Elements;
  varargout{3} = Comments;
  Elements = [];
  %
  % Find face element field
  %
  Name = {'face','Face','poly','Poly','tri','Tri'};
  Names = [];
  
  for i = 1 : length(Name)
    if ( any(strcmp(ElementNames,Name{i})) )
      Names = getfield(PropertyNames,Name{i});
      Name = Name{i};
      break;
    end
  end
  
  if ( ~isempty(Names) )
    % find vertex indices property subfield
    PropertyName = {'vertex_indices','vertex_indexes','vertex_index','indices','indexes'};
    
    for i = 1 : length(PropertyName)
      if ( any(strcmp(Names,PropertyName{i})) )
        PropertyName = PropertyName{i};
        break;
      end
    end
    %
    %  Convert face index list to triangular connectivity.
    %
    if ( ~iscell(PropertyName) )
      
      eval(['FaceIndices=varargout{2}.',Name,'.',PropertyName,';']);
      N = length(FaceIndices);
      Elements = zeros(3,N*2);
      Extra = 0;
      
      for k = 1 : N
        
        Elements(1:3,k) = FaceIndices{k}(1:3)';
        %
        %  The original code had an error in the following loop.
        %
        for j = 4 : length(FaceIndices{k})
          Extra = Extra + 1;
          Elements(1,N + Extra) = FaceIndices{k}(1);
          Elements(2,N + Extra) = FaceIndices{k}(j-1);
          Elements(3,N + Extra) = FaceIndices{k}(j);
        end
        
      end
      %
      %  Add 1 to each vertex value; PLY vertices are zero based.
      %
      Elements = Elements(:,1:N+Extra) + 1;
      
    end
  end
  
else
  
  varargout{1} = Comments;
  
end

return
end