Point Cloud Library (PCL)  1.9.1-dev
sac_model_line.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_LINE_H_
42 #define PCL_SAMPLE_CONSENSUS_IMPL_SAC_MODEL_LINE_H_
43 
44 #include <pcl/sample_consensus/sac_model_line.h>
45 #include <pcl/common/centroid.h>
46 #include <pcl/common/concatenate.h>
47 
48 //////////////////////////////////////////////////////////////////////////
49 template <typename PointT> bool
50 pcl::SampleConsensusModelLine<PointT>::isSampleGood (const std::vector<int> &samples) const
51 {
52  // Make sure that the two sample points are not identical
53  if (
54  (input_->points[samples[0]].x != input_->points[samples[1]].x)
55  ||
56  (input_->points[samples[0]].y != input_->points[samples[1]].y)
57  ||
58  (input_->points[samples[0]].z != input_->points[samples[1]].z))
59  {
60  return (true);
61  }
62 
63  return (false);
64 }
65 
66 //////////////////////////////////////////////////////////////////////////
67 template <typename PointT> bool
69  const std::vector<int> &samples, Eigen::VectorXf &model_coefficients) const
70 {
71  // Need 2 samples
72  if (samples.size () != 2)
73  {
74  PCL_ERROR ("[pcl::SampleConsensusModelLine::computeModelCoefficients] Invalid set of samples given (%lu)!\n", samples.size ());
75  return (false);
76  }
77 
78  if (std::abs (input_->points[samples[0]].x - input_->points[samples[1]].x) <= std::numeric_limits<float>::epsilon () &&
79  std::abs (input_->points[samples[0]].y - input_->points[samples[1]].y) <= std::numeric_limits<float>::epsilon () &&
80  std::abs (input_->points[samples[0]].z - input_->points[samples[1]].z) <= std::numeric_limits<float>::epsilon ())
81  {
82  return (false);
83  }
84 
85  model_coefficients.resize (6);
86  model_coefficients[0] = input_->points[samples[0]].x;
87  model_coefficients[1] = input_->points[samples[0]].y;
88  model_coefficients[2] = input_->points[samples[0]].z;
89 
90  model_coefficients[3] = input_->points[samples[1]].x - model_coefficients[0];
91  model_coefficients[4] = input_->points[samples[1]].y - model_coefficients[1];
92  model_coefficients[5] = input_->points[samples[1]].z - model_coefficients[2];
93 
94  model_coefficients.template tail<3> ().normalize ();
95  return (true);
96 }
97 
98 //////////////////////////////////////////////////////////////////////////
99 template <typename PointT> void
101  const Eigen::VectorXf &model_coefficients, std::vector<double> &distances) const
102 {
103  // Needs a valid set of model coefficients
104  if (!isModelValid (model_coefficients))
105  return;
106 
107  distances.resize (indices_->size ());
108 
109  // Obtain the line point and direction
110  Eigen::Vector4f line_pt (model_coefficients[0], model_coefficients[1], model_coefficients[2], 0);
111  Eigen::Vector4f line_dir (model_coefficients[3], model_coefficients[4], model_coefficients[5], 0);
112  line_dir.normalize ();
113 
114  // Iterate through the 3d points and calculate the distances from them to the line
115  for (size_t i = 0; i < indices_->size (); ++i)
116  {
117  // Calculate the distance from the point to the line
118  // D = ||(P2-P1) x (P1-P0)|| / ||P2-P1|| = norm (cross (p2-p1, p2-p0)) / norm(p2-p1)
119  // Need to estimate sqrt here to keep MSAC and friends general
120  distances[i] = sqrt ((line_pt - input_->points[(*indices_)[i]].getVector4fMap ()).cross3 (line_dir).squaredNorm ());
121  }
122 }
123 
124 //////////////////////////////////////////////////////////////////////////
125 template <typename PointT> void
127  const Eigen::VectorXf &model_coefficients, const double threshold, std::vector<int> &inliers)
128 {
129  // Needs a valid set of model coefficients
130  if (!isModelValid (model_coefficients))
131  return;
132 
133  double sqr_threshold = threshold * threshold;
134 
135  int nr_p = 0;
136  inliers.resize (indices_->size ());
137  error_sqr_dists_.resize (indices_->size ());
138 
139  // Obtain the line point and direction
140  Eigen::Vector4f line_pt (model_coefficients[0], model_coefficients[1], model_coefficients[2], 0);
141  Eigen::Vector4f line_dir (model_coefficients[3], model_coefficients[4], model_coefficients[5], 0);
142  line_dir.normalize ();
143 
144  // Iterate through the 3d points and calculate the distances from them to the line
145  for (size_t i = 0; i < indices_->size (); ++i)
146  {
147  // Calculate the distance from the point to the line
148  // D = ||(P2-P1) x (P1-P0)|| / ||P2-P1|| = norm (cross (p2-p1, p2-p0)) / norm(p2-p1)
149  double sqr_distance = (line_pt - input_->points[(*indices_)[i]].getVector4fMap ()).cross3 (line_dir).squaredNorm ();
150 
151  if (sqr_distance < sqr_threshold)
152  {
153  // Returns the indices of the points whose squared distances are smaller than the threshold
154  inliers[nr_p] = (*indices_)[i];
155  error_sqr_dists_[nr_p] = sqr_distance;
156  ++nr_p;
157  }
158  }
159  inliers.resize (nr_p);
160  error_sqr_dists_.resize (nr_p);
161 }
162 
163 //////////////////////////////////////////////////////////////////////////
164 template <typename PointT> int
166  const Eigen::VectorXf &model_coefficients, const double threshold) const
167 {
168  // Needs a valid set of model coefficients
169  if (!isModelValid (model_coefficients))
170  return (0);
171 
172  double sqr_threshold = threshold * threshold;
173 
174  int nr_p = 0;
175 
176  // Obtain the line point and direction
177  Eigen::Vector4f line_pt (model_coefficients[0], model_coefficients[1], model_coefficients[2], 0);
178  Eigen::Vector4f line_dir (model_coefficients[3], model_coefficients[4], model_coefficients[5], 0);
179  line_dir.normalize ();
180 
181  // Iterate through the 3d points and calculate the distances from them to the line
182  for (size_t i = 0; i < indices_->size (); ++i)
183  {
184  // Calculate the distance from the point to the line
185  // D = ||(P2-P1) x (P1-P0)|| / ||P2-P1|| = norm (cross (p2-p1, p2-p0)) / norm(p2-p1)
186  double sqr_distance = (line_pt - input_->points[(*indices_)[i]].getVector4fMap ()).cross3 (line_dir).squaredNorm ();
187 
188  if (sqr_distance < sqr_threshold)
189  nr_p++;
190  }
191  return (nr_p);
192 }
193 
194 //////////////////////////////////////////////////////////////////////////
195 template <typename PointT> void
197  const std::vector<int> &inliers, const Eigen::VectorXf &model_coefficients, Eigen::VectorXf &optimized_coefficients) const
198 {
199  // Needs a valid set of model coefficients
200  if (!isModelValid (model_coefficients))
201  {
202  optimized_coefficients = model_coefficients;
203  return;
204  }
205 
206  // Need at least 2 points to estimate a line
207  if (inliers.size () <= 2)
208  {
209  PCL_ERROR ("[pcl::SampleConsensusModelLine::optimizeModelCoefficients] Not enough inliers found to support a model (%lu)! Returning the same coefficients.\n", inliers.size ());
210  optimized_coefficients = model_coefficients;
211  return;
212  }
213 
214  optimized_coefficients.resize (6);
215 
216  // Compute the 3x3 covariance matrix
217  Eigen::Vector4f centroid;
218  compute3DCentroid (*input_, inliers, centroid);
219  Eigen::Matrix3f covariance_matrix;
220  computeCovarianceMatrix (*input_, inliers, centroid, covariance_matrix);
221  optimized_coefficients[0] = centroid[0];
222  optimized_coefficients[1] = centroid[1];
223  optimized_coefficients[2] = centroid[2];
224 
225  // Extract the eigenvalues and eigenvectors
226  EIGEN_ALIGN16 Eigen::Vector3f eigen_values;
227  EIGEN_ALIGN16 Eigen::Vector3f eigen_vector;
228  pcl::eigen33 (covariance_matrix, eigen_values);
229  pcl::computeCorrespondingEigenVector (covariance_matrix, eigen_values [2], eigen_vector);
230  //pcl::eigen33 (covariance_matrix, eigen_vectors, eigen_values);
231 
232  optimized_coefficients.template tail<3> ().matrix () = eigen_vector;
233 }
234 
235 //////////////////////////////////////////////////////////////////////////
236 template <typename PointT> void
238  const std::vector<int> &inliers, const Eigen::VectorXf &model_coefficients, PointCloud &projected_points, bool copy_data_fields) const
239 {
240  // Needs a valid model coefficients
241  if (!isModelValid (model_coefficients))
242  return;
243 
244  // Obtain the line point and direction
245  Eigen::Vector4f line_pt (model_coefficients[0], model_coefficients[1], model_coefficients[2], 0);
246  Eigen::Vector4f line_dir (model_coefficients[3], model_coefficients[4], model_coefficients[5], 0);
247 
248  projected_points.header = input_->header;
249  projected_points.is_dense = input_->is_dense;
250 
251  // Copy all the data fields from the input cloud to the projected one?
252  if (copy_data_fields)
253  {
254  // Allocate enough space and copy the basics
255  projected_points.points.resize (input_->points.size ());
256  projected_points.width = input_->width;
257  projected_points.height = input_->height;
258 
259  using FieldList = typename pcl::traits::fieldList<PointT>::type;
260  // Iterate over each point
261  for (size_t i = 0; i < projected_points.points.size (); ++i)
262  // Iterate over each dimension
263  pcl::for_each_type <FieldList> (NdConcatenateFunctor <PointT, PointT> (input_->points[i], projected_points.points[i]));
264 
265  // Iterate through the 3d points and calculate the distances from them to the line
266  for (const int &inlier : inliers)
267  {
268  Eigen::Vector4f pt (input_->points[inlier].x, input_->points[inlier].y, input_->points[inlier].z, 0);
269  // double k = (DOT_PROD_3D (points[i], p21) - dotA_B) / dotB_B;
270  float k = (pt.dot (line_dir) - line_pt.dot (line_dir)) / line_dir.dot (line_dir);
271 
272  Eigen::Vector4f pp = line_pt + k * line_dir;
273  // Calculate the projection of the point on the line (pointProj = A + k * B)
274  projected_points.points[inlier].x = pp[0];
275  projected_points.points[inlier].y = pp[1];
276  projected_points.points[inlier].z = pp[2];
277  }
278  }
279  else
280  {
281  // Allocate enough space and copy the basics
282  projected_points.points.resize (inliers.size ());
283  projected_points.width = static_cast<uint32_t> (inliers.size ());
284  projected_points.height = 1;
285 
286  using FieldList = typename pcl::traits::fieldList<PointT>::type;
287  // Iterate over each point
288  for (size_t i = 0; i < inliers.size (); ++i)
289  // Iterate over each dimension
290  pcl::for_each_type <FieldList> (NdConcatenateFunctor <PointT, PointT> (input_->points[inliers[i]], projected_points.points[i]));
291 
292  // Iterate through the 3d points and calculate the distances from them to the line
293  for (size_t i = 0; i < inliers.size (); ++i)
294  {
295  Eigen::Vector4f pt (input_->points[inliers[i]].x, input_->points[inliers[i]].y, input_->points[inliers[i]].z, 0);
296  // double k = (DOT_PROD_3D (points[i], p21) - dotA_B) / dotB_B;
297  float k = (pt.dot (line_dir) - line_pt.dot (line_dir)) / line_dir.dot (line_dir);
298 
299  Eigen::Vector4f pp = line_pt + k * line_dir;
300  // Calculate the projection of the point on the line (pointProj = A + k * B)
301  projected_points.points[i].x = pp[0];
302  projected_points.points[i].y = pp[1];
303  projected_points.points[i].z = pp[2];
304  }
305  }
306 }
307 
308 //////////////////////////////////////////////////////////////////////////
309 template <typename PointT> bool
311  const std::set<int> &indices, const Eigen::VectorXf &model_coefficients, const double threshold) const
312 {
313  // Needs a valid set of model coefficients
314  if (!isModelValid (model_coefficients))
315  return (false);
316 
317  // Obtain the line point and direction
318  Eigen::Vector4f line_pt (model_coefficients[0], model_coefficients[1], model_coefficients[2], 0);
319  Eigen::Vector4f line_dir (model_coefficients[3], model_coefficients[4], model_coefficients[5], 0);
320  line_dir.normalize ();
321 
322  double sqr_threshold = threshold * threshold;
323  // Iterate through the 3d points and calculate the distances from them to the line
324  for (const int &index : indices)
325  {
326  // Calculate the distance from the point to the line
327  // D = ||(P2-P1) x (P1-P0)|| / ||P2-P1|| = norm (cross (p2-p1, p2-p0)) / norm(p2-p1)
328  if ((line_pt - input_->points[index].getVector4fMap ()).cross3 (line_dir).squaredNorm () > sqr_threshold)
329  return (false);
330  }
331 
332  return (true);
333 }
334 
335 #define PCL_INSTANTIATE_SampleConsensusModelLine(T) template class PCL_EXPORTS pcl::SampleConsensusModelLine<T>;
336 
337 #endif // PCL_SAMPLE_CONSENSUS_IMPL_SAC_MODEL_LINE_H_
338 
void computeCorrespondingEigenVector(const Matrix &mat, const typename Matrix::Scalar &eigenvalue, Vector &eigenvector)
determines the corresponding eigenvector to the given eigenvalue of the symmetric positive semi defin...
Definition: eigen.hpp:219
std::vector< PointT, Eigen::aligned_allocator< PointT > > points
The point data.
Definition: point_cloud.h:411
uint32_t height
The point cloud height (if organized as an image-structure).
Definition: point_cloud.h:416
uint32_t width
The point cloud width (if organized as an image-structure).
Definition: point_cloud.h:414
bool computeModelCoefficients(const std::vector< int > &samples, Eigen::VectorXf &model_coefficients) const override
Check whether the given index samples can form a valid line model, compute the model coefficients fro...
void selectWithinDistance(const Eigen::VectorXf &model_coefficients, const double threshold, std::vector< int > &inliers) override
Select all the points which respect the given model coefficients as inliers.
unsigned int computeCovarianceMatrix(const pcl::PointCloud< PointT > &cloud, const Eigen::Matrix< Scalar, 4, 1 > &centroid, Eigen::Matrix< Scalar, 3, 3 > &covariance_matrix)
Compute the 3x3 covariance matrix of a given set of points.
PointCloud represents the base class in PCL for storing collections of 3D points. ...
pcl::PCLHeader header
The point cloud header.
Definition: point_cloud.h:408
void eigen33(const Matrix &mat, typename Matrix::Scalar &eigenvalue, Vector &eigenvector)
determines the eigenvector and eigenvalue of the smallest eigenvalue of the symmetric positive semi d...
Definition: eigen.hpp:251
void optimizeModelCoefficients(const std::vector< int > &inliers, const Eigen::VectorXf &model_coefficients, Eigen::VectorXf &optimized_coefficients) const override
Recompute the line coefficients using the given inlier set and return them to the user...
void getDistancesToModel(const Eigen::VectorXf &model_coefficients, std::vector< double > &distances) const override
Compute all squared distances from the cloud data to a given line model.
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:419
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 isSampleGood(const std::vector< int > &samples) const override
Check if a sample of indices results in a good sample of points indices.
unsigned int compute3DCentroid(ConstCloudIterator< PointT > &cloud_iterator, Eigen::Matrix< Scalar, 4, 1 > &centroid)
Compute the 3D (X-Y-Z) centroid of a set of points and return it as a 3D vector.
Definition: centroid.hpp:50
Helper functor structure for concatenate.
Definition: concatenate.h:51
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 line model.
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 line model coefficients.