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