Point Cloud Library (PCL)  1.9.1-dev
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) const
70 {
71  // Need 3 samples
72  if (samples.size () != 3)
73  {
74  PCL_ERROR ("[pcl::SampleConsensusModelCircle2D::computeModelCoefficients] Invalid set of samples given (%lu)!\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) const
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 circle
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] = std::abs (std::sqrt (
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 circle
145  for (size_t i = 0; i < indices_->size (); ++i)
146  {
147  // Calculate the distance from the point to the circle as the difference between
148  // dist(point,circle_origin) and circle_radius
149  float distance = std::abs (std::sqrt (
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) const
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 circle
179  for (size_t i = 0; i < indices_->size (); ++i)
180  {
181  // Calculate the distance from the point to the circle as the difference between
182  // dist(point,circle_origin) and circle_radius
183  float distance = std::abs (std::sqrt (
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) const
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 (%lu)!\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 (%lu)! Returning the same coefficients.\n", inliers.size ());
214  return;
215  }
216 
217  OptimizationFunctor functor (this, inliers);
218  Eigen::NumericalDiff<OptimizationFunctor> num_diff (functor);
219  Eigen::LevenbergMarquardt<Eigen::NumericalDiff<OptimizationFunctor>, float> lm (num_diff);
220  int info = lm.minimize (optimized_coefficients);
221 
222  // Compute the L2 norm of the residuals
223  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",
224  info, lm.fvec.norm (), model_coefficients[0], model_coefficients[1], model_coefficients[2], optimized_coefficients[0], optimized_coefficients[1], optimized_coefficients[2]);
225 }
226 
227 //////////////////////////////////////////////////////////////////////////
228 template <typename PointT> void
230  const std::vector<int> &inliers, const Eigen::VectorXf &model_coefficients,
231  PointCloud &projected_points, bool copy_data_fields) const
232 {
233  // Needs a valid set of model coefficients
234  if (model_coefficients.size () != 3)
235  {
236  PCL_ERROR ("[pcl::SampleConsensusModelCircle2D::projectPoints] Invalid number of model coefficients given (%lu)!\n", model_coefficients.size ());
237  return;
238  }
239 
240  projected_points.header = input_->header;
241  projected_points.is_dense = input_->is_dense;
242 
243  // Copy all the data fields from the input cloud to the projected one?
244  if (copy_data_fields)
245  {
246  // Allocate enough space and copy the basics
247  projected_points.points.resize (input_->points.size ());
248  projected_points.width = input_->width;
249  projected_points.height = input_->height;
250 
251  using FieldList = typename pcl::traits::fieldList<PointT>::type;
252  // Iterate over each point
253  for (size_t i = 0; i < projected_points.points.size (); ++i)
254  // Iterate over each dimension
255  pcl::for_each_type <FieldList> (NdConcatenateFunctor <PointT, PointT> (input_->points[i], projected_points.points[i]));
256 
257  // Iterate through the points and project them to the circle
258  for (const int &inlier : inliers)
259  {
260  float dx = input_->points[inlier].x - model_coefficients[0];
261  float dy = input_->points[inlier].y - model_coefficients[1];
262  float a = std::sqrt ( (model_coefficients[2] * model_coefficients[2]) / (dx * dx + dy * dy) );
263 
264  projected_points.points[inlier].x = a * dx + model_coefficients[0];
265  projected_points.points[inlier].y = a * dy + model_coefficients[1];
266  }
267  }
268  else
269  {
270  // Allocate enough space and copy the basics
271  projected_points.points.resize (inliers.size ());
272  projected_points.width = static_cast<uint32_t> (inliers.size ());
273  projected_points.height = 1;
274 
275  using FieldList = typename pcl::traits::fieldList<PointT>::type;
276  // Iterate over each point
277  for (size_t i = 0; i < inliers.size (); ++i)
278  // Iterate over each dimension
279  pcl::for_each_type <FieldList> (NdConcatenateFunctor <PointT, PointT> (input_->points[inliers[i]], projected_points.points[i]));
280 
281  // Iterate through the points and project them to the circle
282  for (size_t i = 0; i < inliers.size (); ++i)
283  {
284  float dx = input_->points[inliers[i]].x - model_coefficients[0];
285  float dy = input_->points[inliers[i]].y - model_coefficients[1];
286  float a = std::sqrt ( (model_coefficients[2] * model_coefficients[2]) / (dx * dx + dy * dy) );
287 
288  projected_points.points[i].x = a * dx + model_coefficients[0];
289  projected_points.points[i].y = a * dy + model_coefficients[1];
290  }
291  }
292 }
293 
294 //////////////////////////////////////////////////////////////////////////
295 template <typename PointT> bool
297  const std::set<int> &indices, const Eigen::VectorXf &model_coefficients, const double threshold) const
298 {
299  // Needs a valid model coefficients
300  if (model_coefficients.size () != 3)
301  {
302  PCL_ERROR ("[pcl::SampleConsensusModelCircle2D::doSamplesVerifyModel] Invalid number of model coefficients given (%lu)!\n", model_coefficients.size ());
303  return (false);
304  }
305 
306  for (const int &index : indices)
307  // Calculate the distance from the point to the circle as the difference between
308  //dist(point,circle_origin) and circle_radius
309  if (std::abs (std::sqrt (
310  ( input_->points[index].x - model_coefficients[0] ) *
311  ( input_->points[index].x - model_coefficients[0] ) +
312  ( input_->points[index].y - model_coefficients[1] ) *
313  ( input_->points[index].y - model_coefficients[1] )
314  ) - model_coefficients[2]) > threshold)
315  return (false);
316 
317  return (true);
318 }
319 
320 //////////////////////////////////////////////////////////////////////////
321 template <typename PointT> bool
322 pcl::SampleConsensusModelCircle2D<PointT>::isModelValid (const Eigen::VectorXf &model_coefficients) const
323 {
324  if (!SampleConsensusModel<PointT>::isModelValid (model_coefficients))
325  return (false);
326 
327  if (radius_min_ != -std::numeric_limits<double>::max() && model_coefficients[2] < radius_min_)
328  return (false);
329  if (radius_max_ != std::numeric_limits<double>::max() && model_coefficients[2] > radius_max_)
330  return (false);
331 
332  return (true);
333 }
334 
335 #define PCL_INSTANTIATE_SampleConsensusModelCircle2D(T) template class PCL_EXPORTS pcl::SampleConsensusModelCircle2D<T>;
336 
337 #endif // PCL_SAMPLE_CONSENSUS_IMPL_SAC_MODEL_CIRCLE_H_
338 
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 2d circle model coefficients.
bool isModelValid(const Eigen::VectorXf &model_coefficients) const override
Check whether a model is valid given the user constraints.
std::vector< PointT, Eigen::aligned_allocator< PointT > > points
The point data.
Definition: point_cloud.h:423
bool isSampleGood(const std::vector< int > &samples) const override
Check if a sample of indices results in a good sample of points indices.
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 2D circle model.
uint32_t height
The point cloud height (if organized as an image-structure).
Definition: point_cloud.h:428
uint32_t width
The point cloud width (if organized as an image-structure).
Definition: point_cloud.h:426
SampleConsensusModel represents the base model class.
Definition: sac_model.h:67
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 2d circle model.
float distance(const PointT &p1, const PointT &p2)
Definition: geometry.h:60
void optimizeModelCoefficients(const std::vector< int > &inliers, const Eigen::VectorXf &model_coefficients, Eigen::VectorXf &optimized_coefficients) const override
Recompute the 2d circle coefficients using the given inlier set and return them to the user...
pcl::PCLHeader header
The point cloud header.
Definition: point_cloud.h:420
void getDistancesToModel(const Eigen::VectorXf &model_coefficients, std::vector< double > &distances) const override
Compute all distances from the cloud data to a given 2D circle model.
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 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 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:431
Helper functor structure for concatenate.
Definition: concatenate.h:51