Point Cloud Library (PCL)  1.9.1-dev
sac_model_circle3d.hpp
1 /*
2  * Software License Agreement (BSD License)
3  *
4  * Point Cloud Library (PCL) - www.pointclouds.org
5  * Copyright (c) 2012-, Open Perception, Inc.
6  *
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *
13  * * Redistributions of source code must retain the above copyright
14  * notice, this list of conditions and the following disclaimer.
15  * * Redistributions in binary form must reproduce the above
16  * copyright notice, this list of conditions and the following
17  * disclaimer in the documentation and/or other materials provided
18  * with the distribution.
19  * * Neither the name of the copyright holder(s) nor the names of its
20  * contributors may be used to endorse or promote products derived
21  * from this software without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27  * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
31  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
33  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34  * POSSIBILITY OF SUCH DAMAGE.
35  *
36  *
37  */
38 
39 #ifndef PCL_SAMPLE_CONSENSUS_IMPL_SAC_MODEL_CIRCLE_3D_HPP_
40 #define PCL_SAMPLE_CONSENSUS_IMPL_SAC_MODEL_CIRCLE_3D_HPP_
41 
42 #include <pcl/sample_consensus/eigen.h>
43 #include <pcl/sample_consensus/sac_model_circle3d.h>
44 #include <pcl/common/concatenate.h>
45 
46 //////////////////////////////////////////////////////////////////////////
47 template <typename PointT> bool
49  const std::vector<int> &samples) const
50 {
51  // Get the values at the three points
52  Eigen::Vector3d p0 (input_->points[samples[0]].x, input_->points[samples[0]].y, input_->points[samples[0]].z);
53  Eigen::Vector3d p1 (input_->points[samples[1]].x, input_->points[samples[1]].y, input_->points[samples[1]].z);
54  Eigen::Vector3d p2 (input_->points[samples[2]].x, input_->points[samples[2]].y, input_->points[samples[2]].z);
55 
56  // calculate vectors between points
57  p1 -= p0;
58  p2 -= p0;
59 
60  return (p1.dot (p2) < 0.000001);
61 }
62 
63 //////////////////////////////////////////////////////////////////////////
64 template <typename PointT> bool
65 pcl::SampleConsensusModelCircle3D<PointT>::computeModelCoefficients (const std::vector<int> &samples, Eigen::VectorXf &model_coefficients) const
66 {
67  // Need 3 samples
68  if (samples.size () != 3)
69  {
70  PCL_ERROR ("[pcl::SampleConsensusModelCircle3D::computeModelCoefficients] Invalid set of samples given (%lu)!\n", samples.size ());
71  return (false);
72  }
73 
74  model_coefficients.resize (7); //needing 7 coefficients: centerX, centerY, centerZ, radius, normalX, normalY, normalZ
75 
76  Eigen::Vector3d p0 (input_->points[samples[0]].x, input_->points[samples[0]].y, input_->points[samples[0]].z);
77  Eigen::Vector3d p1 (input_->points[samples[1]].x, input_->points[samples[1]].y, input_->points[samples[1]].z);
78  Eigen::Vector3d p2 (input_->points[samples[2]].x, input_->points[samples[2]].y, input_->points[samples[2]].z);
79 
80 
81  Eigen::Vector3d helper_vec01 = p0 - p1;
82  Eigen::Vector3d helper_vec02 = p0 - p2;
83  Eigen::Vector3d helper_vec10 = p1 - p0;
84  Eigen::Vector3d helper_vec12 = p1 - p2;
85  Eigen::Vector3d helper_vec20 = p2 - p0;
86  Eigen::Vector3d helper_vec21 = p2 - p1;
87 
88  Eigen::Vector3d common_helper_vec = helper_vec01.cross (helper_vec12);
89 
90  double commonDividend = 2.0 * common_helper_vec.squaredNorm ();
91 
92  double alpha = (helper_vec12.squaredNorm () * helper_vec01.dot (helper_vec02)) / commonDividend;
93  double beta = (helper_vec02.squaredNorm () * helper_vec10.dot (helper_vec12)) / commonDividend;
94  double gamma = (helper_vec01.squaredNorm () * helper_vec20.dot (helper_vec21)) / commonDividend;
95 
96  Eigen::Vector3d circle_center = alpha * p0 + beta * p1 + gamma * p2;
97 
98  Eigen::Vector3d circle_radiusVector = circle_center - p0;
99  double circle_radius = circle_radiusVector.norm ();
100  Eigen::Vector3d circle_normal = common_helper_vec.normalized ();
101 
102  model_coefficients[0] = static_cast<float> (circle_center[0]);
103  model_coefficients[1] = static_cast<float> (circle_center[1]);
104  model_coefficients[2] = static_cast<float> (circle_center[2]);
105  model_coefficients[3] = static_cast<float> (circle_radius);
106  model_coefficients[4] = static_cast<float> (circle_normal[0]);
107  model_coefficients[5] = static_cast<float> (circle_normal[1]);
108  model_coefficients[6] = static_cast<float> (circle_normal[2]);
109 
110  return (true);
111 }
112 
113 //////////////////////////////////////////////////////////////////////////
114 template <typename PointT> void
115 pcl::SampleConsensusModelCircle3D<PointT>::getDistancesToModel (const Eigen::VectorXf &model_coefficients, std::vector<double> &distances) const
116 {
117  // Check if the model is valid given the user constraints
118  if (!isModelValid (model_coefficients))
119  {
120  distances.clear ();
121  return;
122  }
123  distances.resize (indices_->size ());
124 
125  // Iterate through the 3d points and calculate the distances from them to the sphere
126  for (std::size_t i = 0; i < indices_->size (); ++i)
127  // Calculate the distance from the point to the circle:
128  // 1. calculate intersection point of the plane in which the circle lies and the
129  // line from the sample point with the direction of the plane normal (projected point)
130  // 2. calculate the intersection point of the line from the circle center to the projected point
131  // with the circle
132  // 3. calculate distance from corresponding point on the circle to the sample point
133  {
134  // what i have:
135  // P : Sample Point
136  Eigen::Vector3d P (input_->points[(*indices_)[i]].x, input_->points[(*indices_)[i]].y, input_->points[(*indices_)[i]].z);
137  // C : Circle Center
138  Eigen::Vector3d C (model_coefficients[0], model_coefficients[1], model_coefficients[2]);
139  // N : Circle (Plane) Normal
140  Eigen::Vector3d N (model_coefficients[4], model_coefficients[5], model_coefficients[6]);
141  // r : Radius
142  double r = model_coefficients[3];
143 
144  Eigen::Vector3d helper_vectorPC = P - C;
145  // 1.1. get line parameter
146  double lambda = (helper_vectorPC.dot (N)) / N.squaredNorm ();
147 
148  // Projected Point on plane
149  Eigen::Vector3d P_proj = P + lambda * N;
150  Eigen::Vector3d helper_vectorP_projC = P_proj - C;
151 
152  // K : Point on Circle
153  Eigen::Vector3d K = C + r * helper_vectorP_projC.normalized ();
154  Eigen::Vector3d distanceVector = P - K;
155 
156  distances[i] = distanceVector.norm ();
157  }
158 }
159 
160 //////////////////////////////////////////////////////////////////////////
161 template <typename PointT> void
163  const Eigen::VectorXf &model_coefficients, const double threshold,
164  std::vector<int> &inliers)
165 {
166  // Check if the model is valid given the user constraints
167  if (!isModelValid (model_coefficients))
168  {
169  inliers.clear ();
170  return;
171  }
172  int nr_p = 0;
173  inliers.resize (indices_->size ());
174 
175  // Iterate through the 3d points and calculate the distances from them to the sphere
176  for (std::size_t i = 0; i < indices_->size (); ++i)
177  {
178  // what i have:
179  // P : Sample Point
180  Eigen::Vector3d P (input_->points[(*indices_)[i]].x, input_->points[(*indices_)[i]].y, input_->points[(*indices_)[i]].z);
181  // C : Circle Center
182  Eigen::Vector3d C (model_coefficients[0], model_coefficients[1], model_coefficients[2]);
183  // N : Circle (Plane) Normal
184  Eigen::Vector3d N (model_coefficients[4], model_coefficients[5], model_coefficients[6]);
185  // r : Radius
186  double r = model_coefficients[3];
187 
188  Eigen::Vector3d helper_vectorPC = P - C;
189  // 1.1. get line parameter
190  double lambda = (-(helper_vectorPC.dot (N))) / N.dot (N);
191  // Projected Point on plane
192  Eigen::Vector3d P_proj = P + lambda * N;
193  Eigen::Vector3d helper_vectorP_projC = P_proj - C;
194 
195  // K : Point on Circle
196  Eigen::Vector3d K = C + r * helper_vectorP_projC.normalized ();
197  Eigen::Vector3d distanceVector = P - K;
198 
199  if (distanceVector.norm () < threshold)
200  {
201  // Returns the indices of the points whose distances are smaller than the threshold
202  inliers[nr_p] = (*indices_)[i];
203  nr_p++;
204  }
205  }
206  inliers.resize (nr_p);
207 }
208 
209 //////////////////////////////////////////////////////////////////////////
210 template <typename PointT> int
212  const Eigen::VectorXf &model_coefficients, const double threshold) const
213 {
214  // Check if the model is valid given the user constraints
215  if (!isModelValid (model_coefficients))
216  return (0);
217  int nr_p = 0;
218 
219  // Iterate through the 3d points and calculate the distances from them to the sphere
220  for (std::size_t i = 0; i < indices_->size (); ++i)
221  {
222  // what i have:
223  // P : Sample Point
224  Eigen::Vector3d P (input_->points[(*indices_)[i]].x, input_->points[(*indices_)[i]].y, input_->points[(*indices_)[i]].z);
225  // C : Circle Center
226  Eigen::Vector3d C (model_coefficients[0], model_coefficients[1], model_coefficients[2]);
227  // N : Circle (Plane) Normal
228  Eigen::Vector3d N (model_coefficients[4], model_coefficients[5], model_coefficients[6]);
229  // r : Radius
230  double r = model_coefficients[3];
231 
232  Eigen::Vector3d helper_vectorPC = P - C;
233  // 1.1. get line parameter
234  double lambda = (-(helper_vectorPC.dot (N))) / N.dot (N);
235 
236  // Projected Point on plane
237  Eigen::Vector3d P_proj = P + lambda * N;
238  Eigen::Vector3d helper_vectorP_projC = P_proj - C;
239 
240  // K : Point on Circle
241  Eigen::Vector3d K = C + r * helper_vectorP_projC.normalized ();
242  Eigen::Vector3d distanceVector = P - K;
243 
244  if (distanceVector.norm () < threshold)
245  nr_p++;
246  }
247  return (nr_p);
248 }
249 
250 //////////////////////////////////////////////////////////////////////////
251 template <typename PointT> void
253  const std::vector<int> &inliers,
254  const Eigen::VectorXf &model_coefficients,
255  Eigen::VectorXf &optimized_coefficients) const
256 {
257  optimized_coefficients = model_coefficients;
258 
259  // Needs a set of valid model coefficients
260  if (model_coefficients.size () != 7)
261  {
262  PCL_ERROR ("[pcl::SampleConsensusModelCircle3D::optimizeModelCoefficients] Invalid number of model coefficients given (%lu)!\n", model_coefficients.size ());
263  return;
264  }
265 
266  // Need at least 3 samples
267  if (inliers.size () <= 3)
268  {
269  PCL_ERROR ("[pcl::SampleConsensusModelCircle3D::optimizeModelCoefficients] Not enough inliers found to support a model (%lu)! Returning the same coefficients.\n", inliers.size ());
270  return;
271  }
272 
273  OptimizationFunctor functor (this, inliers);
274  Eigen::NumericalDiff<OptimizationFunctor> num_diff (functor);
275  Eigen::LevenbergMarquardt<Eigen::NumericalDiff<OptimizationFunctor>, double> lm (num_diff);
276  Eigen::VectorXd coeff;
277  int info = lm.minimize (coeff);
278  for (Eigen::Index i = 0; i < coeff.size (); ++i)
279  optimized_coefficients[i] = static_cast<float> (coeff[i]);
280 
281  // Compute the L2 norm of the residuals
282  PCL_DEBUG ("[pcl::SampleConsensusModelCircle3D::optimizeModelCoefficients] LM solver finished with exit code %i, having a residual norm of %g. \nInitial solution: %g %g %g %g %g %g %g \nFinal solution: %g %g %g %g %g %g %g\n",
283  info, lm.fvec.norm (), model_coefficients[0], model_coefficients[1], model_coefficients[2], model_coefficients[3], model_coefficients[4], model_coefficients[5], model_coefficients[6], optimized_coefficients[0], optimized_coefficients[1], optimized_coefficients[2], optimized_coefficients[3], optimized_coefficients[4], optimized_coefficients[5], optimized_coefficients[6]);
284 }
285 
286 //////////////////////////////////////////////////////////////////////////
287 template <typename PointT> void
289  const std::vector<int> &inliers, const Eigen::VectorXf &model_coefficients,
290  PointCloud &projected_points, bool copy_data_fields) const
291 {
292  // Needs a valid set of model coefficients
293  if (model_coefficients.size () != 7)
294  {
295  PCL_ERROR ("[pcl::SampleConsensusModelCircle3D::projectPoints] Invalid number of model coefficients given (%lu)!\n", model_coefficients.size ());
296  return;
297  }
298 
299  projected_points.header = input_->header;
300  projected_points.is_dense = input_->is_dense;
301 
302  // Copy all the data fields from the input cloud to the projected one?
303  if (copy_data_fields)
304  {
305  // Allocate enough space and copy the basics
306  projected_points.points.resize (input_->points.size ());
307  projected_points.width = input_->width;
308  projected_points.height = input_->height;
309 
310  using FieldList = typename pcl::traits::fieldList<PointT>::type;
311  // Iterate over each point
312  for (std::size_t i = 0; i < projected_points.points.size (); ++i)
313  // Iterate over each dimension
314  pcl::for_each_type <FieldList> (NdConcatenateFunctor <PointT, PointT> (input_->points[i], projected_points.points[i]));
315 
316  // Iterate through the 3d points and calculate the distances from them to the plane
317  for (std::size_t i = 0; i < inliers.size (); ++i)
318  {
319  // what i have:
320  // P : Sample Point
321  Eigen::Vector3d P (input_->points[inliers[i]].x, input_->points[inliers[i]].y, input_->points[inliers[i]].z);
322  // C : Circle Center
323  Eigen::Vector3d C (model_coefficients[0], model_coefficients[1], model_coefficients[2]);
324  // N : Circle (Plane) Normal
325  Eigen::Vector3d N (model_coefficients[4], model_coefficients[5], model_coefficients[6]);
326  // r : Radius
327  double r = model_coefficients[3];
328 
329  Eigen::Vector3d helper_vectorPC = P - C;
330  // 1.1. get line parameter
331  //float lambda = (helper_vectorPC.dot(N)) / N.squaredNorm() ;
332  double lambda = (-(helper_vectorPC.dot (N))) / N.dot (N);
333  // Projected Point on plane
334  Eigen::Vector3d P_proj = P + lambda * N;
335  Eigen::Vector3d helper_vectorP_projC = P_proj - C;
336 
337  // K : Point on Circle
338  Eigen::Vector3d K = C + r * helper_vectorP_projC.normalized ();
339 
340  projected_points.points[i].x = static_cast<float> (K[0]);
341  projected_points.points[i].y = static_cast<float> (K[1]);
342  projected_points.points[i].z = static_cast<float> (K[2]);
343  }
344  }
345  else
346  {
347  // Allocate enough space and copy the basics
348  projected_points.points.resize (inliers.size ());
349  projected_points.width = std::uint32_t (inliers.size ());
350  projected_points.height = 1;
351 
352  using FieldList = typename pcl::traits::fieldList<PointT>::type;
353  // Iterate over each point
354  for (std::size_t i = 0; i < inliers.size (); ++i)
355  // Iterate over each dimension
356  pcl::for_each_type <FieldList> (NdConcatenateFunctor <PointT, PointT> (input_->points[inliers[i]], projected_points.points[i]));
357 
358  // Iterate through the 3d points and calculate the distances from them to the plane
359  for (std::size_t i = 0; i < inliers.size (); ++i)
360  {
361  // what i have:
362  // P : Sample Point
363  Eigen::Vector3d P (input_->points[inliers[i]].x, input_->points[inliers[i]].y, input_->points[inliers[i]].z);
364  // C : Circle Center
365  Eigen::Vector3d C (model_coefficients[0], model_coefficients[1], model_coefficients[2]);
366  // N : Circle (Plane) Normal
367  Eigen::Vector3d N (model_coefficients[4], model_coefficients[5], model_coefficients[6]);
368  // r : Radius
369  double r = model_coefficients[3];
370 
371  Eigen::Vector3d helper_vectorPC = P - C;
372  // 1.1. get line parameter
373  double lambda = (-(helper_vectorPC.dot (N))) / N.dot (N);
374  // Projected Point on plane
375  Eigen::Vector3d P_proj = P + lambda * N;
376  Eigen::Vector3d helper_vectorP_projC = P_proj - C;
377 
378  // K : Point on Circle
379  Eigen::Vector3d K = C + r * helper_vectorP_projC.normalized ();
380 
381  projected_points.points[i].x = static_cast<float> (K[0]);
382  projected_points.points[i].y = static_cast<float> (K[1]);
383  projected_points.points[i].z = static_cast<float> (K[2]);
384  }
385  }
386 }
387 
388 //////////////////////////////////////////////////////////////////////////
389 template <typename PointT> bool
391  const std::set<int> &indices,
392  const Eigen::VectorXf &model_coefficients,
393  const double threshold) const
394 {
395  // Needs a valid model coefficients
396  if (model_coefficients.size () != 7)
397  {
398  PCL_ERROR ("[pcl::SampleConsensusModelCircle3D::doSamplesVerifyModel] Invalid number of model coefficients given (%lu)!\n", model_coefficients.size ());
399  return (false);
400  }
401 
402  for (const int &index : indices)
403  {
404  // Calculate the distance from the point to the sphere as the difference between
405  //dist(point,sphere_origin) and sphere_radius
406 
407  // what i have:
408  // P : Sample Point
409  Eigen::Vector3d P (input_->points[index].x, input_->points[index].y, input_->points[index].z);
410  // C : Circle Center
411  Eigen::Vector3d C (model_coefficients[0], model_coefficients[1], model_coefficients[2]);
412  // N : Circle (Plane) Normal
413  Eigen::Vector3d N (model_coefficients[4], model_coefficients[5], model_coefficients[6]);
414  // r : Radius
415  double r = model_coefficients[3];
416  Eigen::Vector3d helper_vectorPC = P - C;
417  // 1.1. get line parameter
418  double lambda = (-(helper_vectorPC.dot (N))) / N.dot (N);
419  // Projected Point on plane
420  Eigen::Vector3d P_proj = P + lambda * N;
421  Eigen::Vector3d helper_vectorP_projC = P_proj - C;
422 
423  // K : Point on Circle
424  Eigen::Vector3d K = C + r * helper_vectorP_projC.normalized ();
425  Eigen::Vector3d distanceVector = P - K;
426 
427  if (distanceVector.norm () > threshold)
428  return (false);
429  }
430  return (true);
431 }
432 
433 //////////////////////////////////////////////////////////////////////////
434 template <typename PointT> bool
435 pcl::SampleConsensusModelCircle3D<PointT>::isModelValid (const Eigen::VectorXf &model_coefficients) const
436 {
437  if (!SampleConsensusModel<PointT>::isModelValid (model_coefficients))
438  return (false);
439 
440  if (radius_min_ != -DBL_MAX && model_coefficients[3] < radius_min_)
441  return (false);
442  if (radius_max_ != DBL_MAX && model_coefficients[3] > radius_max_)
443  return (false);
444 
445  return (true);
446 }
447 
448 #define PCL_INSTANTIATE_SampleConsensusModelCircle3D(T) template class PCL_EXPORTS pcl::SampleConsensusModelCircle3D<T>;
449 
450 #endif // PCL_SAMPLE_CONSENSUS_IMPL_SAC_MODEL_CIRCLE3D_HPP_
451 
void projectPoints(const std::vector< int > &inliers, const Eigen::VectorXf &model_coefficients, PointCloud &projected_points, bool copy_data_fields=true) const override
Create a new point cloud with inliers projected onto the 3d circle model.
void selectWithinDistance(const Eigen::VectorXf &model_coefficients, const double threshold, std::vector< int > &inliers) override
Compute all distances from the cloud data to a given 3D circle model.
std::vector< PointT, Eigen::aligned_allocator< PointT > > points
The point data.
Definition: point_cloud.h:394
int countWithinDistance(const Eigen::VectorXf &model_coefficients, const double threshold) const override
Count all the points which respect the given model coefficients as inliers.
bool isModelValid(const Eigen::VectorXf &model_coefficients) const override
Check whether a model is valid given the user constraints.
bool computeModelCoefficients(const std::vector< int > &samples, Eigen::VectorXf &model_coefficients) const override
Check whether the given index samples can form a valid 2D circle model, compute the model coefficient...
bool isSampleGood(const std::vector< int > &samples) const override
Check if a sample of indices results in a good sample of points indices.
std::uint32_t width
The point cloud width (if organized as an image-structure).
Definition: point_cloud.h:397
SampleConsensusModel represents the base model class.
Definition: sac_model.h:67
std::uint32_t height
The point cloud height (if organized as an image-structure).
Definition: point_cloud.h:399
pcl::PCLHeader header
The point cloud header.
Definition: point_cloud.h:391
void getDistancesToModel(const Eigen::VectorXf &model_coefficients, std::vector< double > &distances) const override
Compute all distances from the cloud data to a given 3D circle model.
Definition: norms.h:54
bool doSamplesVerifyModel(const std::set< int > &indices, const Eigen::VectorXf &model_coefficients, const double threshold) const override
Verify whether a subset of indices verifies the given 3d circle model coefficients.
bool is_dense
True if no points are invalid (e.g., have NaN or Inf values in any of their floating point fields)...
Definition: point_cloud.h:402
void optimizeModelCoefficients(const std::vector< int > &inliers, const Eigen::VectorXf &model_coefficients, Eigen::VectorXf &optimized_coefficients) const override
Recompute the 3d circle coefficients using the given inlier set and return them to the user...
Helper functor structure for concatenate.
Definition: concatenate.h:51