Point Cloud Library (PCL)  1.7.0
sac_model_circle.hpp
1 /*
2  * Software License Agreement (BSD License)
3  *
4  * Point Cloud Library (PCL) - www.pointclouds.org
5  * Copyright (c) 2009, Willow Garage, Inc.
6  * Copyright (c) 2012-, Open Perception, Inc.
7  *
8  * All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  *
14  * * Redistributions of source code must retain the above copyright
15  * notice, this list of conditions and the following disclaimer.
16  * * Redistributions in binary form must reproduce the above
17  * copyright notice, this list of conditions and the following
18  * disclaimer in the documentation and/or other materials provided
19  * with the distribution.
20  * * Neither the name of the copyright holder(s) nor the names of its
21  * contributors may be used to endorse or promote products derived
22  * from this software without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
27  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
28  * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
29  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
30  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
31  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
32  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
34  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35  * POSSIBILITY OF SUCH DAMAGE.
36  *
37  * $Id$
38  *
39  */
40 
41 #ifndef PCL_SAMPLE_CONSENSUS_IMPL_SAC_MODEL_CIRCLE_H_
42 #define PCL_SAMPLE_CONSENSUS_IMPL_SAC_MODEL_CIRCLE_H_
43 
44 #include <pcl/sample_consensus/eigen.h>
45 #include <pcl/sample_consensus/sac_model_circle.h>
46 #include <pcl/common/concatenate.h>
47 
48 //////////////////////////////////////////////////////////////////////////
49 template <typename PointT> bool
50 pcl::SampleConsensusModelCircle2D<PointT>::isSampleGood(const std::vector<int> &samples) const
51 {
52  // Get the values at the two points
53  Eigen::Array2d p0 (input_->points[samples[0]].x, input_->points[samples[0]].y);
54  Eigen::Array2d p1 (input_->points[samples[1]].x, input_->points[samples[1]].y);
55  Eigen::Array2d p2 (input_->points[samples[2]].x, input_->points[samples[2]].y);
56 
57  // Compute the segment values (in 2d) between p1 and p0
58  p1 -= p0;
59  // Compute the segment values (in 2d) between p2 and p0
60  p2 -= p0;
61 
62  Eigen::Array2d dy1dy2 = p1 / p2;
63 
64  return (dy1dy2[0] != dy1dy2[1]);
65 }
66 
67 //////////////////////////////////////////////////////////////////////////
68 template <typename PointT> bool
69 pcl::SampleConsensusModelCircle2D<PointT>::computeModelCoefficients (const std::vector<int> &samples, Eigen::VectorXf &model_coefficients)
70 {
71  // Need 3 samples
72  if (samples.size () != 3)
73  {
74  PCL_ERROR ("[pcl::SampleConsensusModelCircle2D::computeModelCoefficients] Invalid set of samples given (%zu)!\n", samples.size ());
75  return (false);
76  }
77 
78  model_coefficients.resize (3);
79 
80  Eigen::Vector2d p0 (input_->points[samples[0]].x, input_->points[samples[0]].y);
81  Eigen::Vector2d p1 (input_->points[samples[1]].x, input_->points[samples[1]].y);
82  Eigen::Vector2d p2 (input_->points[samples[2]].x, input_->points[samples[2]].y);
83 
84  Eigen::Vector2d u = (p0 + p1) / 2.0;
85  Eigen::Vector2d v = (p1 + p2) / 2.0;
86 
87  Eigen::Vector2d p1p0dif = p1 - p0;
88  Eigen::Vector2d p2p1dif = p2 - p1;
89  Eigen::Vector2d uvdif = u - v;
90 
91  Eigen::Vector2d m (- p1p0dif[0] / p1p0dif[1], - p2p1dif[0] / p2p1dif[1]);
92 
93  // Center (x, y)
94  model_coefficients[0] = static_cast<float> ((m[0] * u[0] - m[1] * v[0] - uvdif[1] ) / (m[0] - m[1]));
95  model_coefficients[1] = static_cast<float> ((m[0] * m[1] * uvdif[0] + m[0] * v[1] - m[1] * u[1]) / (m[0] - m[1]));
96 
97  // Radius
98  model_coefficients[2] = static_cast<float> (sqrt ((model_coefficients[0] - p0[0]) * (model_coefficients[0] - p0[0]) +
99  (model_coefficients[1] - p0[1]) * (model_coefficients[1] - p0[1])));
100  return (true);
101 }
102 
103 //////////////////////////////////////////////////////////////////////////
104 template <typename PointT> void
105 pcl::SampleConsensusModelCircle2D<PointT>::getDistancesToModel (const Eigen::VectorXf &model_coefficients, std::vector<double> &distances)
106 {
107  // Check if the model is valid given the user constraints
108  if (!isModelValid (model_coefficients))
109  {
110  distances.clear ();
111  return;
112  }
113  distances.resize (indices_->size ());
114 
115  // Iterate through the 3d points and calculate the distances from them to the sphere
116  for (size_t i = 0; i < indices_->size (); ++i)
117  // Calculate the distance from the point to the circle as the difference between
118  // dist(point,circle_origin) and circle_radius
119  distances[i] = fabsf (sqrtf (
120  ( input_->points[(*indices_)[i]].x - model_coefficients[0] ) *
121  ( input_->points[(*indices_)[i]].x - model_coefficients[0] ) +
122 
123  ( input_->points[(*indices_)[i]].y - model_coefficients[1] ) *
124  ( input_->points[(*indices_)[i]].y - model_coefficients[1] )
125  ) - model_coefficients[2]);
126 }
127 
128 //////////////////////////////////////////////////////////////////////////
129 template <typename PointT> void
131  const Eigen::VectorXf &model_coefficients, const double threshold,
132  std::vector<int> &inliers)
133 {
134  // Check if the model is valid given the user constraints
135  if (!isModelValid (model_coefficients))
136  {
137  inliers.clear ();
138  return;
139  }
140  int nr_p = 0;
141  inliers.resize (indices_->size ());
142  error_sqr_dists_.resize (indices_->size ());
143 
144  // Iterate through the 3d points and calculate the distances from them to the sphere
145  for (size_t i = 0; i < indices_->size (); ++i)
146  {
147  // Calculate the distance from the point to the sphere as the difference between
148  // dist(point,sphere_origin) and sphere_radius
149  float distance = fabsf (sqrtf (
150  ( input_->points[(*indices_)[i]].x - model_coefficients[0] ) *
151  ( input_->points[(*indices_)[i]].x - model_coefficients[0] ) +
152 
153  ( input_->points[(*indices_)[i]].y - model_coefficients[1] ) *
154  ( input_->points[(*indices_)[i]].y - model_coefficients[1] )
155  ) - model_coefficients[2]);
156  if (distance < threshold)
157  {
158  // Returns the indices of the points whose distances are smaller than the threshold
159  inliers[nr_p] = (*indices_)[i];
160  error_sqr_dists_[nr_p] = static_cast<double> (distance);
161  ++nr_p;
162  }
163  }
164  inliers.resize (nr_p);
165  error_sqr_dists_.resize (nr_p);
166 }
167 
168 //////////////////////////////////////////////////////////////////////////
169 template <typename PointT> int
171  const Eigen::VectorXf &model_coefficients, const double threshold)
172 {
173  // Check if the model is valid given the user constraints
174  if (!isModelValid (model_coefficients))
175  return (0);
176  int nr_p = 0;
177 
178  // Iterate through the 3d points and calculate the distances from them to the sphere
179  for (size_t i = 0; i < indices_->size (); ++i)
180  {
181  // Calculate the distance from the point to the sphere as the difference between
182  // dist(point,sphere_origin) and sphere_radius
183  float distance = fabsf (sqrtf (
184  ( input_->points[(*indices_)[i]].x - model_coefficients[0] ) *
185  ( input_->points[(*indices_)[i]].x - model_coefficients[0] ) +
186 
187  ( input_->points[(*indices_)[i]].y - model_coefficients[1] ) *
188  ( input_->points[(*indices_)[i]].y - model_coefficients[1] )
189  ) - model_coefficients[2]);
190  if (distance < threshold)
191  nr_p++;
192  }
193  return (nr_p);
194 }
195 
196 //////////////////////////////////////////////////////////////////////////
197 template <typename PointT> void
199  const std::vector<int> &inliers, const Eigen::VectorXf &model_coefficients, Eigen::VectorXf &optimized_coefficients)
200 {
201  optimized_coefficients = model_coefficients;
202 
203  // Needs a set of valid model coefficients
204  if (model_coefficients.size () != 3)
205  {
206  PCL_ERROR ("[pcl::SampleConsensusModelCircle2D::optimizeModelCoefficients] Invalid number of model coefficients given (%zu)!\n", model_coefficients.size ());
207  return;
208  }
209 
210  // Need at least 3 samples
211  if (inliers.size () <= 3)
212  {
213  PCL_ERROR ("[pcl::SampleConsensusModelCircle2D::optimizeModelCoefficients] Not enough inliers found to support a model (%zu)! Returning the same coefficients.\n", inliers.size ());
214  return;
215  }
216 
217  tmp_inliers_ = &inliers;
218 
219  OptimizationFunctor functor (static_cast<int> (inliers.size ()), this);
220  Eigen::NumericalDiff<OptimizationFunctor> num_diff (functor);
221  Eigen::LevenbergMarquardt<Eigen::NumericalDiff<OptimizationFunctor>, float> lm (num_diff);
222  int info = lm.minimize (optimized_coefficients);
223 
224  // Compute the L2 norm of the residuals
225  PCL_DEBUG ("[pcl::SampleConsensusModelCircle2D::optimizeModelCoefficients] LM solver finished with exit code %i, having a residual norm of %g. \nInitial solution: %g %g %g \nFinal solution: %g %g %g\n",
226  info, lm.fvec.norm (), model_coefficients[0], model_coefficients[1], model_coefficients[2], optimized_coefficients[0], optimized_coefficients[1], optimized_coefficients[2]);
227 }
228 
229 //////////////////////////////////////////////////////////////////////////
230 template <typename PointT> void
232  const std::vector<int> &inliers, const Eigen::VectorXf &model_coefficients,
233  PointCloud &projected_points, bool copy_data_fields)
234 {
235  // Needs a valid set of model coefficients
236  if (model_coefficients.size () != 3)
237  {
238  PCL_ERROR ("[pcl::SampleConsensusModelCircle2D::projectPoints] Invalid number of model coefficients given (%zu)!\n", model_coefficients.size ());
239  return;
240  }
241 
242  projected_points.header = input_->header;
243  projected_points.is_dense = input_->is_dense;
244 
245  // Copy all the data fields from the input cloud to the projected one?
246  if (copy_data_fields)
247  {
248  // Allocate enough space and copy the basics
249  projected_points.points.resize (input_->points.size ());
250  projected_points.width = input_->width;
251  projected_points.height = input_->height;
252 
253  typedef typename pcl::traits::fieldList<PointT>::type FieldList;
254  // Iterate over each point
255  for (size_t i = 0; i < projected_points.points.size (); ++i)
256  // Iterate over each dimension
257  pcl::for_each_type <FieldList> (NdConcatenateFunctor <PointT, PointT> (input_->points[i], projected_points.points[i]));
258 
259  // Iterate through the 3d points and calculate the distances from them to the plane
260  for (size_t i = 0; i < inliers.size (); ++i)
261  {
262  float dx = input_->points[inliers[i]].x - model_coefficients[0];
263  float dy = input_->points[inliers[i]].y - model_coefficients[1];
264  float a = sqrtf ( (model_coefficients[2] * model_coefficients[2]) / (dx * dx + dy * dy) );
265 
266  projected_points.points[inliers[i]].x = a * dx + model_coefficients[0];
267  projected_points.points[inliers[i]].y = a * dy + model_coefficients[1];
268  }
269  }
270  else
271  {
272  // Allocate enough space and copy the basics
273  projected_points.points.resize (inliers.size ());
274  projected_points.width = static_cast<uint32_t> (inliers.size ());
275  projected_points.height = 1;
276 
277  typedef typename pcl::traits::fieldList<PointT>::type FieldList;
278  // Iterate over each point
279  for (size_t i = 0; i < inliers.size (); ++i)
280  // Iterate over each dimension
281  pcl::for_each_type <FieldList> (NdConcatenateFunctor <PointT, PointT> (input_->points[inliers[i]], projected_points.points[i]));
282 
283  // Iterate through the 3d points and calculate the distances from them to the plane
284  for (size_t i = 0; i < inliers.size (); ++i)
285  {
286  float dx = input_->points[inliers[i]].x - model_coefficients[0];
287  float dy = input_->points[inliers[i]].y - model_coefficients[1];
288  float a = sqrtf ( (model_coefficients[2] * model_coefficients[2]) / (dx * dx + dy * dy) );
289 
290  projected_points.points[i].x = a * dx + model_coefficients[0];
291  projected_points.points[i].y = a * dy + model_coefficients[1];
292  }
293  }
294 }
295 
296 //////////////////////////////////////////////////////////////////////////
297 template <typename PointT> bool
299  const std::set<int> &indices, const Eigen::VectorXf &model_coefficients, const double threshold)
300 {
301  // Needs a valid model coefficients
302  if (model_coefficients.size () != 3)
303  {
304  PCL_ERROR ("[pcl::SampleConsensusModelCircle2D::doSamplesVerifyModel] Invalid number of model coefficients given (%zu)!\n", model_coefficients.size ());
305  return (false);
306  }
307 
308  for (std::set<int>::const_iterator it = indices.begin (); it != indices.end (); ++it)
309  // Calculate the distance from the point to the sphere as the difference between
310  //dist(point,sphere_origin) and sphere_radius
311  if (fabsf (sqrtf (
312  ( input_->points[*it].x - model_coefficients[0] ) *
313  ( input_->points[*it].x - model_coefficients[0] ) +
314  ( input_->points[*it].y - model_coefficients[1] ) *
315  ( input_->points[*it].y - model_coefficients[1] )
316  ) - model_coefficients[2]) > threshold)
317  return (false);
318 
319  return (true);
320 }
321 
322 //////////////////////////////////////////////////////////////////////////
323 template <typename PointT> bool
324 pcl::SampleConsensusModelCircle2D<PointT>::isModelValid (const Eigen::VectorXf &model_coefficients)
325 {
326  // Needs a valid model coefficients
327  if (model_coefficients.size () != 3)
328  {
329  PCL_ERROR ("[pcl::SampleConsensusModelCircle2D::isModelValid] Invalid number of model coefficients given (%zu)!\n", model_coefficients.size ());
330  return (false);
331  }
332 
333  if (radius_min_ != -std::numeric_limits<double>::max() && model_coefficients[2] < radius_min_)
334  return (false);
335  if (radius_max_ != std::numeric_limits<double>::max() && model_coefficients[2] > radius_max_)
336  return (false);
337 
338  return (true);
339 }
340 
341 #define PCL_INSTANTIATE_SampleConsensusModelCircle2D(T) template class PCL_EXPORTS pcl::SampleConsensusModelCircle2D<T>;
342 
343 #endif // PCL_SAMPLE_CONSENSUS_IMPL_SAC_MODEL_CIRCLE_H_
344