Search code examples
matlabfwritepoint-cloud-library

Process PCD files (Delete lines based on indices) - MATLAB


I have a *.pcd file(see below). The data has five fields and the last field is 'index'. Now I want to delete points with index [2 4 6 8]. And write the result to a new .pcd file.... Does anyone know how to do it ...... Thanks a lot!

   # .PCD v.7 - Point Cloud Data file format
   FIELDS x y z rgb index
   SIZE 4 4 4 4 4
   TYPE F F F F U 
   COUNT 1 1 1 1 1
   WIDTH 12
   HEIGHT 1
   VIEWPOINT 0 0 0 1 0 0 0
   POINTS 12
   DATA ascii
   1824.064 -627.111 -119.4176 0 1
   1824.412 -629.678 -119.7147 0 2    %delete
   1819.929 -630.5591 -116.9839 0 3
   1820.276 -623.1166 -117.2799 0 4   %delete
   1820.622 -635.6741 -117.576 0 5
   1816.134 -636.5178 -114.8408 0 6   %delete
   1816.48 -639.0659 -115.1358 0 7
   1811.02 -639.5347 -111.7907 0 8    %delete
   1811.364 -662.0717 -112.0844 0 9
   1707.098 829.5436 59.0613 0 10
   1707.441 827.0067 58.76764 0 11
   1707.785 824.4698 58.47398 0 12

Solution

  • See if this works for you -

    exclude_index = [2 4 6 8];
    field_num = 5;
    
    A = importdata(inputfile,'\n');
    
    A1 = cellfun(@(x) strtrim(x), A,'Uni',0);
    A1_firstchar = arrayfun(@(x) A1{x}(1),1:numel(A1),'Uni',0);
    startind = find(cell2mat(isstrprop(A1_firstchar,'digit')),1,'first');
    
    A_part1 = A(1:startind-1);
    A_part2 = A(startind:end,:);
    
    B = cellfun(@(x) strtrim(x),A_part2 ,'Uni',0);
    C = cellfun(@(x) strsplit(x),B,'Uni',0);
    D = str2double(arrayfun(@(n) C{n}(field_num),1:numel(C)));
    
    Anew = [A_part1 ; A_part2(~ismember(D,exclude_index),:)];
    
    fid = fopen(outputfile, 'w');
    for i=1:numel(Anew)
        fprintf(fid, '%s\n', Anew{i});
    end
    fclose(fid);
    

    Please make sure to edit inputfile and outputfile to the paths where you have the input .pcd file and the path where you intend to save the processed .pcd file respectively.


    Performance oriented solution

    %// Number of header lines
    headerlines = 10;
    
    %// read data into cell array
    A = importdata(inputfile,'\n');
    
    %// read formatted data
    fid = fopen(inputfile, 'r');
    C = textscan(fid,'%f %f %f %d %d','HeaderLines',headerlines,'Delimiter',' ');
    
    %// removed rows from cell array that matches our conditions
    idx = find(ismember(C{5},[2 4 6 8]));
    A(headerlines + idx)=[];
    
    %// Write to output file
    fid = fopen(outputfile, 'w');
    for i=1:numel(A)
        fprintf(fid, '%s\n', A{i});
    end
    fclose(fid);