-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathDFSegmentation.cc
More file actions
546 lines (498 loc) · 26.6 KB
/
DFSegmentation.cc
File metadata and controls
546 lines (498 loc) · 26.6 KB
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
#include "DFSegmentation.hh"
#include <cilantro/utilities/point_cloud.hpp>
#include <cilantro/core/nearest_neighbors.hpp>
#include <cilantro/clustering/connected_component_extraction.hpp>
#include <cmath>
namespace diffCheck::segmentation
{
std::vector<std::shared_ptr<geometry::DFPointCloud>> DFSegmentation::NormalBasedSegmentation(
std::shared_ptr<geometry::DFPointCloud> &pointCloud,
float normalThresholdDegree,
int minClusterSize,
bool useKnnNeighborhood,
int knnNeighborhoodSize,
float radiusNeighborhoodSize,
bool colorClusters)
{
if (!pointCloud->HasNormals())
{
DIFFCHECK_WARN("The point cloud does not have normals. Estimating normals with 50 neighbors.");
pointCloud->EstimateNormals(true, 50);
}
std::shared_ptr<cilantro::PointCloud3f> cilantroPointCloud = pointCloud->Cvt2CilantroPointCloud();
std::vector<std::shared_ptr<geometry::DFPointCloud>> segments;
if (useKnnNeighborhood)
{
cilantro::KNNNeighborhoodSpecification<int> neighborhood(knnNeighborhoodSize);
cilantro::NormalsProximityEvaluator<float, 3> similarityEvaluator(
cilantroPointCloud->normals,
normalThresholdDegree*M_PI/180.0f);
cilantro::ConnectedComponentExtraction3f<> segmenter(cilantroPointCloud->points);
segmenter.segment(neighborhood, similarityEvaluator, minClusterSize);
auto clusterToPointMap = segmenter.getClusterToPointIndicesMap();
int nSegments = segmenter.getNumberOfClusters();
for (int indice = 0; indice<nSegments; indice++)
{
std::shared_ptr<geometry::DFPointCloud> segment = std::make_shared<geometry::DFPointCloud>();
for (auto pointIndice : clusterToPointMap[indice])
{
Eigen::Vector3d point = cilantroPointCloud->points.col(pointIndice).cast<double>();
Eigen::Vector3d normal = cilantroPointCloud->normals.col(pointIndice).cast<double>();
segment->Points.push_back(point);
segment->Normals.push_back(normal);
if (cilantroPointCloud->hasColors())
{
Eigen::Vector3d color = cilantroPointCloud->colors.col(pointIndice).cast<double>();
segment->Colors.push_back(color);
}
}
if (colorClusters)
segment->ApplyColor(Eigen::Vector3d::Random());
segments.push_back(segment);
}
}
else
{
cilantro::RadiusNeighborhoodSpecification<float> neighborhood(radiusNeighborhoodSize);
cilantro::NormalsProximityEvaluator<float, 3> similarityEvaluator(
cilantroPointCloud->normals,
normalThresholdDegree*M_PI/180.0f);
cilantro::ConnectedComponentExtraction3f<> segmenter(cilantroPointCloud->points);
segmenter.segment(neighborhood, similarityEvaluator, minClusterSize);
auto clusterToPointMap = segmenter.getClusterToPointIndicesMap();
int nSegments = segmenter.getNumberOfClusters();
for (int indice = 0; indice<nSegments; indice++)
{
std::shared_ptr<geometry::DFPointCloud> segment = std::make_shared<geometry::DFPointCloud>();
for (auto pointIndice : clusterToPointMap[indice])
{
Eigen::Vector3d point = cilantroPointCloud->points.col(pointIndice).cast<double>();
Eigen::Vector3d normal = cilantroPointCloud->normals.col(pointIndice).cast<double>();
segment->Points.push_back(point);
segment->Normals.push_back(normal);
if (cilantroPointCloud->hasColors())
{
Eigen::Vector3d color = cilantroPointCloud->colors.col(pointIndice).cast<double>();
segment->Colors.push_back(color);
}
}
if (colorClusters)
segment->ApplyColor(Eigen::Vector3d::Random());
segments.push_back(segment);
}
}
return segments;
}
std::vector<std::shared_ptr<geometry::DFPointCloud>> DFSegmentation::AssociateClustersToMeshes(
bool isCylinder,
bool discriminatePoints,
std::vector<std::shared_ptr<geometry::DFMesh>> referenceMesh,
std::vector<std::shared_ptr<geometry::DFPointCloud>> &clusters,
double angleThreshold,
double associationThreshold,
double maximumFaceSegmentDistance)
{
std::vector<std::shared_ptr<geometry::DFPointCloud>> faceSegments = std::vector<std::shared_ptr<geometry::DFPointCloud>>();
// iterate through the mesh faces given as function argument
if (referenceMesh.size() == 0)
{
DIFFCHECK_WARN("No mesh faces to associate with the clusters. Returning an empty point cloud.");
return std::vector<std::shared_ptr<geometry::DFPointCloud>>();
}
//differentiate between cylinder and other shapes
if (isCylinder)
{
for (std::shared_ptr<diffCheck::geometry::DFMesh> face : referenceMesh)
{
std::tuple<Eigen::Vector3d, Eigen::Vector3d> centerAndAxis = face->ComputeOBBCenterAndAxis();
Eigen::Vector3d cylinderCenter = std::get<0>(centerAndAxis);
Eigen::Vector3d cylinderAxis = std::get<1>(centerAndAxis);
double faceDistance = std::numeric_limits<double>::max();
std::shared_ptr<geometry::DFPointCloud> correspondingSegment;
std::shared_ptr<geometry::DFPointCloud> facePoints = std::make_shared<geometry::DFPointCloud>();
Eigen::Vector3d min = face->Vertices[0];
Eigen::Vector3d max = face->Vertices[0];
for (auto vertex : face->Vertices)
{
if(vertex.x() < min.x()){min.x() = vertex.x();}
if(vertex.y() < min.y()){min.y() = vertex.y();}
if(vertex.z() < min.z()){min.z() = vertex.z();}
if(vertex.x() > max.x()){max.x() = vertex.x();}
if(vertex.y() > max.y()){max.y() = vertex.y();}
if(vertex.z() > max.z()){max.z() = vertex.z();}
}
if (clusters.size() == 0)
{
DIFFCHECK_WARN("No clusters to associate with the mesh faces. Returning an empty point cloud.");
return std::vector<std::shared_ptr<geometry::DFPointCloud>>();
}
for (auto segment : clusters)
{
Eigen::Vector3d segmentCenter;
Eigen::Vector3d segmentNormal;
for (auto point : segment->Points)
{
segmentCenter += point;
}
if (segment->GetNumPoints() > 0)
{
segmentCenter /= segment->GetNumPoints();
}
else
{
DIFFCHECK_WARN("Empty segment. Skipping the segment.");
continue;
}
for (auto normal : segment->Normals)
{
segmentNormal += normal;
}
segmentNormal.normalize();
// we consider the distance to the cylinder axis, not the cylinder center
Eigen::Vector3d projectedSegmentCenter = (segmentCenter - cylinderCenter).dot(cylinderAxis) * cylinderAxis + cylinderCenter;
double currentDistance = (cylinderCenter - projectedSegmentCenter).norm();
double absoluteDistance = (segmentCenter - cylinderCenter).norm();
if (std::abs(cylinderAxis.dot(segmentNormal)) < angleThreshold && currentDistance < faceDistance && absoluteDistance < (max - min).norm()*associationThreshold)
{
correspondingSegment = segment;
faceDistance = currentDistance;
}
}
if (correspondingSegment == nullptr)
{
DIFFCHECK_WARN("No segment found for the face. Returning an empty point cloud for this face.");
faceSegments.push_back(facePoints);
continue;
}
bool hasColors = correspondingSegment->GetNumColors() > 0;
for (Eigen::Vector3d point : correspondingSegment->Points)
{
if (face->IsPointOnFace(point, associationThreshold))
{
facePoints->Points.push_back(point);
facePoints->Normals.push_back(
correspondingSegment->Normals[std::distance(
correspondingSegment->Points.begin(),
std::find(correspondingSegment->Points.begin(),
correspondingSegment->Points.end(),
point))]
);
if (hasColors)
{
facePoints->Colors.push_back(
correspondingSegment->Colors[std::distance(
correspondingSegment->Points.begin(),
std::find(correspondingSegment->Points.begin(),
correspondingSegment->Points.end(),
point))]
);
}
}
}
for(Eigen::Vector3d point : facePoints->Points)
{
correspondingSegment->Points.erase(
std::remove(
correspondingSegment->Points.begin(),
correspondingSegment->Points.end(),
point),
correspondingSegment->Points.end());
}
if (correspondingSegment->GetNumPoints() == 0)
{
DIFFCHECK_WARN("No point was left in the segment. Deleting the segment.");
clusters.erase(
std::remove(
clusters.begin(),
clusters.end(),
correspondingSegment),
clusters.end());
}
faceSegments.push_back(facePoints);
}
}
else
{
for (std::shared_ptr<diffCheck::geometry::DFMesh> face : referenceMesh)
{
std::shared_ptr<geometry::DFPointCloud> correspondingSegment;
std::shared_ptr<geometry::DFPointCloud> facePoints = std::make_shared<geometry::DFPointCloud>();
// Getting the center of the mesh
Eigen::Vector3d faceCenter = face->Cvt2O3DTriangleMesh()->GetCenter();
// Getting the normal of the mesh face
Eigen::Vector3d faceNormal = face->GetFirstNormal();
faceNormal.normalize();
double faceDistance = std::numeric_limits<double>::max();
if (clusters.size() == 0)
{
DIFFCHECK_WARN("No clusters to associate with the mesh faces. Returning an empty point cloud.");
return std::vector<std::shared_ptr<geometry::DFPointCloud>>();
}
for (auto segment : clusters)
{
Eigen::Vector3d segmentCenter;
Eigen::Vector3d segmentNormal;
for (auto point : segment->Points){segmentCenter += point;}
if (segment->GetNumPoints() > 0)
{
segmentCenter /= segment->GetNumPoints();
}
else
{
DIFFCHECK_WARN("Empty segment. Skipping the segment.");
continue;
}
for (auto normal : segment->Normals){segmentNormal += normal;}
segmentNormal.normalize();
double currentDistance = (faceCenter - segmentCenter).norm();
double currentDitanceOrthogonalToFace = std::abs((faceCenter - segmentCenter).dot(faceNormal));
double currentAngle = std::abs(sin(acos(faceNormal.dot(faceCenter - segmentCenter))));
if (std::abs(sin(acos(faceNormal.dot(segmentNormal)))) < angleThreshold && currentDitanceOrthogonalToFace < maximumFaceSegmentDistance && currentDitanceOrthogonalToFace < faceDistance)
{
correspondingSegment = segment;
faceDistance = currentDitanceOrthogonalToFace;
}
}
if (correspondingSegment == nullptr)
{
DIFFCHECK_WARN("No segment found for the face. Returning an empty point cloud for this face.");
faceSegments.push_back(facePoints);
continue;
}
bool hasColors = correspondingSegment->GetNumColors() > 0;
for (Eigen::Vector3d point : correspondingSegment->Points)
{
if (discriminatePoints)
{
bool pointInFace = false;
if (face->IsPointOnFace(point, associationThreshold))
{
facePoints->Points.push_back(point);
facePoints->Normals.push_back(
correspondingSegment->Normals[std::distance(
correspondingSegment->Points.begin(),
std::find(correspondingSegment->Points.begin(),
correspondingSegment->Points.end(),
point))]
);
if (hasColors)
{
facePoints->Colors.push_back(
correspondingSegment->Colors[std::distance(
correspondingSegment->Points.begin(),
std::find(correspondingSegment->Points.begin(),
correspondingSegment->Points.end(),
point))]
);
}
}
}
else
{
facePoints->Points.push_back(point);
facePoints->Normals.push_back(
correspondingSegment->Normals[std::distance(
correspondingSegment->Points.begin(),
std::find(correspondingSegment->Points.begin(),
correspondingSegment->Points.end(),
point))]
);
if (hasColors)
{
facePoints->Colors.push_back(
correspondingSegment->Colors[std::distance(
correspondingSegment->Points.begin(),
std::find(correspondingSegment->Points.begin(),
correspondingSegment->Points.end(),
point))]
);
}
}
}
for(Eigen::Vector3d point : facePoints->Points)
{
correspondingSegment->Points.erase(
std::remove(
correspondingSegment->Points.begin(),
correspondingSegment->Points.end(),
point),
correspondingSegment->Points.end());
}
faceSegments.push_back(facePoints);
}
}
return faceSegments;
}
void DFSegmentation::CleanUnassociatedClusters(
bool isCylinder,
bool discriminatePoints,
std::vector<std::shared_ptr<geometry::DFPointCloud>> &unassociatedClusters,
std::vector<std::vector<std::shared_ptr<geometry::DFPointCloud>>> &existingPointCloudSegments,
std::vector<std::vector<std::shared_ptr<geometry::DFMesh>>> meshes,
double angleThreshold,
double associationThreshold,
double maximumFaceSegmentDistance)
{
if (unassociatedClusters.size() == 0)
{
DIFFCHECK_WARN("No unassociated clusters. Nothing is done");
return;
}
else
{
for (std::shared_ptr<geometry::DFPointCloud> cluster : unassociatedClusters)
{
std::shared_ptr<geometry::DFMesh> correspondingMeshFace;
Eigen::Vector3d clusterCenter;
Eigen::Vector3d clusterNormal = Eigen::Vector3d::Zero();
if (cluster->GetNumPoints() == 0)
{
DIFFCHECK_WARN("Empty cluster. Skipping the cluster.");
continue;
}
if (cluster->GetNumNormals() == 0)
{
DIFFCHECK_WARN("Empty normals in the cluster. Skipping the cluster.");
continue;
}
if (meshes.size() == 0)
{
DIFFCHECK_WARN("No meshes to associate with the clusters. Skipping the cluster.");
continue;
}
for (Eigen::Vector3d point : cluster->Points)
{
clusterCenter += point;
}
clusterCenter /= cluster->GetNumPoints();
for (Eigen::Vector3d normal : cluster->Normals)
{
clusterNormal += normal;
}
clusterNormal.normalize();
int meshIndex = 0;
int faceIndex = 0 ;
int goodMeshIndex = 0;
int goodFaceIndex = 0;
double distance = std::numeric_limits<double>::max();
for (std::vector<std::shared_ptr<geometry::DFMesh>> mesh : meshes)
{
if (mesh.size() == 0)
{
DIFFCHECK_WARN("Empty piece in the meshes vector. Skipping the mesh face vector.");
continue;
}
for (std::shared_ptr<geometry::DFMesh> meshFace : mesh)
{
Eigen::Vector3d faceCenter = Eigen::Vector3d::Zero();
Eigen::Vector3d faceNormal = Eigen::Vector3d::Zero();
if (isCylinder)
{
std::vector<Eigen::Vector3d> minmax = meshFace->GetTightBoundingBox();
Eigen::Vector3d min = minmax[0];
Eigen::Vector3d max = minmax[1];
std::tuple<Eigen::Vector3d, Eigen::Vector3d> centerAndAxis = mesh[0]->ComputeOBBCenterAndAxis();
Eigen::Vector3d center = std::get<0>(centerAndAxis);
Eigen::Vector3d axis = std::get<1>(centerAndAxis);
double dotProduct = clusterNormal.dot(axis);
dotProduct = std::max(-1.0, std::min(1.0, dotProduct));
double currentDistance = (center - clusterCenter).norm() ;
double adaptedDistance = currentDistance * std::abs(dotProduct);
if (std::abs(dotProduct) < angleThreshold && adaptedDistance < distance && currentDistance < (max - min).norm()*associationThreshold)
{
goodMeshIndex = meshIndex;
goodFaceIndex = faceIndex;
distance = adaptedDistance;
correspondingMeshFace = meshFace;
}
}
else
{
std::shared_ptr<open3d::geometry::TriangleMesh> o3dFace = meshFace->Cvt2O3DTriangleMesh();
faceNormal = meshFace->GetFirstNormal();
faceNormal.normalize();
faceCenter = o3dFace->GetCenter();
/*
To make sure we select the right meshFace, we add another metric:
Indeed, from experimentation, sometimes the wrong mesh face is selected, because it is parallel to the correct one
(so the normal don't play a role) and the center of the face is closer to the cluster center than the correct face.
To prevent this, we take into the account the angle between the line linking the center of the meshFace considered
and the center of the point cloud cluster and the normal of the cluster. This value should be close to pi/2
The following two lines are not super optimized but more readable than the optimized version
*/
double dotProduct = clusterNormal.dot((clusterCenter - faceCenter).normalized());
dotProduct = std::max(-1.0, std::min(1.0, dotProduct));
double clusterNormalToJunctionLineAngle = std::acos(dotProduct);
double currentDistance = (clusterCenter - faceCenter).norm() * std::abs(std::cos(clusterNormalToJunctionLineAngle))
/ std::min(std::abs(clusterNormal.dot(faceNormal)), 0.05) ;
if (std::abs(sin(acos(faceNormal.dot(clusterNormal)))) < angleThreshold && currentDistance < maximumFaceSegmentDistance && currentDistance * (std::abs(faceNormal.dot((faceCenter - clusterCenter) / (faceCenter - clusterCenter).norm()))) < distance)
{
goodMeshIndex = meshIndex;
goodFaceIndex = faceIndex;
distance = currentDistance;
correspondingMeshFace = meshFace;
}
}
faceIndex++;
}
meshIndex++;
}
if (correspondingMeshFace == nullptr)
{
DIFFCHECK_WARN("No mesh face found for the cluster. Skipping the cluster.");
continue;
}
if (goodMeshIndex >= existingPointCloudSegments.size() || goodFaceIndex >= existingPointCloudSegments[goodMeshIndex].size())
{
DIFFCHECK_WARN("No segment found for the face. Skipping the face.");
continue;
}
std::shared_ptr<geometry::DFPointCloud> completed_segment = existingPointCloudSegments[goodMeshIndex][goodFaceIndex];
for (Eigen::Vector3d point : cluster->Points)
{
if(isCylinder)
{
completed_segment->Points.push_back(point);
completed_segment->Normals.push_back(cluster->Normals[std::distance(cluster->Points.begin(), std::find(cluster->Points.begin(), cluster->Points.end(), point))]);
completed_segment->Colors.push_back(cluster->Colors[std::distance(cluster->Points.begin(), std::find(cluster->Points.begin(), cluster->Points.end(), point))]);
}
else
{
if (discriminatePoints)
{
if (correspondingMeshFace->IsPointOnFace(point, associationThreshold))
{
completed_segment->Points.push_back(point);
completed_segment->Normals.push_back(cluster->Normals[std::distance(cluster->Points.begin(), std::find(cluster->Points.begin(), cluster->Points.end(), point))]);
completed_segment->Colors.push_back(cluster->Colors[std::distance(cluster->Points.begin(), std::find(cluster->Points.begin(), cluster->Points.end(), point))]);
}
}
else
{
completed_segment->Points.push_back(point);
completed_segment->Normals.push_back(cluster->Normals[std::distance(cluster->Points.begin(), std::find(cluster->Points.begin(), cluster->Points.end(), point))]);
completed_segment->Colors.push_back(cluster->Colors[std::distance(cluster->Points.begin(), std::find(cluster->Points.begin(), cluster->Points.end(), point))]);
}
}
}
std::vector<int> indicesToRemove;
for (int i = 0; i < cluster->Points.size(); ++i)
{
if (std::find(completed_segment->Points.begin(), completed_segment->Points.end(), cluster->Points[i]) != completed_segment->Points.end())
{
indicesToRemove.push_back(i);
}
}
for (auto it = indicesToRemove.rbegin(); it != indicesToRemove.rend(); ++it)
{
std::swap(cluster->Points[*it], cluster->Points.back());
cluster->Points.pop_back();
std::swap(cluster->Normals[*it], cluster->Normals.back());
cluster->Normals.pop_back();
std::swap(cluster->Colors[*it], cluster->Colors.back());
cluster->Colors.pop_back();
}
}
}
};
} // namespace diffCheck::segmentation