Point Cloud Library (PCL)  1.11.1
lmeds.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_LMEDS_H_
42 #define PCL_SAMPLE_CONSENSUS_IMPL_LMEDS_H_
43 
44 #include <pcl/sample_consensus/lmeds.h>
45 
46 //////////////////////////////////////////////////////////////////////////
47 template <typename PointT> bool
49 {
50  // Warn and exit if no threshold was set
51  if (threshold_ == std::numeric_limits<double>::max())
52  {
53  PCL_ERROR ("[pcl::LeastMedianSquares::computeModel] No threshold set!\n");
54  return (false);
55  }
56 
57  iterations_ = 0;
58  double d_best_penalty = std::numeric_limits<double>::max();
59 
60  Indices selection;
61  Eigen::VectorXf model_coefficients;
62  std::vector<double> distances;
63 
64  unsigned skipped_count = 0;
65  // suppress infinite loops by just allowing 10 x maximum allowed iterations for invalid model parameters!
66  const unsigned max_skip = max_iterations_ * 10;
67 
68  // Iterate
69  while ((iterations_ < max_iterations_) && (skipped_count < max_skip))
70  {
71  // Get X samples which satisfy the model criteria
72  sac_model_->getSamples (iterations_, selection);
73 
74  if (selection.empty ())
75  {
76  break;
77  }
78 
79  // Search for inliers in the point cloud for the current plane model M
80  if (!sac_model_->computeModelCoefficients (selection, model_coefficients))
81  {
82  //iterations_++;
83  ++skipped_count;
84  continue;
85  }
86 
87  double d_cur_penalty;
88  // d_cur_penalty = sum (min (dist, threshold))
89 
90  // Iterate through the 3d points and calculate the distances from them to the model
91  sac_model_->getDistancesToModel (model_coefficients, distances);
92 
93  // No distances? The model must not respect the user given constraints
94  if (distances.empty ())
95  {
96  //iterations_++;
97  ++skipped_count;
98  continue;
99  }
100  // Move all NaNs in distances to the end
101  const auto new_end = (sac_model_->getInputCloud()->is_dense ? distances.end() : std::partition (distances.begin(), distances.end(), [](double d){return !std::isnan (d);}));
102  const auto nr_valid_dists = std::distance (distances.begin (), new_end);
103 
104  // d_cur_penalty = median (distances)
105  const std::size_t mid = nr_valid_dists / 2;
106  PCL_DEBUG ("[pcl::LeastMedianSquares::computeModel] There are %lu valid distances remaining after removing NaN values.\n", nr_valid_dists);
107  if (nr_valid_dists == 0)
108  {
109  //iterations_++;
110  ++skipped_count;
111  continue;
112  }
113 
114  // Do we have a "middle" point or should we "estimate" one ?
115  if ((nr_valid_dists % 2) == 0)
116  {
117  // Looking at two values instead of one probably doesn't matter because they are mostly barely different, but let's do it for accuracy's sake
118  std::nth_element (distances.begin (), distances.begin () + (mid - 1), new_end);
119  const double tmp = distances[mid-1];
120  const double tmp2 = *(std::min_element (distances.begin () + mid, new_end));
121  d_cur_penalty = (sqrt (tmp) + sqrt (tmp2)) / 2.0;
122  PCL_DEBUG ("[pcl::LeastMedianSquares::computeModel] Computing median with two values (%g and %g) because number of distances is even.\n", tmp, distances[mid]);
123  }
124  else
125  {
126  std::nth_element (distances.begin (), distances.begin () + mid, new_end);
127  d_cur_penalty = sqrt (distances[mid]);
128  PCL_DEBUG ("[pcl::LeastMedianSquares::computeModel] Computing median with one value (%g) because number of distances is odd.\n", distances[mid]);
129  }
130 
131  // Better match ?
132  if (d_cur_penalty < d_best_penalty)
133  {
134  d_best_penalty = d_cur_penalty;
135 
136  // Save the current model/coefficients selection as being the best so far
137  model_ = selection;
138  model_coefficients_ = model_coefficients;
139  }
140 
141  ++iterations_;
142  if (debug_verbosity_level > 1)
143  {
144  PCL_DEBUG ("[pcl::LeastMedianSquares::computeModel] Trial %d out of %d. Best penalty is %f.\n", iterations_, max_iterations_, d_best_penalty);
145  }
146  }
147 
148  if (model_.empty ())
149  {
150  if (debug_verbosity_level > 0)
151  {
152  PCL_DEBUG ("[pcl::LeastMedianSquares::computeModel] Unable to find a solution!\n");
153  }
154  return (false);
155  }
156 
157  // Classify the data points into inliers and outliers
158  // Sigma = 1.4826 * (1 + 5 / (n-d)) * sqrt (M)
159  // @note: See "Robust Regression Methods for Computer Vision: A Review"
160  //double sigma = 1.4826 * (1 + 5 / (sac_model_->getIndices ()->size () - best_model.size ())) * sqrt (d_best_penalty);
161  //double threshold = 2.5 * sigma;
162 
163  // Iterate through the 3d points and calculate the distances from them to the model again
164  sac_model_->getDistancesToModel (model_coefficients_, distances);
165  // No distances? The model must not respect the user given constraints
166  if (distances.empty ())
167  {
168  PCL_ERROR ("[pcl::LeastMedianSquares::computeModel] The model found failed to verify against the given constraints!\n");
169  return (false);
170  }
171 
172  Indices &indices = *sac_model_->getIndices ();
173 
174  if (distances.size () != indices.size ())
175  {
176  PCL_ERROR ("[pcl::LeastMedianSquares::computeModel] Estimated distances (%lu) differs than the normal of indices (%lu).\n", distances.size (), indices.size ());
177  return (false);
178  }
179 
180  inliers_.resize (distances.size ());
181  // Get the inliers for the best model found
182  std::size_t n_inliers_count = 0;
183  for (std::size_t i = 0; i < distances.size (); ++i)
184  {
185  if (distances[i] <= threshold_)
186  {
187  inliers_[n_inliers_count++] = indices[i];
188  }
189  }
190 
191  // Resize the inliers vector
192  inliers_.resize (n_inliers_count);
193 
194  if (debug_verbosity_level > 0)
195  {
196  PCL_DEBUG ("[pcl::LeastMedianSquares::computeModel] Model: %lu size, %lu inliers.\n", model_.size (), n_inliers_count);
197  }
198 
199  return (true);
200 }
201 
202 #define PCL_INSTANTIATE_LeastMedianSquares(T) template class PCL_EXPORTS pcl::LeastMedianSquares<T>;
203 
204 #endif // PCL_SAMPLE_CONSENSUS_IMPL_LMEDS_H_
float distance(const PointT &p1, const PointT &p2)
Definition: geometry.h:60
IndicesAllocator<> Indices
Type used for indices in PCL.
Definition: types.h:141
bool computeModel(int debug_verbosity_level=0) override
Compute the actual model and find the inliers.
Definition: lmeds.hpp:48