Point Cloud Library (PCL)  1.11.0
 All Classes Namespaces Functions Variables Typedefs Enumerations Enumerator Friends Modules Pages
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
51 {
52  if (samples.size () != sample_size_)
53  {
54  PCL_ERROR ("[pcl::SampleConsensusModelCircle2D::isSampleGood] Wrong number of samples (is %lu, should be %lu)!\n", samples.size (), sample_size_);
55  return (false);
56  }
57  // Get the values at the two points
58  Eigen::Array2d p0 (input_->points[samples[0]].x, input_->points[samples[0]].y);
59  Eigen::Array2d p1 (input_->points[samples[1]].x, input_->points[samples[1]].y);
60  Eigen::Array2d p2 (input_->points[samples[2]].x, input_->points[samples[2]].y);
61 
62  // Compute the segment values (in 2d) between p1 and p0
63  p1 -= p0;
64  // Compute the segment values (in 2d) between p2 and p0
65  p2 -= p0;
66 
67  Eigen::Array2d dy1dy2 = p1 / p2;
68 
69  return (dy1dy2[0] != dy1dy2[1]);
70 }
71 
72 //////////////////////////////////////////////////////////////////////////
73 template <typename PointT> bool
74 pcl::SampleConsensusModelCircle2D<PointT>::computeModelCoefficients (const Indices &samples, Eigen::VectorXf &model_coefficients) const
75 {
76  // Need 3 samples
77  if (samples.size () != sample_size_)
78  {
79  PCL_ERROR ("[pcl::SampleConsensusModelCircle2D::computeModelCoefficients] Invalid set of samples given (%lu)!\n", samples.size ());
80  return (false);
81  }
82 
83  model_coefficients.resize (model_size_);
84 
85  Eigen::Vector2d p0 (input_->points[samples[0]].x, input_->points[samples[0]].y);
86  Eigen::Vector2d p1 (input_->points[samples[1]].x, input_->points[samples[1]].y);
87  Eigen::Vector2d p2 (input_->points[samples[2]].x, input_->points[samples[2]].y);
88 
89  Eigen::Vector2d u = (p0 + p1) / 2.0;
90  Eigen::Vector2d v = (p1 + p2) / 2.0;
91 
92  Eigen::Vector2d p1p0dif = p1 - p0;
93  Eigen::Vector2d p2p1dif = p2 - p1;
94  Eigen::Vector2d uvdif = u - v;
95 
96  Eigen::Vector2d m (- p1p0dif[0] / p1p0dif[1], - p2p1dif[0] / p2p1dif[1]);
97 
98  // Center (x, y)
99  model_coefficients[0] = static_cast<float> ((m[0] * u[0] - m[1] * v[0] - uvdif[1] ) / (m[0] - m[1]));
100  model_coefficients[1] = static_cast<float> ((m[0] * m[1] * uvdif[0] + m[0] * v[1] - m[1] * u[1]) / (m[0] - m[1]));
101 
102  // Radius
103  model_coefficients[2] = static_cast<float> (sqrt ((model_coefficients[0] - p0[0]) * (model_coefficients[0] - p0[0]) +
104  (model_coefficients[1] - p0[1]) * (model_coefficients[1] - p0[1])));
105  return (true);
106 }
107 
108 //////////////////////////////////////////////////////////////////////////
109 template <typename PointT> void
110 pcl::SampleConsensusModelCircle2D<PointT>::getDistancesToModel (const Eigen::VectorXf &model_coefficients, std::vector<double> &distances) const
111 {
112  // Check if the model is valid given the user constraints
113  if (!isModelValid (model_coefficients))
114  {
115  distances.clear ();
116  return;
117  }
118  distances.resize (indices_->size ());
119 
120  // Iterate through the 3d points and calculate the distances from them to the circle
121  for (std::size_t i = 0; i < indices_->size (); ++i)
122  // Calculate the distance from the point to the circle as the difference between
123  // dist(point,circle_origin) and circle_radius
124  distances[i] = std::abs (std::sqrt (
125  ( input_->points[(*indices_)[i]].x - model_coefficients[0] ) *
126  ( input_->points[(*indices_)[i]].x - model_coefficients[0] ) +
127 
128  ( input_->points[(*indices_)[i]].y - model_coefficients[1] ) *
129  ( input_->points[(*indices_)[i]].y - model_coefficients[1] )
130  ) - model_coefficients[2]);
131 }
132 
133 //////////////////////////////////////////////////////////////////////////
134 template <typename PointT> void
136  const Eigen::VectorXf &model_coefficients, const double threshold,
137  Indices &inliers)
138 {
139  // Check if the model is valid given the user constraints
140  if (!isModelValid (model_coefficients))
141  {
142  inliers.clear ();
143  return;
144  }
145  inliers.clear ();
146  error_sqr_dists_.clear ();
147  inliers.reserve (indices_->size ());
148  error_sqr_dists_.reserve (indices_->size ());
149 
150  // Iterate through the 3d points and calculate the distances from them to the circle
151  for (std::size_t i = 0; i < indices_->size (); ++i)
152  {
153  // Calculate the distance from the point to the circle as the difference between
154  // dist(point,circle_origin) and circle_radius
155  float distance = std::abs (std::sqrt (
156  ( input_->points[(*indices_)[i]].x - model_coefficients[0] ) *
157  ( input_->points[(*indices_)[i]].x - model_coefficients[0] ) +
158 
159  ( input_->points[(*indices_)[i]].y - model_coefficients[1] ) *
160  ( input_->points[(*indices_)[i]].y - model_coefficients[1] )
161  ) - model_coefficients[2]);
162  if (distance < threshold)
163  {
164  // Returns the indices of the points whose distances are smaller than the threshold
165  inliers.push_back ((*indices_)[i]);
166  error_sqr_dists_.push_back (static_cast<double> (distance));
167  }
168  }
169 }
170 
171 //////////////////////////////////////////////////////////////////////////
172 template <typename PointT> std::size_t
174  const Eigen::VectorXf &model_coefficients, const double threshold) const
175 {
176  // Check if the model is valid given the user constraints
177  if (!isModelValid (model_coefficients))
178  return (0);
179  std::size_t nr_p = 0;
180 
181  // Iterate through the 3d points and calculate the distances from them to the circle
182  for (std::size_t i = 0; i < indices_->size (); ++i)
183  {
184  // Calculate the distance from the point to the circle as the difference between
185  // dist(point,circle_origin) and circle_radius
186  float distance = std::abs (std::sqrt (
187  ( input_->points[(*indices_)[i]].x - model_coefficients[0] ) *
188  ( input_->points[(*indices_)[i]].x - model_coefficients[0] ) +
189 
190  ( input_->points[(*indices_)[i]].y - model_coefficients[1] ) *
191  ( input_->points[(*indices_)[i]].y - model_coefficients[1] )
192  ) - model_coefficients[2]);
193  if (distance < threshold)
194  nr_p++;
195  }
196  return (nr_p);
197 }
198 
199 //////////////////////////////////////////////////////////////////////////
200 template <typename PointT> void
202  const Indices &inliers, const Eigen::VectorXf &model_coefficients, Eigen::VectorXf &optimized_coefficients) const
203 {
204  optimized_coefficients = model_coefficients;
205 
206  // Needs a set of valid model coefficients
207  if (!isModelValid (model_coefficients))
208  {
209  PCL_ERROR ("[pcl::SampleConsensusModelCircle2D::optimizeModelCoefficients] Given model is invalid!\n");
210  return;
211  }
212 
213  // Need more than the minimum sample size to make a difference
214  if (inliers.size () <= sample_size_)
215  {
216  PCL_ERROR ("[pcl::SampleConsensusModelCircle2D::optimizeModelCoefficients] Not enough inliers to refine/optimize the model's coefficients (%lu)! Returning the same coefficients.\n", inliers.size ());
217  return;
218  }
219 
220  OptimizationFunctor functor (this, inliers);
221  Eigen::NumericalDiff<OptimizationFunctor> num_diff (functor);
222  Eigen::LevenbergMarquardt<Eigen::NumericalDiff<OptimizationFunctor>, float> lm (num_diff);
223  int info = lm.minimize (optimized_coefficients);
224 
225  // Compute the L2 norm of the residuals
226  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",
227  info, lm.fvec.norm (), model_coefficients[0], model_coefficients[1], model_coefficients[2], optimized_coefficients[0], optimized_coefficients[1], optimized_coefficients[2]);
228 }
229 
230 //////////////////////////////////////////////////////////////////////////
231 template <typename PointT> void
233  const Indices &inliers, const Eigen::VectorXf &model_coefficients,
234  PointCloud &projected_points, bool copy_data_fields) const
235 {
236  // Needs a valid set of model coefficients
237  if (!isModelValid (model_coefficients))
238  {
239  PCL_ERROR ("[pcl::SampleConsensusModelCircle2D::projectPoints] Given model is invalid!\n");
240  return;
241  }
242 
243  projected_points.header = input_->header;
244  projected_points.is_dense = input_->is_dense;
245 
246  // Copy all the data fields from the input cloud to the projected one?
247  if (copy_data_fields)
248  {
249  // Allocate enough space and copy the basics
250  projected_points.points.resize (input_->points.size ());
251  projected_points.width = input_->width;
252  projected_points.height = input_->height;
253 
254  using FieldList = typename pcl::traits::fieldList<PointT>::type;
255  // Iterate over each point
256  for (std::size_t i = 0; i < projected_points.points.size (); ++i)
257  // Iterate over each dimension
258  pcl::for_each_type <FieldList> (NdConcatenateFunctor <PointT, PointT> (input_->points[i], projected_points.points[i]));
259 
260  // Iterate through the points and project them to the circle
261  for (const auto &inlier : inliers)
262  {
263  float dx = input_->points[inlier].x - model_coefficients[0];
264  float dy = input_->points[inlier].y - model_coefficients[1];
265  float a = std::sqrt ( (model_coefficients[2] * model_coefficients[2]) / (dx * dx + dy * dy) );
266 
267  projected_points.points[inlier].x = a * dx + model_coefficients[0];
268  projected_points.points[inlier].y = a * dy + model_coefficients[1];
269  }
270  }
271  else
272  {
273  // Allocate enough space and copy the basics
274  projected_points.points.resize (inliers.size ());
275  projected_points.width = static_cast<std::uint32_t> (inliers.size ());
276  projected_points.height = 1;
277 
278  using FieldList = typename pcl::traits::fieldList<PointT>::type;
279  // Iterate over each point
280  for (std::size_t i = 0; i < inliers.size (); ++i)
281  // Iterate over each dimension
282  pcl::for_each_type <FieldList> (NdConcatenateFunctor <PointT, PointT> (input_->points[inliers[i]], projected_points.points[i]));
283 
284  // Iterate through the points and project them to the circle
285  for (std::size_t i = 0; i < inliers.size (); ++i)
286  {
287  float dx = input_->points[inliers[i]].x - model_coefficients[0];
288  float dy = input_->points[inliers[i]].y - model_coefficients[1];
289  float a = std::sqrt ( (model_coefficients[2] * model_coefficients[2]) / (dx * dx + dy * dy) );
290 
291  projected_points.points[i].x = a * dx + model_coefficients[0];
292  projected_points.points[i].y = a * dy + model_coefficients[1];
293  }
294  }
295 }
296 
297 //////////////////////////////////////////////////////////////////////////
298 template <typename PointT> bool
300  const std::set<index_t> &indices, const Eigen::VectorXf &model_coefficients, const double threshold) const
301 {
302  // Needs a valid model coefficients
303  if (!isModelValid (model_coefficients))
304  {
305  PCL_ERROR ("[pcl::SampleConsensusModelCircle2D::doSamplesVerifyModel] Given model is invalid!\n");
306  return (false);
307  }
308 
309  for (const auto &index : indices)
310  // Calculate the distance from the point to the circle as the difference between
311  //dist(point,circle_origin) and circle_radius
312  if (std::abs (std::sqrt (
313  ( input_->points[index].x - model_coefficients[0] ) *
314  ( input_->points[index].x - model_coefficients[0] ) +
315  ( input_->points[index].y - model_coefficients[1] ) *
316  ( input_->points[index].y - model_coefficients[1] )
317  ) - model_coefficients[2]) > threshold)
318  return (false);
319 
320  return (true);
321 }
322 
323 //////////////////////////////////////////////////////////////////////////
324 template <typename PointT> bool
325 pcl::SampleConsensusModelCircle2D<PointT>::isModelValid (const Eigen::VectorXf &model_coefficients) const
326 {
327  if (!SampleConsensusModel<PointT>::isModelValid (model_coefficients))
328  return (false);
329 
330  if (radius_min_ != -std::numeric_limits<double>::max() && model_coefficients[2] < radius_min_)
331  return (false);
332  if (radius_max_ != std::numeric_limits<double>::max() && model_coefficients[2] > radius_max_)
333  return (false);
334 
335  return (true);
336 }
337 
338 #define PCL_INSTANTIATE_SampleConsensusModelCircle2D(T) template class PCL_EXPORTS pcl::SampleConsensusModelCircle2D<T>;
339 
340 #endif // PCL_SAMPLE_CONSENSUS_IMPL_SAC_MODEL_CIRCLE_H_
341 
bool isModelValid(const Eigen::VectorXf &model_coefficients) const override
Check whether a model is valid given the user constraints.
bool isSampleGood(const Indices &samples) const override
Check if a sample of indices results in a good sample of points indices.
bool computeModelCoefficients(const Indices &samples, Eigen::VectorXf &model_coefficients) const override
Check whether the given index samples can form a valid 2D circle model, compute the model coefficient...
void optimizeModelCoefficients(const Indices &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...
std::uint32_t width
The point cloud width (if organized as an image-structure).
Definition: point_cloud.h:413
std::size_t countWithinDistance(const Eigen::VectorXf &model_coefficients, const double threshold) const override
Count all the points which respect the given model coefficients as inliers.
std::vector< PointT, Eigen::aligned_allocator< PointT > > points
The point data.
Definition: point_cloud.h:410
SampleConsensusModel represents the base model class.
Definition: sac_model.h:70
bool doSamplesVerifyModel(const std::set< index_t > &indices, const Eigen::VectorXf &model_coefficients, const double threshold) const override
Verify whether a subset of indices verifies the given 2d circle model coefficients.
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.
PointCloud represents the base class in PCL for storing collections of 3D points. ...
std::uint32_t height
The point cloud height (if organized as an image-structure).
Definition: point_cloud.h:415
Helper functor structure for concatenate.
Definition: concatenate.h:51
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:418
void projectPoints(const Indices &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.
void selectWithinDistance(const Eigen::VectorXf &model_coefficients, const double threshold, Indices &inliers) override
Compute all distances from the cloud data to a given 2D circle model.
pcl::PCLHeader header
The point cloud header.
Definition: point_cloud.h:407