Point Cloud Library (PCL)  1.6.0
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
mlesac.hpp
Go to the documentation of this file.
1 /*
2  * Software License Agreement (BSD License)
3  *
4  * Copyright (c) 2009, Willow Garage, Inc.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * * Redistributions of source code must retain the above copyright
12  * notice, this list of conditions and the following disclaimer.
13  * * Redistributions in binary form must reproduce the above
14  * copyright notice, this list of conditions and the following
15  * disclaimer in the documentation and/or other materials provided
16  * with the distribution.
17  * * Neither the name of Willow Garage, Inc. nor the names of its
18  * contributors may be used to endorse or promote products derived
19  * from this software without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
25  * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
27  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
29  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
31  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32  * POSSIBILITY OF SUCH DAMAGE.
33  *
34  * $Id: mlesac.hpp 6144 2012-07-04 22:06:28Z rusu $
35  *
36  */
37 
38 #ifndef PCL_SAMPLE_CONSENSUS_IMPL_MLESAC_H_
39 #define PCL_SAMPLE_CONSENSUS_IMPL_MLESAC_H_
40 
42 
44 template <typename PointT> bool
46 {
47  // Warn and exit if no threshold was set
48  if (threshold_ == std::numeric_limits<double>::max())
49  {
50  PCL_ERROR ("[pcl::MaximumLikelihoodSampleConsensus::computeModel] No threshold set!\n");
51  return (false);
52  }
53 
54  iterations_ = 0;
55  double d_best_penalty = std::numeric_limits<double>::max();
56  double k = 1.0;
57 
58  std::vector<int> best_model;
59  std::vector<int> selection;
60  Eigen::VectorXf model_coefficients;
61  std::vector<double> distances;
62 
63  // Compute sigma - remember to set threshold_ correctly !
64  sigma_ = computeMedianAbsoluteDeviation (sac_model_->getInputCloud (), sac_model_->getIndices (), threshold_);
65  if (debug_verbosity_level > 1)
66  PCL_DEBUG ("[pcl::MaximumLikelihoodSampleConsensus::computeModel] Estimated sigma value: %f.\n", sigma_);
67 
68  // Compute the bounding box diagonal: V = sqrt (sum (max(pointCloud) - min(pointCloud)^2))
69  Eigen::Vector4f min_pt, max_pt;
70  getMinMax (sac_model_->getInputCloud (), sac_model_->getIndices (), min_pt, max_pt);
71  max_pt -= min_pt;
72  double v = sqrt (max_pt.dot (max_pt));
73 
74  int n_inliers_count = 0;
75  size_t indices_size;
76  unsigned skipped_count = 0;
77  // supress infinite loops by just allowing 10 x maximum allowed iterations for invalid model parameters!
78  const unsigned max_skip = max_iterations_ * 10;
79 
80  // Iterate
81  while (iterations_ < k && skipped_count < max_skip)
82  {
83  // Get X samples which satisfy the model criteria
84  sac_model_->getSamples (iterations_, selection);
85 
86  if (selection.empty ()) break;
87 
88  // Search for inliers in the point cloud for the current plane model M
89  if (!sac_model_->computeModelCoefficients (selection, model_coefficients))
90  {
91  //iterations_++;
92  ++ skipped_count;
93  continue;
94  }
95 
96  // Iterate through the 3d points and calculate the distances from them to the model
97  sac_model_->getDistancesToModel (model_coefficients, distances);
98 
99  // Use Expectiation-Maximization to find out the right value for d_cur_penalty
100  // ---[ Initial estimate for the gamma mixing parameter = 1/2
101  double gamma = 0.5;
102  double p_outlier_prob = 0;
103 
104  indices_size = sac_model_->getIndices ()->size ();
105  std::vector<double> p_inlier_prob (indices_size);
106  for (int j = 0; j < iterations_EM_; ++j)
107  {
108  // Likelihood of a datum given that it is an inlier
109  for (size_t i = 0; i < indices_size; ++i)
110  p_inlier_prob[i] = gamma * exp (- (distances[i] * distances[i] ) / 2 * (sigma_ * sigma_) ) /
111  (sqrt (2 * M_PI) * sigma_);
112 
113  // Likelihood of a datum given that it is an outlier
114  p_outlier_prob = (1 - gamma) / v;
115 
116  gamma = 0;
117  for (size_t i = 0; i < indices_size; ++i)
118  gamma += p_inlier_prob [i] / (p_inlier_prob[i] + p_outlier_prob);
119  gamma /= static_cast<double>(sac_model_->getIndices ()->size ());
120  }
121 
122  // Find the log likelihood of the model -L = -sum [log (pInlierProb + pOutlierProb)]
123  double d_cur_penalty = 0;
124  for (size_t i = 0; i < indices_size; ++i)
125  d_cur_penalty += log (p_inlier_prob[i] + p_outlier_prob);
126  d_cur_penalty = - d_cur_penalty;
127 
128  // Better match ?
129  if (d_cur_penalty < d_best_penalty)
130  {
131  d_best_penalty = d_cur_penalty;
132 
133  // Save the current model/coefficients selection as being the best so far
134  model_ = selection;
135  model_coefficients_ = model_coefficients;
136 
137  n_inliers_count = 0;
138  // Need to compute the number of inliers for this model to adapt k
139  for (size_t i = 0; i < distances.size (); ++i)
140  if (distances[i] <= 2 * sigma_)
141  n_inliers_count++;
142 
143  // Compute the k parameter (k=log(z)/log(1-w^n))
144  double w = static_cast<double> (n_inliers_count) / static_cast<double> (sac_model_->getIndices ()->size ());
145  double p_no_outliers = 1 - pow (w, static_cast<double> (selection.size ()));
146  p_no_outliers = (std::max) (std::numeric_limits<double>::epsilon (), p_no_outliers); // Avoid division by -Inf
147  p_no_outliers = (std::min) (1 - std::numeric_limits<double>::epsilon (), p_no_outliers); // Avoid division by 0.
148  k = log (1 - probability_) / log (p_no_outliers);
149  }
150 
151  ++iterations_;
152  if (debug_verbosity_level > 1)
153  PCL_DEBUG ("[pcl::MaximumLikelihoodSampleConsensus::computeModel] Trial %d out of %d. Best penalty is %f.\n", iterations_, static_cast<int> (ceil (k)), d_best_penalty);
154  if (iterations_ > max_iterations_)
155  {
156  if (debug_verbosity_level > 0)
157  PCL_DEBUG ("[pcl::MaximumLikelihoodSampleConsensus::computeModel] MLESAC reached the maximum number of trials.\n");
158  break;
159  }
160  }
161 
162  if (model_.empty ())
163  {
164  if (debug_verbosity_level > 0)
165  PCL_DEBUG ("[pcl::MaximumLikelihoodSampleConsensus::computeModel] Unable to find a solution!\n");
166  return (false);
167  }
168 
169  // Iterate through the 3d points and calculate the distances from them to the model again
170  sac_model_->getDistancesToModel (model_coefficients_, distances);
171  std::vector<int> &indices = *sac_model_->getIndices ();
172  if (distances.size () != indices.size ())
173  {
174  PCL_ERROR ("[pcl::MaximumLikelihoodSampleConsensus::computeModel] Estimated distances (%zu) differs than the normal of indices (%zu).\n", distances.size (), indices.size ());
175  return (false);
176  }
177 
178  inliers_.resize (distances.size ());
179  // Get the inliers for the best model found
180  n_inliers_count = 0;
181  for (size_t i = 0; i < distances.size (); ++i)
182  if (distances[i] <= 2 * sigma_)
183  inliers_[n_inliers_count++] = indices[i];
184 
185  // Resize the inliers vector
186  inliers_.resize (n_inliers_count);
187 
188  if (debug_verbosity_level > 0)
189  PCL_DEBUG ("[pcl::MaximumLikelihoodSampleConsensus::computeModel] Model: %zu size, %d inliers.\n", model_.size (), n_inliers_count);
190 
191  return (true);
192 }
193 
195 template <typename PointT> double
197  const PointCloudConstPtr &cloud,
198  const boost::shared_ptr <std::vector<int> > &indices,
199  double sigma)
200 {
201  std::vector<double> distances (indices->size ());
202 
203  Eigen::Vector4f median;
204  // median (dist (x - median (x)))
205  computeMedian (cloud, indices, median);
206 
207  for (size_t i = 0; i < indices->size (); ++i)
208  {
209  pcl::Vector4fMapConst pt = cloud->points[(*indices)[i]].getVector4fMap ();
210  Eigen::Vector4f ptdiff = pt - median;
211  ptdiff[3] = 0;
212  distances[i] = ptdiff.dot (ptdiff);
213  }
214 
215  std::sort (distances.begin (), distances.end ());
216 
217  double result;
218  size_t mid = indices->size () / 2;
219  // Do we have a "middle" point or should we "estimate" one ?
220  if (indices->size () % 2 == 0)
221  result = (sqrt (distances[mid-1]) + sqrt (distances[mid])) / 2;
222  else
223  result = sqrt (distances[mid]);
224  return (sigma * result);
225 }
226 
228 template <typename PointT> void
230  const PointCloudConstPtr &cloud,
231  const boost::shared_ptr <std::vector<int> > &indices,
232  Eigen::Vector4f &min_p,
233  Eigen::Vector4f &max_p)
234 {
235  min_p.setConstant (FLT_MAX);
236  max_p.setConstant (-FLT_MAX);
237  min_p[3] = max_p[3] = 0;
238 
239  for (size_t i = 0; i < indices->size (); ++i)
240  {
241  if (cloud->points[(*indices)[i]].x < min_p[0]) min_p[0] = cloud->points[(*indices)[i]].x;
242  if (cloud->points[(*indices)[i]].y < min_p[1]) min_p[1] = cloud->points[(*indices)[i]].y;
243  if (cloud->points[(*indices)[i]].z < min_p[2]) min_p[2] = cloud->points[(*indices)[i]].z;
244 
245  if (cloud->points[(*indices)[i]].x > max_p[0]) max_p[0] = cloud->points[(*indices)[i]].x;
246  if (cloud->points[(*indices)[i]].y > max_p[1]) max_p[1] = cloud->points[(*indices)[i]].y;
247  if (cloud->points[(*indices)[i]].z > max_p[2]) max_p[2] = cloud->points[(*indices)[i]].z;
248  }
249 }
250 
252 template <typename PointT> void
254  const PointCloudConstPtr &cloud,
255  const boost::shared_ptr <std::vector<int> > &indices,
256  Eigen::Vector4f &median)
257 {
258  // Copy the values to vectors for faster sorting
259  std::vector<float> x (indices->size ());
260  std::vector<float> y (indices->size ());
261  std::vector<float> z (indices->size ());
262  for (size_t i = 0; i < indices->size (); ++i)
263  {
264  x[i] = cloud->points[(*indices)[i]].x;
265  y[i] = cloud->points[(*indices)[i]].y;
266  z[i] = cloud->points[(*indices)[i]].z;
267  }
268  std::sort (x.begin (), x.end ());
269  std::sort (y.begin (), y.end ());
270  std::sort (z.begin (), z.end ());
271 
272  size_t mid = indices->size () / 2;
273  if (indices->size () % 2 == 0)
274  {
275  median[0] = (x[mid-1] + x[mid]) / 2;
276  median[1] = (y[mid-1] + y[mid]) / 2;
277  median[2] = (z[mid-1] + z[mid]) / 2;
278  }
279  else
280  {
281  median[0] = x[mid];
282  median[1] = y[mid];
283  median[2] = z[mid];
284  }
285  median[3] = 0;
286 }
287 
288 #define PCL_INSTANTIATE_MaximumLikelihoodSampleConsensus(T) template class PCL_EXPORTS pcl::MaximumLikelihoodSampleConsensus<T>;
289 
290 #endif // PCL_SAMPLE_CONSENSUS_IMPL_MLESAC_H_
291