forked from rafapages/pointcloudmesher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpcMesher.cpp
1614 lines (1136 loc) · 48.2 KB
/
pcMesher.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
#define PCL_NO_PRECOMPILE
#include <pcl/io/ply_io.h>
#include <pcl/io/pcd_io.h>
#include <pcl/io/vtk_lib_io.h>
#include <pcl/filters/statistical_outlier_removal.h>
#include <pcl/features/normal_3d.h>
#include <pcl/kdtree/kdtree_flann.h>
#include <pcl/conversions.h>
#include <pcl/surface/simplification_remove_unused_vertices.h>
#include <pcl/surface/gp3.h>
#include <pcl/ModelCoefficients.h>
#include <pcl/sample_consensus/method_types.h>
#include <pcl/sample_consensus/model_types.h>
#include <pcl/segmentation/sac_segmentation.h>
#include <pcl/filters/voxel_grid.h>
#include <pcl/filters/extract_indices.h>
#include <pcl/filters/voxel_grid.h>
#include <pcl/segmentation/extract_clusters.h>
#include <pcl/surface/vtk_smoothing/vtk_mesh_quadric_decimation.h>
#include <pcl/surface/vtk_smoothing/vtk_mesh_smoothing_laplacian.h>
#include <pcl/geometry/mesh_conversion.h>
#include <pcl/geometry/mesh_io.h>
#include <pcl/geometry/polygon_mesh.h>
#include <pcl/geometry/get_boundary.h>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/filters/filter.h>
#include <FreeImagePlus.h>
#include <stdlib.h> /* strtol */
#include "pcMesher.h"
PcMesher::PcMesher(){
pointClouds_.clear();
nClouds_ = 0;
cameras_.clear();
nCameras_ = 0;
imageList_.clear();
camPerVtx_.clear();
}
PcMesher::~PcMesher(){
}
unsigned int PcMesher::getNClouds() const {
return nClouds_;
}
std::vector<std::vector<int> > PcMesher::getCamPerVtx() const {
return camPerVtx_;
}
PointCloud<PointXYZRGBNormalCam>::Ptr PcMesher::getPointCloudPtr(unsigned int _index){
return pointClouds_[_index];
}
void PcMesher::clearPointClouds(){
pointClouds_.clear();
}
Eigen::Vector3f PcMesher::getDimensions(const PointCloud<PointXYZRGBNormalCam>::Ptr &_cloud){
std::cerr << "Estimating dimensions of point cloud" << std::endl;
float minx, miny, minz, maxx, maxy, maxz;
minx = miny = minz = FLT_MAX;
maxx = maxy = maxz = FLT_MIN;
for (unsigned int i = 0; i < _cloud->points.size(); i++){
PointXYZRGBNormalCam current = _cloud->points[i];
if (current.x < minx){
minx = current.x;
}
if (current.y < miny){
miny = current.y;
}
if (current.z < minz){
minz = current.z;
}
if (current.x > maxx){
maxx = current.x;
}
if (current.y > maxy){
maxy = current.y;
}
if (current.z > maxz){
maxz = current.z;
}
}
const float dimx = fabs(maxx - minx);
const float dimy = fabs(maxy - miny);
const float dimz = fabs(maxz - minz);
return Eigen::Vector3f(dimx, dimy, dimz);
}
Eigen::Vector3f PcMesher::getDimensions(const unsigned int _index){
PointCloud<PointXYZRGBNormalCam>::Ptr pointcloud = pointClouds_[_index];
return this->getDimensions(pointcloud);
}
Eigen::Vector3f PcMesher::getDimensions(const PolygonMesh &_mesh){
PointCloud<PointXYZRGBNormalCam> meshCloud;
fromPCLPointCloud2 (_mesh.cloud, meshCloud);
PointCloud<PointXYZRGBNormalCam>::Ptr meshCloudPtr = boost::make_shared<PointCloud<PointXYZRGBNormalCam> >(meshCloud);
Eigen::Vector3f dims = this->getDimensions(meshCloudPtr);
return dims;
}
double PcMesher::computeResolution(const PointCloud<PointXYZRGBNormalCam>::Ptr &_cloud) const {
double res = 0.0;
int n_points = 0;
int nres;
std::vector<int> indices (2);
std::vector<float> sqr_distances (2);
pcl::search::KdTree<PointXYZRGBNormalCam> tree;
tree.setInputCloud (_cloud);
for (size_t i = 0; i < _cloud->size (); ++i){
if (! pcl_isfinite ((*_cloud)[i].x)){
continue;
}
//Considering the second neighbor since the first is the point itself.
nres = tree.nearestKSearch (i, 2, indices, sqr_distances);
if (nres == 2){
res += sqrt (sqr_distances[1]);
++n_points;
}
}
if (n_points != 0){
res /= n_points;
}
return res;
}
void PcMesher::removeOutliers(PointCloud<PointXYZRGBNormalCam>::Ptr& _cloud){
StatisticalOutlierRemoval<PointXYZRGBNormalCam> sor;
sor.setInputCloud(_cloud);
sor.setMeanK(50);
sor.setStddevMulThresh(1.0);
sor.filter(*_cloud);
}
void PcMesher::removeOutliers(unsigned int _index){
std::cerr << "Removing outliers of pointcloud " << _index + 1 << "/" << nClouds_ << std::endl;
PointCloud<PointXYZRGBNormalCam>::Ptr cloud = pointClouds_[_index];
PointIndices outliers;
StatisticalOutlierRemoval<PointXYZRGBNormalCam> sor(true); // Setting this to true we are able to extract indices of deleted points
sor.setInputCloud(cloud);
sor.setMeanK(50);
sor.setStddevMulThresh(1.0);
// sor.setStddevMulThresh(0.5);
sor.filter(*cloud);
// Indices to outliers
sor.getRemovedIndices(outliers);
removeOutliersFromCamPerVtx(outliers);
}
void PcMesher::removeAllOutliers(){
for (unsigned int i = 0; i < pointClouds_.size(); i++){
this->removeOutliers(i);
}
}
void PcMesher::downSample(const PointCloud<PointXYZRGBNormalCam>::Ptr& _cloud, PointCloud<PointXYZRGBNormalCam>::Ptr _outCloud){
pcl::PCLPointCloud2::Ptr outcloud (new pcl::PCLPointCloud2 ());
pcl::PCLPointCloud2::Ptr incloud (new pcl::PCLPointCloud2 ());
toPCLPointCloud2(*_cloud, *incloud);
double res = computeResolution(_cloud);
std::cerr << "PointCloud before filtering: " << _cloud->width * _cloud->height << std::endl;
std::cerr << "Downsampling point cloud..." << std::endl;
// Create the filtering object
VoxelGrid<pcl::PCLPointCloud2> sor;
sor.setInputCloud (incloud);
// sor.setLeafSize (0.05f, 0.05f, 0.05f);
sor.setLeafSize (10*res, 10*res, 10*res);
sor.filter (*outcloud);
// PointCloud instead of PCLPointCloud2
fromPCLPointCloud2 (*outcloud, *_outCloud);
std::cerr << "PointCloud after filtering: " << _outCloud->width * _outCloud->height << std::endl;
}
void PcMesher::getPlaneDefinedByCameras(PointXYZRGBNormalCam& _normal) const{
std::vector<Eigen::Vector3f> cam_pos;
for (unsigned int i = 0; i < cameras_.size(); i++){
const Camera c = cameras_[i];
cam_pos.push_back(c.getCameraPosition());
}
Eigen::Vector3f normal;
fitPlane(cam_pos, normal);
_normal.x = normal(0);
_normal.y = normal(1);
_normal.z = normal(2);
// std::cerr << "normal\n" << normal << std::endl;
}
void PcMesher::fitPlane(const std::vector<Eigen::Vector3f> _cloud, Eigen::Vector3f& _normal) const{
// http://stackoverflow.com/questions/1400213/3d-least-squares-plane
Eigen::Matrix3f A;
Eigen::Vector3f b;
float xx, xy, yy, xz, yz, x, y, z;
xx = xy = yy = xz = yz = x = y = z = 0.0;
for (unsigned int i = 0; i < _cloud.size(); i++){
const Eigen::Vector3f current = _cloud[i];
xx += current(0) * current(0);
xy += current(0) * current(1);
yy += current(1) * current(1);
xz += current(0) * current(2);
yz += current(1) * current(2);
x = current(0);
y = current(1);
z = current(2);
}
A << xx, xy, x,
xy, yy, y,
x, y, (float) _cloud.size();
b << xz, yz, z;
_normal = A.colPivHouseholderQr().solve(b);
_normal.normalize();
}
void PcMesher::estimateNormals(const unsigned int _index){
std::cerr << "Estimating normals of pointcloud " << _index + 1 << "/" << nClouds_ << std::endl;
// Create the normal estimation class, and pass the input dataset to it
PointCloud<PointXYZRGBNormalCam>::Ptr cloud = pointClouds_[_index];
NormalEstimation<PointXYZRGBNormalCam, PointXYZRGBNormalCam> ne;
ne.setInputCloud(cloud);
// Create an empty kdtree representation, and pass it to the normal estimation object.
// Its content will be filled inside the object, based on the given input dataset (as no other search surface is given).
search::KdTree<PointXYZRGBNormalCam>::Ptr tree (new search::KdTree<PointXYZRGBNormalCam> ());
ne.setSearchMethod (tree);
// Use all neighbors in a sphere of radius 3cm
ne.setRadiusSearch (0.3); // <--------------------- IT'S IMPORTANT TO DETERMINE THIS NUMBER PROPERLY
// Compute the features
ne.compute (*cloud);
}
void PcMesher::estimateNormals(const unsigned int _index, const float _radius){
std::cerr << "Estimating normals of pointcloud " << _index + 1 << "/" << nClouds_ << std::endl;
// Create the normal estimation class, and pass the input dataset to it
PointCloud<PointXYZRGBNormalCam>::Ptr cloud = pointClouds_[_index];
NormalEstimation<PointXYZRGBNormalCam, PointXYZRGBNormalCam> ne;
ne.setInputCloud(cloud);
// Create an empty kdtree representation, and pass it to the normal estimation object.
// Its content will be filled inside the object, based on the given input dataset (as no other search surface is given).
search::KdTree<PointXYZRGBNormalCam>::Ptr tree (new search::KdTree<PointXYZRGBNormalCam> ());
ne.setSearchMethod (tree);
// Use all neighbors in a sphere of radius <_radius>
ne.setRadiusSearch (_radius);
// Compute the features
ne.compute (*cloud);
}
void PcMesher::estimateAllNormals(){
for (unsigned int i = 0; i < pointClouds_.size(); i++){
estimateNormals(i);
}
}
void PcMesher::estimateAllNormals(const float _radius){
for (unsigned int i = 0; i < pointClouds_.size(); i++){
estimateNormals(i, _radius);
}
}
void PcMesher::fixNormal(const unsigned int _index){
PointCloud<PointXYZRGBNormalCam>::Ptr cloud = pointClouds_[_index];
for (unsigned int i = 0; i < cloud->points.size(); i++){
PointXYZRGBNormalCam current = cloud->points[i];
Eigen::Vector3f cur_pos = current.getArray3fMap();
Eigen::Vector3f cam_pos = cameras_[current.camera].getCameraPosition();
Eigen::Vector3f cam_dir = cam_pos - cur_pos;
Eigen::Vector3f normal = current.getNormalVector3fMap();
if (cam_dir.dot(normal) < 0){
cloud->points[i].normal_x = -current.normal_x;
cloud->points[i].normal_y = -current.normal_y;
cloud->points[i].normal_z = -current.normal_z;
}
}
}
void PcMesher::fixAllNormals(){
for (unsigned int i = 0; i < pointClouds_.size(); i++){
fixNormal(i);
}
}
void PcMesher::segmentPlanes(float _threshold){
std::cerr << "Segmenting planes" << std::endl;
PointCloud<PointXYZRGBNormalCam>::Ptr cloud = pointClouds_[0];
PointCloud<PointXYZRGBNormalCam>::Ptr cloud_p (new PointCloud<PointXYZRGBNormalCam>);
PointCloud<PointXYZRGBNormalCam>::Ptr cloud_f (new PointCloud<PointXYZRGBNormalCam>);
PointCloud<PointXYZRGBNormalCam>::Ptr tempPlaneCloud (new PointCloud<PointXYZRGBNormalCam>);
PointCloud<PointXYZRGBNormalCam>::Ptr emptyCloud (new PointCloud<PointXYZRGBNormalCam>);
ModelCoefficients::Ptr coefficients (new ModelCoefficients ());
PointIndices::Ptr inliers (new PointIndices ());
// PointIndices lastOutliers;
// Create the segmentation object
SACSegmentation<PointXYZRGBNormalCam> seg;
seg.setOptimizeCoefficients (true);
seg.setModelType (SACMODEL_PLANE);
seg.setMethodType (SAC_RANSAC);
seg.setMaxIterations (1000);
// seg.setDistanceThreshold(0.1);
seg.setDistanceThreshold(_threshold);
// seg.setDistanceThreshold(0.03);
// Create the filtering object
ExtractIndices<PointXYZRGBNormalCam> extract(true); // set to true to be able to extract the outliers also
int i = 0;
const int nr_points = (int) cloud->points.size ();
// To avoid an infinite loop
const int max_iter = 10;
int iter = 0;
// While 5% of the original cloud is still there
while (cloud->points.size () > 0.05 * nr_points) // 0.01
{
if (iter == max_iter) break;
// Segment the largest planar component from the remaining cloud
seg.setInputCloud (cloud);
seg.segment (*inliers, *coefficients);
if (inliers->indices.size () == 0){
std::cerr << "Could not estimate a planar model for the given dataset." << std::endl;
break;
}
// We get the normal of the estimated plane
Eigen::Vector3f planeNormal(coefficients->values[0], coefficients->values[1], coefficients->values[2]);
const int inliersOrignalSize = inliers->indices.size();
// We check if every inlier orientation is the aprox. the same as the plane's
for (unsigned int j = 0; j < inliersOrignalSize; j++){
PointXYZRGBNormalCam current = cloud->points[inliers->indices[j]];
Eigen::Vector3f cur_norm(current.normal_x, current.normal_y, current.normal_z);
const float cos = planeNormal.dot(cur_norm) / (planeNormal.squaredNorm() * cur_norm.squaredNorm());
// vectors with normals in an angle bigger than 45º are marked with -1 in the inlier list
if ( fabs(cos) < 0.707){ // >45º
inliers->indices[j] = -1;
}
}
// inliers marked as -1 are removed from the list
inliers->indices.erase(std::remove(inliers->indices.begin(), inliers->indices.end(), -1), inliers->indices.end());
// if not enough points are left to determine a plane, we move to the following plane
bool badplane = false;
if (inliers->indices.size() < 0.01 * nr_points) {
// if (inliers->indices.size() < 0.005 * nr_points) {
std::cerr << iter << std::endl;
std::cerr << inliers->indices.size() << "/" << inliersOrignalSize << std::endl;
iter++;
badplane = true;
}
// Extract the inliers
extract.setInputCloud (cloud);
extract.setIndices (inliers);
extract.setNegative (false);
extract.filter (*cloud_p);
// Indices to outliers
// extract.getRemovedIndices(lastOutliers);
if (!badplane){ // If we have a valid plane, we save it
// We create a pointer to a copy of the plane cloud to be able to store properly
PointCloud<PointXYZRGBNormalCam>::Ptr plane_cloud = boost::make_shared<PointCloud<PointXYZRGBNormalCam> >(*cloud_p);
pointClouds_.push_back(plane_cloud);
nClouds_++;
// Create the filtering object
extract.setNegative (true);
extract.filter (*cloud_f);
cloud.swap (cloud_f);
*pointClouds_[0] += *tempPlaneCloud;
tempPlaneCloud = emptyCloud; // To clear the content of temPlaneCloud
std::cerr << "PointCloud #" << i+1 << " representing the planar component: " << cloud_p->width * cloud_p->height << " data points. ";
std::cerr << "Points reimaning: " << cloud->width * cloud->height << std::endl;
// Write plane in ply file
std::stringstream ss;
ss << "out_" << i+1 << ".ply";
std::cerr << "PointCloud #" << i+1 << " exported." << std::endl;
io::savePLYFile(ss.str(), *plane_cloud);
i++;
iter = 0;
} else { // In this case, the points are rearranged so we have a different result
extract.setNegative (true);
extract.filter (*cloud_f);
cloud.swap (cloud_f);
*pointClouds_[0] += *tempPlaneCloud;
tempPlaneCloud = boost::make_shared<PointCloud<PointXYZRGBNormalCam> >(*cloud_p);
}
}
std::cerr << "Exporting non-planar points" << std::endl;
io::savePLYFile("outliers.ply", *pointClouds_[0]);
}
void PcMesher::segmentCylinders(){
PointCloud<PointXYZRGBNormalCam>::Ptr cloud = pointClouds_[0];
SACSegmentationFromNormals<PointXYZRGBNormalCam, PointXYZRGBNormalCam> seg;
ExtractIndices<PointXYZRGBNormalCam> extract;
ModelCoefficients::Ptr coefficients (new ModelCoefficients ());
PointIndices::Ptr inliers (new PointIndices ());
// Create the segmentation object for cylinder segmentation and set all the parameters
seg.setOptimizeCoefficients (true);
seg.setModelType (SACMODEL_CYLINDER);
seg.setMethodType (SAC_RANSAC);
// seg.setNormalDistanceWeight (0.1);
seg.setMaxIterations (1000);
seg.setDistanceThreshold (0.1);
seg.setRadiusLimits (0.5, 2);
seg.setInputCloud (cloud);
seg.setInputNormals (cloud);
// Obtain the cylinder inliers and coefficients
seg.segment (*inliers, *coefficients);
std::cerr << "Cylinder coefficients: " << *coefficients << std::endl;
// Write the cylinder inliers to disk
extract.setInputCloud (cloud);
extract.setIndices (inliers);
extract.setNegative (false);
pcl::PointCloud<PointXYZRGBNormalCam>::Ptr cloud_cylinder (new pcl::PointCloud<PointXYZRGBNormalCam> ());
// We create a pointer to a copy of the plane cloud to be able to store properly
PointCloud<PointXYZRGBNormalCam>::Ptr cyl_cloud = boost::make_shared<PointCloud<PointXYZRGBNormalCam> >(*cloud_cylinder);
extract.filter (*cloud_cylinder);
if (cloud_cylinder->points.empty ()) {
std::cerr << "Can't find the cylindrical component." << std::endl;
} else {
io::savePLYFile("cilindro.ply", *cloud_cylinder);
pointClouds_.push_back(cyl_cloud);
nClouds_++;
}
}
void PcMesher::surfaceReconstruction(const unsigned int _index){
PointCloud<PointXYZRGBNormalCam>::Ptr cloud = pointClouds_[_index];
Poisson<PointXYZRGBNormalCam> poisson;
poisson.setDepth(10);
poisson.setInputCloud(cloud);
PolygonMesh mesh;
poisson.reconstruct(mesh);
std::stringstream ss;
ss << "triangles_" << _index << ".ply";
io::savePLYFile(ss.str(), mesh);
}
PolygonMesh PcMesher::surfaceReconstruction(PointCloud<PointXYZRGBNormalCam>::Ptr _cloud){
Poisson<PointXYZRGBNormalCam> poisson;
poisson.setDepth(10);
poisson.setInputCloud(_cloud);
PolygonMesh mesh;
poisson.reconstruct(mesh);
return mesh;
}
PolygonMesh PcMesher::deleteWrongVertices(PointCloud<PointXYZRGBNormalCam>::Ptr _cloud, PolygonMesh& _inputMesh){
std::cerr << "Cleaning the Poisson mesh" << std::endl;
// This value needs to be automatized
float MAXD = 0.1;
KdTreeFLANN<PointXYZRGBNormalCam> kdtree;
kdtree.setInputCloud(_cloud);
// Some data for the output mesh:
// vector for storing valid polygons
std::vector<Vertices> validFaces;
// PointCloud instead of PCLPointCloud2
PointCloud<PointXYZRGBNormalCam> meshCloud;
fromPCLPointCloud2 (_inputMesh.cloud, meshCloud);
// foreach face
std::vector<Vertices, std::allocator<Vertices> >::iterator face_it; // por qué el allocator?
for (face_it = _inputMesh.polygons.begin(); face_it != _inputMesh.polygons.end(); ++face_it) {
bool isInside = true;
// for each vertex in the face
for (unsigned int i = 0; i < 3; i++){
PointXYZRGBNormalCam searchPoint = meshCloud.points[face_it->vertices[i]];
// We first search for the closest point in the original point cloud to the searchPoint
std::vector<int> pointIdxNKNSearch(1);
std::vector<float> pointNKNSquaredDistance(1);
float radius;
if ( kdtree.nearestKSearch (searchPoint, 1, pointIdxNKNSearch, pointNKNSquaredDistance) > 0 ){
for (size_t ind = 0; ind < pointIdxNKNSearch.size(); ++ind){ // It's just one iteration
// Now we search for the K closest points to determine the point cloud density
PointXYZRGBNormalCam anchorPoint = _cloud->points[pointIdxNKNSearch[ind]];
int K = 10;
std::vector<int> pointIdx(K);
std::vector<float> pointSquaredDistance(K);
float sum_distance = 0.0;
if (kdtree.nearestKSearch(anchorPoint, K, pointIdx, pointSquaredDistance) > 0){
for (int j = 0; j < pointIdx.size(); ++j){
sum_distance += sqrt(pointSquaredDistance[j]);
}
}
radius = sum_distance / static_cast<float>(K) * 10.0f; // 3.0f: the bigger this number, the lower number of holes
}
}
// Neighbors within radius search
std::vector<int> pointIdxRadiusSearch;
std::vector<float> pointRadiusSquaredDistance;
// float radius = MAXD;
// if there is no vertex in the input point cloud close to this current vertex of the mesh
// the whole face is discarded
if ( kdtree.radiusSearch (searchPoint, radius, pointIdxRadiusSearch, pointRadiusSquaredDistance) <= 0 ){
isInside = false;
break;
}
}
if (isInside) validFaces.push_back(*face_it);
}
// Write output polygon mesh
PolygonMesh outputMesh;
// Same point cloud as the input mesh
outputMesh.cloud = _inputMesh.cloud;
// Only the valid faces
outputMesh.polygons.clear();
outputMesh.polygons.insert(outputMesh.polygons.begin(), validFaces.begin(), validFaces.end());
// Here we delete unused vertices
PolygonMesh finalOutputMesh;
surface::SimplificationRemoveUnusedVertices cleaner;
cleaner.simplify(outputMesh, finalOutputMesh);
return finalOutputMesh;
}
PolygonMesh PcMesher::decimateMesh(const PolygonMesh& _mesh, float _reduction){
// _reduction goes from 0 to 1
std::cerr << "Decimating mesh a " << (1 - _reduction) * 100 << "%" << std::endl;
PolygonMesh::Ptr meshPtr = boost::make_shared<PolygonMesh>(_mesh);
PolygonMesh outputMesh;
MeshQuadricDecimationVTK decimator;
decimator.setInputMesh(meshPtr);
// decimator.setTargetReductionFactor(0.99f);
decimator.setTargetReductionFactor(1 - _reduction);
decimator.process(outputMesh);
return outputMesh;
}
PolygonMesh PcMesher::smoothMeshLaplacian(const PolygonMesh &_mesh){
std::cerr << "Applying Laplacian filtering to mesh" << std::endl;
PolygonMesh::Ptr meshPtr = boost::make_shared<PolygonMesh>(_mesh);
PolygonMesh outputMesh;
MeshSmoothingLaplacianVTK smoother;
smoother.setInputMesh(meshPtr);
smoother.setNumIter(3);
smoother.setRelaxationFactor(0.5);
smoother.process(outputMesh);
return outputMesh;
}
void PcMesher::detectLargestComponent(Mesh &_inputMesh) const {
std::vector<bool> visited(_inputMesh.sizeVertices(), false);
std::vector<std::vector<Mesh::VertexIndex> > components;
unsigned int nComponents = 0;
Mesh::VertexIndex vi;
while (true){
//find an unvisited vertex
bool found = false;
for (unsigned int i = 0; i < _inputMesh.sizeVertices(); i++){
if(!visited[i]){
found = true;
visited[i] = true;
vi = Mesh::VertexIndex(i);
break;
}
}
//if none was found -> finished
if (!found) break;
nComponents++;
std::vector<Mesh::VertexIndex> vindices;
std::vector<Mesh::VertexIndex> componentIndices;
vindices.push_back(vi);
while(vindices.size() > 0){
Mesh::VertexIndex current = vindices.back();
vindices.pop_back();
Mesh::VertexAroundVertexCirculator vac = _inputMesh.getVertexAroundVertexCirculator(current);
const Mesh::VertexAroundVertexCirculator vac_end = vac;
do {
if (!visited[vac.getTargetIndex().get()]){
visited[vac.getTargetIndex().get()] = true;
vindices.push_back(vac.getTargetIndex());
componentIndices.push_back(vac.getTargetIndex());
}
} while (++vac != vac_end);
}
components.push_back(componentIndices);
}
std::cerr << "Number of mesh components: " << nComponents << std::endl;
// In case there is more than one component, we just keep the largest
if (components.size() != 1){
int maxIndex = -1;
unsigned int maxNumber = 0;
for (unsigned int i = 0; i < components.size(); i++){
if (components[i].size() > maxNumber){
maxIndex = i;
maxNumber = components[i].size();
}
}
std::cerr << "Largest component is number " << maxIndex << " with " << maxNumber << " elements" << std::endl;
for (unsigned int i = 0; i < components.size(); i++){
// Vertices which don't belong to largest component are deleted
if (i != maxIndex){
const std::vector<Mesh::VertexIndex> curr_comp = components[i];
for (unsigned int j = 0; j < curr_comp.size(); j++){
const Mesh::VertexIndex curr_vi = curr_comp[j];
_inputMesh.deleteVertex(curr_vi);
}
}
}
}
_inputMesh.cleanUp();
}
bool PcMesher::isMeshOpen(const Mesh& _inputMesh) const {
bool open = false;
for (unsigned int i = 0; i < _inputMesh.sizeVertices(); i++){
if (_inputMesh.isBoundary(Mesh::VertexIndex(i))){
open = true;
break;
}
}
return open;
}
void PcMesher::openHole(Mesh &_inputMesh, const PointXYZRGBNormalCam& _normal) const {
// if (isMeshOpen(_inputMesh)){
// std::cerr << "Mesh is already open!" << std::endl;
// return;
// }
Mesh::VertexIndex highest, lowest;
float ftop, fbot;
ftop = -FLT_MAX;
fbot = FLT_MAX;
Eigen::Vector3f normal = _normal.getArray3fMap();
for (unsigned int i = 0; i < _inputMesh.sizeVertices(); i++){
const Mesh::VertexIndex vidx = Mesh::VertexIndex(i);
const PointXYZRGBNormalCam ve = _inputMesh.getVertexDataCloud()[vidx.get()];
Eigen::Vector3f v = ve.getArray3fMap();
float dotp = normal.dot(v);
if (dotp > ftop){
ftop = dotp;
highest = vidx;
}
if (dotp < fbot){
fbot = dotp;
lowest = vidx;
}
}
Mesh::FaceAroundVertexCirculator hcirc = _inputMesh.getFaceAroundVertexCirculator(highest);
const Mesh::FaceAroundVertexCirculator hcirc_end = hcirc;
do{
Mesh::FaceIndex fidx = hcirc.getTargetIndex();
if (fidx.isValid()){
_inputMesh.deleteFace(fidx);
break;
}
} while (++hcirc != hcirc_end);
Mesh::FaceAroundVertexCirculator lcirc = _inputMesh.getFaceAroundVertexCirculator(lowest);
const Mesh::FaceAroundVertexCirculator lcirc_end = lcirc;
do{
Mesh::FaceIndex fidx = lcirc.getTargetIndex();
if (fidx.isValid()){
_inputMesh.deleteFace(fidx);
break;
}
} while (++lcirc != lcirc_end);
_inputMesh.cleanUp();
// pcl::PolygonMesh out;
// pcl::geometry::toFaceVertexMesh(_inputMesh, out);
// io::savePLYFile("prueba3.ply", out);
}
void PcMesher::cleanOpenMesh(const PointCloud<PointXYZRGBNormalCam>::Ptr& _cloud, Mesh &_inputMesh) const {
if (!isMeshOpen(_inputMesh)){
std::cerr << "This mesh is not open!" << std::endl;
return;
}
// we acquire a set of boundary halfedges
std::vector<Mesh::HalfEdgeIndices> boundary;
pcl::geometry::getBoundBoundaryHalfEdges(_inputMesh, boundary);
for (unsigned int i = 0; i < boundary.size(); i++){
Mesh::HalfEdgeIndices b = boundary[i];
std::cerr << "Part " << i << " has " << b.size() << " boundary helfedges" << std::endl;
}
// Save the original boundary sizes
std::vector<int> nBounds;
int nParts = boundary.size();
for (unsigned int i = 0; i < boundary.size(); i++){
nBounds.push_back(boundary[i].size());
}
// Estimate the optimal search radius
double resolution = computeResolution(_cloud);
float radius = 5*resolution;
// Search
bool far = true;
int it = 0;
while (far){
far = false;
for (unsigned int i = 0; i < boundary.size(); i++){
Mesh::HalfEdgeIndices b = boundary[i];
for (unsigned int j = 0; j < b.size(); j++){
const Mesh::HalfEdgeIndex hei = b[j];
const Mesh::VertexIndex vei = _inputMesh.getOriginatingVertexIndex(hei);
if (!vei.isValid()) continue;
const PointXYZRGBNormalCam current = _inputMesh.getVertexDataCloud()[vei.get()];
const Mesh::FaceIndex face = _inputMesh.getOppositeFaceIndex(hei);
//std::cerr << i << "/" << j << std::endl;
if (!isPointCloseToPointCloud(current, _cloud, radius) && face.isValid()){
// We remove all faces containing the current vertex
Mesh::FaceAroundVertexCirculator fav = _inputMesh.getFaceAroundVertexCirculator(_inputMesh.getOriginatingVertexIndex(hei));
const Mesh::FaceAroundVertexCirculator fav_end = fav;
std::vector<Mesh::FaceIndex> toDelete;
do {
Mesh::FaceIndex fav_face = fav.getTargetIndex();
toDelete.push_back(fav_face);
} while (++fav != fav_end);
for (unsigned int j = 0; j < toDelete.size(); j++){
if (toDelete[j].isValid()){
_inputMesh.deleteFace(toDelete[j]);
}
}
_inputMesh.deleteFace(face);
far = true;
}
}
}
_inputMesh.cleanUp();
boundary.clear();
pcl::geometry::getBoundBoundaryHalfEdges(_inputMesh, boundary);
// To avoid extra calculations, if a boundary has not changed, it is not
// iterated again. We keep track of the number of halfedges in each iteration,
// so if this number hasn't changed, we don't analyze the boundary again.
//
if (nParts != boundary.size()){
// Update nBounds and nParts
nParts = boundary.size();
for (unsigned int i = 0; i < boundary.size(); i++){
nBounds.push_back(boundary[i].size());
}
} else {
std::vector<Mesh::HalfEdgeIndices>::iterator itt = boundary.end()-1;
for (int i = nParts-1; i >= 0; i--){ // starting from the end helps optimizing deletion
if (nBounds[i] == boundary[i].size()){
boundary.erase(itt);
} else {
// The value in nBounds is updated
nBounds[i] = boundary[i].size();
}
if (itt != boundary.begin()) // just in case...
itt--;
}
}
// TEST: just to see the effect ------------
for (unsigned int i = 0; i < nBounds.size(); i++){
std::cerr << nBounds[i] << " ";
}
std::cerr << "\n";
for (unsigned int i = 0; i < boundary.size(); i++){
std::cerr << "Part " << i << " has " << boundary[i].size() << " boundary helfedges" << std::endl;
}
it++;
// pcl::PolygonMesh test;
// pcl::geometry::toFaceVertexMesh(_inputMesh, test);
// std::stringstream ss;
// ss << it;
// ss << ".ply";
// io::savePLYFile(ss.str().c_str(), test);
// ----------------------------------------