forked from norlab-ulaval/libpointmatcher
-
Notifications
You must be signed in to change notification settings - Fork 2
/
IO.cpp
executable file
·2353 lines (1972 loc) · 61.8 KB
/
IO.cpp
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
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// kate: replace-tabs off; indent-width 4; indent-mode normal
// vim: ts=4:sw=4:noexpandtab
/*
Copyright (c) 2010--2012,
François Pomerleau and Stephane Magnenat, ASL, ETHZ, Switzerland
You can contact the authors at <f dot pomerleau at gmail dot com> and
<stephane at magnenat dot net>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the <organization> nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL ETH-ASL BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "IO.h"
#include "IOFunctions.h"
#include "InspectorsImpl.h"
// For logging
#include "PointMatcherPrivate.h"
#include <iostream>
#include <fstream>
#include <stdexcept>
#include <ctype.h>
#include "boost/algorithm/string.hpp"
#include "boost/filesystem.hpp"
#include "boost/filesystem/path.hpp"
#include "boost/filesystem/operations.hpp"
#include "boost/lexical_cast.hpp"
#include "boost/foreach.hpp"
#ifdef WIN32
#define strtok_r strtok_s
#endif // WIN32
namespace PointMatcherSupport {
namespace {
const int one = 1;
}
const bool isBigEndian = *reinterpret_cast<const unsigned char*>(&one) == static_cast<unsigned char>(0);
const int oneBigEndian = isBigEndian ? 1 : 1 << 8 * (sizeof(int) - 1);
}
using namespace std;
using namespace PointMatcherSupport;
// Tokenize a string, excepted if it begins with a '%' (a comment in CSV)
static std::vector<string> csvLineToVector(const char* line)
{
std::vector<string> parsedLine;
char delimiters[] = " \t,;";
char *token;
char tmpLine[1024];
char *brkt = 0;
strcpy(tmpLine, line);
token = strtok_r(tmpLine, delimiters, &brkt);
if(line[0] != '%') // Jump line if it's commented
{
while (token)
{
parsedLine.push_back(string(token));
token = strtok_r(NULL, delimiters, &brkt);
}
}
return parsedLine;
}
// Open and parse a CSV file, return the data
CsvElements parseCsvWithHeader(const std::string& fileName)
{
validateFile(fileName);
ifstream is(fileName.c_str());
unsigned elementCount=0;
std::map<string, unsigned> keywordCols;
CsvElements data;
bool firstLine(true);
unsigned lineCount=0;
string line;
while (safeGetLine(is, line))
{
if(firstLine)
{
std::vector<string> header = csvLineToVector(line.c_str());
elementCount = header.size();
for(unsigned int i = 0; i < elementCount; i++)
{
keywordCols[header[i]] = i;
}
firstLine = false;
}
else // load the rest of the file
{
std::vector<string> parsedLine = csvLineToVector(line.c_str());
if(parsedLine.size() != elementCount && parsedLine.size() !=0)
{
stringstream errorMsg;
errorMsg << "Error at line " << lineCount+1 << ": expecting " << elementCount << " columns but read " << parsedLine.size() << " elements.";
throw runtime_error(errorMsg.str());
}
for(unsigned int i = 0; i < parsedLine.size(); i++)
{
for(BOOST_AUTO(it,keywordCols.begin()); it!=keywordCols.end(); it++)
{
if(i == (*it).second)
{
data[(*it).first].push_back(parsedLine[i]);
}
}
}
}
lineCount++;
}
// Use for debug
//for(BOOST_AUTO(it,data.begin()); it!=data.end(); it++)
//{
// cout << "--------------------------" << endl;
// cout << "Header: |" << (*it).first << "|" << endl;
// //for(unsigned i=0; i<(*it).second.size(); i++)
// //{
// // cout << (*it).second[i] << endl;
// //}
//}
return data;
}
//! Constructor, leave fields blank if unused
template<typename T>
PointMatcherIO<T>::FileInfo::FileInfo(const std::string& readingFileName, const std::string& referenceFileName, const std::string& configFileName, const TransformationParameters& initialTransformation, const TransformationParameters& groundTruthTransformation, const Vector& gravity):
readingFileName(readingFileName),
referenceFileName(referenceFileName),
configFileName(configFileName),
initialTransformation(initialTransformation),
groundTruthTransformation(groundTruthTransformation),
gravity(gravity)
{}
template struct PointMatcherIO<float>::FileInfo;
template struct PointMatcherIO<double>::FileInfo;
// Empty constructor
template<typename T>
PointMatcherIO<T>::FileInfoVector::FileInfoVector()
{
}
//! Load a vector of FileInfo from a CSV file.
/**
@param fileName name of the CSV file
@param dataPath path relative to which the point cloud CSV or VTK will be resolved
@param configPath path relative to which the yaml configuration files will be resolved
The first line of the CSV file must contain a header. The supported tags are:
- reading: file name of the reading point cloud
- reference: file name of the reference point cloud
- config: file name of the YAML configuration of the ICP chain
- iTxy: initial transformation, coordinate x,y
- gTxy: ground-truth transformation, coordinate x,y
Note that the header must at least contain "reading".
*/
template<typename T>
PointMatcherIO<T>::FileInfoVector::FileInfoVector(const std::string& fileName, std::string dataPath, std::string configPath)
{
if (dataPath.empty())
{
#if BOOST_FILESYSTEM_VERSION >= 3
dataPath = boost::filesystem::path(fileName).parent_path().string();
#else
dataPath = boost::filesystem::path(fileName).parent_path().file_string();
#endif
}
if (configPath.empty())
{
#if BOOST_FILESYSTEM_VERSION >= 3
configPath = boost::filesystem::path(fileName).parent_path().string();
#else
configPath = boost::filesystem::path(fileName).parent_path().file_string();
#endif
}
const CsvElements data = parseCsvWithHeader(fileName);
// Look for transformations
const bool found3dInitialTrans(findTransform(data, "iT", 3));
bool found2dInitialTrans(findTransform(data, "iT", 2));
const bool found3dGroundTruthTrans(findTransform(data, "gT", 3));
bool found2dGroundTruthTrans(findTransform(data, "gT", 2));
if (found3dInitialTrans)
found2dInitialTrans = false;
if (found3dGroundTruthTrans)
found2dGroundTruthTrans = false;
// Check for consistency
if (found3dInitialTrans && found2dGroundTruthTrans)
throw runtime_error("Initial transformation is in 3D but ground-truth is in 2D");
if (found2dInitialTrans && found3dGroundTruthTrans)
throw runtime_error("Initial transformation is in 2D but ground-truth is in 3D");
CsvElements::const_iterator readingIt(data.find("reading"));
if (readingIt == data.end())
throw runtime_error("Error transfering CSV to structure: The header should at least contain \"reading\".");
CsvElements::const_iterator referenceIt(data.find("reference"));
CsvElements::const_iterator configIt(data.find("config"));
// Load reading
const std::vector<string>& readingFileNames = readingIt->second;
const unsigned lineCount = readingFileNames.size();
boost::optional<std::vector<string> > referenceFileNames;
boost::optional<std::vector<string> > configFileNames;
if (referenceIt != data.end())
{
referenceFileNames = referenceIt->second;
assert (referenceFileNames->size() == lineCount);
}
if (configIt != data.end())
{
configFileNames = configIt->second;
assert (configFileNames->size() == lineCount);
}
// for every lines
for(unsigned line=0; line<lineCount; line++)
{
FileInfo info;
// Files
info.readingFileName = localToGlobalFileName(dataPath, readingFileNames[line]);
if (referenceFileNames)
info.referenceFileName = localToGlobalFileName(dataPath, (*referenceFileNames)[line]);
if (configFileNames)
info.configFileName = localToGlobalFileName(configPath, (*configFileNames)[line]);
// Load transformations
if(found3dInitialTrans)
info.initialTransformation = getTransform(data, "iT", 3, line);
if(found2dInitialTrans)
info.initialTransformation = getTransform(data, "iT", 2, line);
if(found3dGroundTruthTrans)
info.groundTruthTransformation = getTransform(data, "gT", 3, line);
if(found2dGroundTruthTrans)
info.groundTruthTransformation = getTransform(data, "gT", 2, line);
// Build the list
this->push_back(info);
}
// Debug: Print the list
/*for(unsigned i=0; i<list.size(); i++)
{
cout << "\n--------------------------" << endl;
cout << "Sequence " << i << ":" << endl;
cout << "Reading path: " << list[i].readingFileName << endl;
cout << "Reference path: " << list[i].referenceFileName << endl;
cout << "Extension: " << list[i].fileExtension << endl;
cout << "Tranformation:\n" << list[i].initialTransformation << endl;
cout << "Grativity:\n" << list[i].gravity << endl;
}
*/
}
//! Join parentPath and fileName and return the result as a global path
template<typename T>
std::string PointMatcherIO<T>::FileInfoVector::localToGlobalFileName(const std::string& parentPath, const std::string& fileName)
{
std::string globalFileName(fileName);
if (!boost::filesystem::exists(globalFileName))
{
const boost::filesystem::path globalFilePath(boost::filesystem::path(parentPath) / boost::filesystem::path(fileName));
#if BOOST_FILESYSTEM_VERSION >= 3
globalFileName = globalFilePath.string();
#else
globalFileName = globalFilePath.file_string();
#endif
}
validateFile(globalFileName);
return globalFileName;
}
//! Return whether there is a valid transformation named prefix in data
template<typename T>
bool PointMatcherIO<T>::FileInfoVector::findTransform(const CsvElements& data, const std::string& prefix, unsigned dim)
{
bool found(true);
for(unsigned i=0; i<dim+1; i++)
{
for(unsigned j=0; j<dim+1; j++)
{
stringstream transName;
transName << prefix << i << j;
found = found && (data.find(transName.str()) != data.end());
}
}
return found;
}
//! Return the transformation named prefix from data
template<typename T>
typename PointMatcherIO<T>::TransformationParameters PointMatcherIO<T>::FileInfoVector::getTransform(const CsvElements& data, const std::string& prefix, unsigned dim, unsigned line)
{
TransformationParameters transformation(TransformationParameters::Identity(dim+1, dim+1));
for(unsigned i=0; i<dim+1; i++)
{
for(unsigned j=0; j<dim+1; j++)
{
stringstream transName;
transName << prefix << i << j;
CsvElements::const_iterator colIt(data.find(transName.str()));
const T value = boost::lexical_cast<T> (colIt->second[line]);
transformation(i,j) = value;
}
}
return transformation;
}
template struct PointMatcherIO<float>::FileInfoVector;
template struct PointMatcherIO<double>::FileInfoVector;
//! Throw a runtime_error exception if fileName cannot be opened
void PointMatcherSupport::validateFile(const std::string& fileName)
{
boost::filesystem::path fullPath(fileName);
ifstream ifs(fileName.c_str());
if (!ifs.good() || !boost::filesystem::is_regular_file(fullPath))
#if BOOST_FILESYSTEM_VERSION >= 3
#if BOOST_VERSION >= 105000
throw runtime_error(string("Cannot open file ") + boost::filesystem::complete(fullPath).generic_string());
#else
throw runtime_error(string("Cannot open file ") + boost::filesystem3::complete(fullPath).generic_string());
#endif
#else
throw runtime_error(string("Cannot open file ") + boost::filesystem::complete(fullPath).native_file_string());
#endif
}
//! Load a point cloud from a file, determine format from extension
template<typename T>
typename PointMatcher<T>::DataPoints PointMatcher<T>::DataPoints::load(const std::string& fileName)
{
const boost::filesystem::path path(fileName);
const string& ext(boost::filesystem::extension(path));
if (boost::iequals(ext, ".vtk"))
return PointMatcherIO<T>::loadVTK(fileName);
else if (boost::iequals(ext, ".csv"))
return PointMatcherIO<T>::loadCSV(fileName);
else if (boost::iequals(ext, ".ply"))
return PointMatcherIO<T>::loadPLY(fileName);
else if (boost::iequals(ext, ".pcd"))
return PointMatcherIO<T>::loadPCD(fileName);
else
throw runtime_error("loadAnyFormat(): Unknown extension \"" + ext + "\" for file \"" + fileName + "\", extension must be either \".vtk\" or \".csv\"");
}
template
PointMatcher<float>::DataPoints PointMatcher<float>::DataPoints::load(const std::string& fileName);
template
PointMatcher<double>::DataPoints PointMatcher<double>::DataPoints::load(const std::string& fileName);
//! @brief Load comma separated values (csv) file
//! @param fileName a string containing the path and the file name
//!
//! This loader has 3 behaviors since there is no official standard for
//! csv files. A 2D or 3D point cloud will be created automatically if:
//! - there is a header with columns named x, y and optionnaly z
//! - there are only 2 or 3 columns in the file
//!
//! Otherwise, the user is asked to enter column id manually which might
//! block automatic processing.
template<typename T>
typename PointMatcher<T>::DataPoints PointMatcherIO<T>::loadCSV(const std::string& fileName)
{
ifstream ifs(fileName.c_str());
validateFile(fileName);
return loadCSV(ifs);
}
template<typename T>
PointMatcherIO<T>::SupportedLabel::SupportedLabel(const std::string& internalName, const std::string& externalName, const PMPropTypes& type):
internalName(internalName),
externalName(externalName),
type(type)
{
}
// Class LabelGenerator
template<typename T>
void PointMatcherIO<T>::LabelGenerator::add(const std::string internalName)
{
bool findLabel = false;
for(size_t i=0; i<labels.size(); ++i)
{
if(internalName == labels[i].text)
{
labels[i].span++;
findLabel = true;
break;
}
}
if(!findLabel)
{
labels.push_back(Label(internalName,1));
}
}
template<typename T>
void PointMatcherIO<T>::LabelGenerator::add(const std::string internalName, const unsigned int dim)
{
labels.push_back(Label(internalName, dim));
}
// Class LabelGenerator
template<typename T>
typename PointMatcher<T>::DataPoints::Labels PointMatcherIO<T>::LabelGenerator::getLabels() const
{
return labels;
}
template
class PointMatcherIO<float>::LabelGenerator;
template
class PointMatcherIO<double>::LabelGenerator;
template <typename T>
std::string PointMatcherIO<T>::getColLabel(const Label& label, const int row)
{
std::string externalName;
if (label.text == "normals")
{
if (row == 0)
{
externalName = "nx";
}
if (row == 1)
{
externalName = "ny";
}
if (row == 2)
{
externalName = "nz";
}
}
else if (label.text == "color")
{
if (row == 0)
{
externalName = "red";
}
if (row == 1)
{
externalName = "green";
}
if (row == 2)
{
externalName = "blue";
}
if (row == 3)
externalName = "alpha";
}
else if (label.text == "eigValues")
{
externalName = "eigValues" + boost::lexical_cast<string>(row);
}
else if (label.text == "eigVectors")
{
// format: eigVectors<0-2><X-Z>
externalName = "eigVectors" + boost::lexical_cast<string>(row/3);
int row_mod = row % 3;
if (row_mod == 0)
externalName += "X";
else if (row_mod == 1)
externalName += "Y";
else if (row_mod == 2)
externalName += "Z";
}
else if (label.span == 1)
{
externalName = label.text;
}
else
externalName = label.text + boost::lexical_cast<std::string>(row);
return externalName;
}
//! @brief Load comma separated values (csv) file
//! @see loadCSV()
template<typename T>
typename PointMatcher<T>::DataPoints PointMatcherIO<T>::loadCSV(std::istream& is)
{
vector<GenericInputHeader> csvHeader;
LabelGenerator featLabelGen, descLabelGen, timeLabelGen;
Matrix features;
Matrix descriptors;
Int64Matrix times;
unsigned int csvCol = 0;
unsigned int csvRow = 0;
bool hasHeader(false);
bool firstLine(true);
//count lines in the file
is.unsetf(std::ios_base::skipws);
unsigned int line_count = std::count(
std::istream_iterator<char>(is),
std::istream_iterator<char>(),
'\n');
//reset the stream
is.clear();
is.seekg(0, ios::beg);
char delimiters[] = " \t,;";
char *token;
string line;
while (safeGetLine(is, line))
{
// Skip empty lines
if(line.empty())
break;
// Look for text header
unsigned int len = strspn(line.c_str(), " ,+-.1234567890Ee");
if(len != line.length())
{
//cout << "Header detected" << endl;
hasHeader = true;
}
else
{
hasHeader = false;
}
// Count dimension using first line
if(firstLine)
{
unsigned int dim = 0;
char tmpLine[1024]; //FIXME: might be problematic for large file
strcpy(tmpLine, line.c_str());
char *brkt = 0;
token = strtok_r(tmpLine, delimiters, &brkt);
//1- BUILD HEADER
while (token)
{
// Load text header
if(hasHeader)
{
csvHeader.push_back(GenericInputHeader(string(token)));
}
dim++;
token = strtok_r(NULL, delimiters, &brkt);
}
if (!hasHeader)
{
// Check if it is a simple file with only coordinates
if (!(dim == 2 || dim == 3))
{
int idX=0, idY=0, idZ=0;
cout << "WARNING: " << dim << " columns detected. Not obvious which columns to load for x, y or z." << endl;
cout << endl << "Enter column ID (starting from 0) for x: ";
cin >> idX;
cout << "Enter column ID (starting from 0) for y: ";
cin >> idY;
cout << "Enter column ID (starting from 0, -1 if 2D data) for z: ";
cin >> idZ;
// Fill with unkown column names
for(unsigned int i=0; i<dim; i++)
{
std::ostringstream os;
os << "empty" << i;
csvHeader.push_back(GenericInputHeader(os.str()));
}
// Overwrite with user inputs
csvHeader[idX] = GenericInputHeader("x");
csvHeader[idY] = GenericInputHeader("y");
if(idZ != -1)
csvHeader[idZ] = GenericInputHeader("z");
}
else
{
// Assume logical order...
csvHeader.push_back(GenericInputHeader("x"));
csvHeader.push_back(GenericInputHeader("y"));
if(dim == 3)
csvHeader.push_back(GenericInputHeader("z"));
}
}
//2- PROCESS HEADER
// Load known features, descriptors, and time
const SupportedLabels externalLabels = getSupportedExternalLabels();
// Counters
int rowIdFeatures = 0;
int rowIdDescriptors = 0;
int rowIdTime = 0;
// Loop through all known external names (ordered list)
for(size_t i=0; i<externalLabels.size(); i++)
{
const SupportedLabel supLabel = externalLabels[i];
for(size_t j=0; j < csvHeader.size(); j++)
{
if(supLabel.externalName == csvHeader[j].name)
{
csvHeader[j].matrixType = supLabel.type;
switch (supLabel.type)
{
case FEATURE:
csvHeader[j].matrixRowId = rowIdFeatures;
featLabelGen.add(supLabel.internalName);
rowIdFeatures++;
break;
case DESCRIPTOR:
csvHeader[j].matrixRowId = rowIdDescriptors;
descLabelGen.add(supLabel.internalName);
rowIdDescriptors++;
break;
case TIME:
csvHeader[j].matrixRowId = rowIdTime;
timeLabelGen.add(supLabel.internalName);
rowIdTime++;
break;
default:
throw runtime_error(string("CSV parse error: encounter a type different from FEATURE, DESCRIPTOR and TIME. Implementation not supported. See the definition of 'enum PMPropTypes'"));
break;
}
// we stop searching once we have a match
break;
}
}
}
// loop through the remaining UNSUPPORTED labels and assigned them to a descriptor row
for(unsigned int i=0; i<csvHeader.size(); i++)
{
if(csvHeader[i].matrixType == UNSUPPORTED)
{
csvHeader[i].matrixType = DESCRIPTOR; // force descriptor
csvHeader[i].matrixRowId = rowIdDescriptors;
descLabelGen.add(csvHeader[i].name); // keep original name
rowIdDescriptors++;
}
}
//3- RESERVE MEMORY
if(hasHeader && line_count > 0)
line_count--;
const unsigned int featDim = featLabelGen.getLabels().totalDim();
const unsigned int descDim = descLabelGen.getLabels().totalDim();
const unsigned int timeDim = timeLabelGen.getLabels().totalDim();
const unsigned int nbPoints = line_count;
features = Matrix(featDim, nbPoints);
descriptors = Matrix(descDim, nbPoints);
times = Int64Matrix(timeDim, nbPoints);
}
//4- LOAD DATA (this start again from the first line)
char* brkt = 0;
char line_c[1024];//FIXME: this might be a problem for large files
strcpy(line_c,line.c_str());
token = strtok_r(line_c, delimiters, &brkt);
if(!(hasHeader && firstLine))
{
// Parse a line
csvCol = 0;
while (token)
{
if(csvCol > (csvHeader.size() - 1))
{
// Error check (too much data)
throw runtime_error(
(boost::format("CSV parse error: at line %1%, too many elements to parse compare to the header number of columns (col=%2%).") % csvRow % csvHeader.size()).str());
}
// Alias
const int matrixRow = csvHeader[csvCol].matrixRowId;
const int matrixCol = csvRow;
switch (csvHeader[csvCol].matrixType)
{
case FEATURE:
features(matrixRow, matrixCol) = lexical_cast_scalar_to_string<T>(string(token));
break;
case DESCRIPTOR:
descriptors(matrixRow, matrixCol) = lexical_cast_scalar_to_string<T>(token);
break;
case TIME:
times(matrixRow, matrixCol) = lexical_cast_scalar_to_string<std::int64_t>(token);
break;
default:
throw runtime_error(string("CSV parse error: encounter a type different from FEATURE, DESCRIPTOR and TIME. Implementation not supported. See the definition of 'enum PMPropTypes'"));
break;
}
//fetch next element
token = strtok_r(NULL, delimiters, &brkt);
csvCol++;
}
// Error check (not enough data)
if(csvCol != (csvHeader.size()))
{
throw runtime_error(
(boost::format("CSV parse error: at line %1%, not enough elements to parse compare to the header number of columns (col=%2%).") % csvRow % csvHeader.size()).str());
}
csvRow++;
}
firstLine = false;
}
// 5- ASSEMBLE FINAL DATAPOINTS
DataPoints loadedPoints(features, featLabelGen.getLabels());
if (descriptors.rows() > 0)
{
loadedPoints.descriptors = descriptors;
loadedPoints.descriptorLabels = descLabelGen.getLabels();
}
if(times.rows() > 0)
{
loadedPoints.times = times;
loadedPoints.timeLabels = timeLabelGen.getLabels();
}
// Ensure homogeous coordinates
if(!loadedPoints.featureExists("pad"))
{
loadedPoints.addFeature("pad", Matrix::Ones(1,features.cols()));
}
return loadedPoints;
}
template
PointMatcher<float>::DataPoints PointMatcherIO<float>::loadCSV(const std::string& fileName);
template
PointMatcher<double>::DataPoints PointMatcherIO<double>::loadCSV(const std::string& fileName);
//! Save a point cloud to a file, determine format from extension
template<typename T>
void PointMatcher<T>::DataPoints::save(const std::string& fileName, bool binary) const
{
const boost::filesystem::path path(fileName);
const string& ext(boost::filesystem::extension(path));
if (boost::iequals(ext, ".vtk"))
return PointMatcherIO<T>::saveVTK(*this, fileName, binary);
if (binary)
throw runtime_error("save(): Binary writing is not supported together with extension \"" + ext + "\". Currently binary writing is only supported with \".vtk\".");
if (boost::iequals(ext, ".csv"))
return PointMatcherIO<T>::saveCSV(*this, fileName);
else if (boost::iequals(ext, ".ply"))
return PointMatcherIO<T>::savePLY(*this, fileName);
else if (boost::iequals(ext, ".pcd"))
return PointMatcherIO<T>::savePCD(*this, fileName);
else
throw runtime_error("save(): Unknown extension \"" + ext + "\" for file \"" + fileName + "\", extension must be either \".vtk\", \".ply\", \".pcd\" or \".csv\"");
}
template
void PointMatcher<float>::DataPoints::save(const std::string& fileName, bool binary) const;
template
void PointMatcher<double>::DataPoints::save(const std::string& fileName, bool binary) const;
//! Save point cloud to a file as CSV
template<typename T>
void PointMatcherIO<T>::saveCSV(const DataPoints& data, const std::string& fileName)
{
ofstream ofs(fileName.c_str());
if (!ofs.good())
throw runtime_error(string("Cannot open file ") + fileName);
saveCSV(data, ofs);
}
//! Save point cloud to a stream as CSV
template<typename T>
void PointMatcherIO<T>::saveCSV(const DataPoints& data, std::ostream& os)
{
const int pointCount(data.features.cols());
const int dimCount(data.features.rows());
const int descDimCount(data.descriptors.rows());
if (pointCount == 0)
{
LOG_WARNING_STREAM( "Warning, no points, doing nothing");
return;
}
// write header
for (int i = 0; i < dimCount - 1; i++)
{
os << data.featureLabels[i].text;
if (!((i == (dimCount - 2)) && descDimCount == 0))
os << ",";
}
int n = 0;
for (size_t i = 0; i < data.descriptorLabels.size(); i++)
{
Label lab = data.descriptorLabels[i];
for (size_t s = 0; s < lab.span; s++)
{
os << getColLabel(lab,s);
if (n != (descDimCount - 1))
os << ",";
n++;
}
}
os << "\n";
// write points
for (int p = 0; p < pointCount; ++p)
{
for (int i = 0; i < dimCount-1; ++i)
{
os << data.features(i, p);
if(!((i == (dimCount - 2)) && descDimCount == 0))
os << " , ";
}
for (int i = 0; i < descDimCount; i++)
{
os << data.descriptors(i,p);
if (i != (descDimCount - 1))
os << ",";
}
os << "\n";
}
}
template
void PointMatcherIO<float>::saveCSV(const DataPoints& data, const std::string& fileName);
template
void PointMatcherIO<double>::saveCSV(const DataPoints& data, const std::string& fileName);
//! Load point cloud from a file as VTK
template<typename T>
typename PointMatcher<T>::DataPoints PointMatcherIO<T>::loadVTK(const std::string& fileName)
{
ifstream ifs(fileName.c_str(), std::ios::binary);
if (!ifs.good())
throw runtime_error(string("Cannot open file ") + fileName);
return loadVTK(ifs);
}
void skipBlock(bool binary, int binarySize, std::istream & is, bool hasSeparateSizeParameter = true){
int n;
int size;
is >> n;
if(!is.good()){
throw std::runtime_error("File violates the VTK format : parameter 'n' is missing after a field name.");
}
if(hasSeparateSizeParameter) {
is >> size;
if(!is.good()){
throw std::runtime_error("File violates the VTK format : parameter 'size' is missing after a field name.");
}
} else {
size = n;
}
std::string line;
safeGetLine(is, line); // remove line end after parameters;
if(binary){
is.seekg(size * binarySize, std::ios_base::cur);
} else {
for (int p = 0; p < n; p++)
{
safeGetLine(is, line);
}
}
}
//! Load point cloud from a stream as VTK
template<typename T>
typename PointMatcher<T>::DataPoints PointMatcherIO<T>::loadVTK(std::istream& is)
{
std::map<std::string, SplitTime> labelledSplitTime;
DataPoints loadedPoints;
// parse header
string line;
safeGetLine(is, line);
if (line.find("# vtk DataFile Version") != 0)
throw runtime_error(string("Wrong magic header, found ") + line);
safeGetLine(is, line);
safeGetLine(is, line);
const bool isBinary = (line == "BINARY");
if (line != "ASCII"){
if(!isBinary){
throw runtime_error(string("Wrong file type, expecting ASCII or BINARY, found ") + line);
}
}
safeGetLine(is, line);
SupportedVTKDataTypes dataType;
if (line == "DATASET POLYDATA")
dataType = POLYDATA;
else if (line == "DATASET UNSTRUCTURED_GRID")
dataType = UNSTRUCTURED_GRID;
else
throw runtime_error(string("Wrong data type, expecting DATASET POLYDATA, found ") + line);
// parse points, descriptors and time
string fieldName;
string name;
int dim = 0;
int pointCount = 0;
string type;
while (is >> fieldName)
{
// load features
if(fieldName == "POINTS")
{
is >> pointCount;
is >> type;
safeGetLine(is, line); // remove line end after parameters!
if(!(type == "float" || type == "double"))
throw runtime_error(string("Field POINTS can only be of type double or float"));
Matrix features(4, pointCount);
for (int p = 0; p < pointCount; ++p)