Point Cloud Library (PCL)  1.9.1-dev
mls.hpp
1 /*
2  * Software License Agreement (BSD License)
3  *
4  * Point Cloud Library (PCL) - www.pointclouds.org
5  * Copyright (c) 2009-2011, Willow Garage, Inc.
6  *
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *
13  * * Redistributions of source code must retain the above copyright
14  * notice, this list of conditions and the following disclaimer.
15  * * Redistributions in binary form must reproduce the above
16  * copyright notice, this list of conditions and the following
17  * disclaimer in the documentation and/or other materials provided
18  * with the distribution.
19  * * Neither the name of Willow Garage, Inc. nor the names of its
20  * contributors may be used to endorse or promote products derived
21  * from this software without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27  * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
31  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
33  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34  * POSSIBILITY OF SUCH DAMAGE.
35  *
36  * $Id$
37  *
38  */
39 
40 #ifndef PCL_SURFACE_IMPL_MLS_H_
41 #define PCL_SURFACE_IMPL_MLS_H_
42 
43 #include <pcl/point_traits.h>
44 #include <pcl/surface/mls.h>
45 #include <pcl/common/io.h>
46 #include <pcl/common/copy_point.h>
47 #include <pcl/common/centroid.h>
48 #include <pcl/common/eigen.h>
49 #include <pcl/common/geometry.h>
50 
51 #ifdef _OPENMP
52 #include <omp.h>
53 #endif
54 
55 //////////////////////////////////////////////////////////////////////////////////////////////
56 template <typename PointInT, typename PointOutT> void
58 {
59  // Reset or initialize the collection of indices
60  corresponding_input_indices_.reset (new PointIndices);
61 
62  // Check if normals have to be computed/saved
63  if (compute_normals_)
64  {
65  normals_.reset (new NormalCloud);
66  // Copy the header
67  normals_->header = input_->header;
68  // Clear the fields in case the method exits before computation
69  normals_->width = normals_->height = 0;
70  normals_->points.clear ();
71  }
72 
73  // Copy the header
74  output.header = input_->header;
75  output.width = output.height = 0;
76  output.points.clear ();
77 
78  if (search_radius_ <= 0 || sqr_gauss_param_ <= 0)
79  {
80  PCL_ERROR ("[pcl::%s::process] Invalid search radius (%f) or Gaussian parameter (%f)!\n", getClassName ().c_str (), search_radius_, sqr_gauss_param_);
81  return;
82  }
83 
84  // Check if distinct_cloud_ was set
85  if (upsample_method_ == DISTINCT_CLOUD && !distinct_cloud_)
86  {
87  PCL_ERROR ("[pcl::%s::process] Upsample method was set to DISTINCT_CLOUD, but no distinct cloud was specified.\n", getClassName ().c_str ());
88  return;
89  }
90 
91  if (!initCompute ())
92  return;
93 
94  // Initialize the spatial locator
95  if (!tree_)
96  {
97  KdTreePtr tree;
98  if (input_->isOrganized ())
99  tree.reset (new pcl::search::OrganizedNeighbor<PointInT> ());
100  else
101  tree.reset (new pcl::search::KdTree<PointInT> (false));
102  setSearchMethod (tree);
103  }
104 
105  // Send the surface dataset to the spatial locator
106  tree_->setInputCloud (input_);
107 
108  switch (upsample_method_)
109  {
110  // Initialize random number generator if necessary
111  case (RANDOM_UNIFORM_DENSITY):
112  {
113  std::random_device rd;
114  rng_.seed (rd());
115  const double tmp = search_radius_ / 2.0;
116  rng_uniform_distribution_.reset (new std::uniform_real_distribution<> (-tmp, tmp));
117 
118  break;
119  }
120  case (VOXEL_GRID_DILATION):
121  case (DISTINCT_CLOUD):
122  {
123  if (!cache_mls_results_)
124  PCL_WARN ("The cache mls results is forced when using upsampling method VOXEL_GRID_DILATION or DISTINCT_CLOUD.\n");
125 
126  cache_mls_results_ = true;
127  break;
128  }
129  default:
130  break;
131  }
132 
133  if (cache_mls_results_)
134  {
135  mls_results_.resize (input_->size ());
136  }
137  else
138  {
139  mls_results_.resize (1); // Need to have a reference to a single dummy result.
140  }
141 
142  // Perform the actual surface reconstruction
143  performProcessing (output);
144 
145  if (compute_normals_)
146  {
147  normals_->height = 1;
148  normals_->width = static_cast<uint32_t> (normals_->size ());
149 
150  for (size_t i = 0; i < output.size (); ++i)
151  {
152  using FieldList = typename pcl::traits::fieldList<PointOutT>::type;
153  pcl::for_each_type<FieldList> (SetIfFieldExists<PointOutT, float> (output.points[i], "normal_x", normals_->points[i].normal_x));
154  pcl::for_each_type<FieldList> (SetIfFieldExists<PointOutT, float> (output.points[i], "normal_y", normals_->points[i].normal_y));
155  pcl::for_each_type<FieldList> (SetIfFieldExists<PointOutT, float> (output.points[i], "normal_z", normals_->points[i].normal_z));
156  pcl::for_each_type<FieldList> (SetIfFieldExists<PointOutT, float> (output.points[i], "curvature", normals_->points[i].curvature));
157  }
158 
159  }
160 
161  // Set proper widths and heights for the clouds
162  output.height = 1;
163  output.width = static_cast<uint32_t> (output.size ());
164 
165  deinitCompute ();
166 }
167 
168 //////////////////////////////////////////////////////////////////////////////////////////////
169 template <typename PointInT, typename PointOutT> void
171  const std::vector<int> &nn_indices,
172  PointCloudOut &projected_points,
173  NormalCloud &projected_points_normals,
174  PointIndices &corresponding_input_indices,
175  MLSResult &mls_result) const
176 {
177  // Note: this method is const because it needs to be thread-safe
178  // (MovingLeastSquaresOMP calls it from multiple threads)
179 
180  mls_result.computeMLSSurface<PointInT> (*input_, index, nn_indices, search_radius_, order_);
181 
182  switch (upsample_method_)
183  {
184  case (NONE):
185  {
186  const MLSResult::MLSProjectionResults proj = mls_result.projectQueryPoint (projection_method_, nr_coeff_);
187  addProjectedPointNormal (index, proj.point, proj.normal, mls_result.curvature, projected_points, projected_points_normals, corresponding_input_indices);
188  break;
189  }
190 
191  case (SAMPLE_LOCAL_PLANE):
192  {
193  // Uniformly sample a circle around the query point using the radius and step parameters
194  for (float u_disp = -static_cast<float> (upsampling_radius_); u_disp <= upsampling_radius_; u_disp += static_cast<float> (upsampling_step_))
195  for (float v_disp = -static_cast<float> (upsampling_radius_); v_disp <= upsampling_radius_; v_disp += static_cast<float> (upsampling_step_))
196  if (u_disp * u_disp + v_disp * v_disp < upsampling_radius_ * upsampling_radius_)
197  {
199  addProjectedPointNormal (index, proj.point, proj.normal, mls_result.curvature, projected_points, projected_points_normals, corresponding_input_indices);
200  }
201  break;
202  }
203 
204  case (RANDOM_UNIFORM_DENSITY):
205  {
206  // Compute the local point density and add more samples if necessary
207  const int num_points_to_add = static_cast<int> (std::floor (desired_num_points_in_radius_ / 2.0 / static_cast<double> (nn_indices.size ())));
208 
209  // Just add the query point, because the density is good
210  if (num_points_to_add <= 0)
211  {
212  // Just add the current point
213  const MLSResult::MLSProjectionResults proj = mls_result.projectQueryPoint (projection_method_, nr_coeff_);
214  addProjectedPointNormal (index, proj.point, proj.normal, mls_result.curvature, projected_points, projected_points_normals, corresponding_input_indices);
215  }
216  else
217  {
218  // Sample the local plane
219  for (int num_added = 0; num_added < num_points_to_add;)
220  {
221  const double u = (*rng_uniform_distribution_) (rng_);
222  const double v = (*rng_uniform_distribution_) (rng_);
223 
224  // Check if inside circle; if not, try another coin flip
225  if (u * u + v * v > search_radius_ * search_radius_ / 4)
226  continue;
227 
229  if (order_ > 1 && mls_result.num_neighbors >= 5 * nr_coeff_)
230  proj = mls_result.projectPointSimpleToPolynomialSurface (u, v);
231  else
232  proj = mls_result.projectPointToMLSPlane (u, v);
233 
234  addProjectedPointNormal (index, proj.point, proj.normal, mls_result.curvature, projected_points, projected_points_normals, corresponding_input_indices);
235 
236  num_added++;
237  }
238  }
239  break;
240  }
241 
242  default:
243  break;
244  }
245 }
246 
247 template <typename PointInT, typename PointOutT> void
249  const Eigen::Vector3d &point,
250  const Eigen::Vector3d &normal,
251  double curvature,
252  PointCloudOut &projected_points,
253  NormalCloud &projected_points_normals,
254  PointIndices &corresponding_input_indices) const
255 {
256  PointOutT aux;
257  aux.x = static_cast<float> (point[0]);
258  aux.y = static_cast<float> (point[1]);
259  aux.z = static_cast<float> (point[2]);
260 
261  // Copy additional point information if available
262  copyMissingFields (input_->points[index], aux);
263 
264  projected_points.push_back (aux);
265  corresponding_input_indices.indices.push_back (index);
266 
267  if (compute_normals_)
268  {
269  pcl::Normal aux_normal;
270  aux_normal.normal_x = static_cast<float> (normal[0]);
271  aux_normal.normal_y = static_cast<float> (normal[1]);
272  aux_normal.normal_z = static_cast<float> (normal[2]);
273  aux_normal.curvature = curvature;
274  projected_points_normals.push_back (aux_normal);
275  }
276 }
277 
278 //////////////////////////////////////////////////////////////////////////////////////////////
279 template <typename PointInT, typename PointOutT> void
281 {
282  // Compute the number of coefficients
283  nr_coeff_ = (order_ + 1) * (order_ + 2) / 2;
284 
285 #ifdef _OPENMP
286  // (Maximum) number of threads
287  const unsigned int threads = threads_ == 0 ? 1 : threads_;
288  // Create temporaries for each thread in order to avoid synchronization
289  typename PointCloudOut::CloudVectorType projected_points (threads);
290  typename NormalCloud::CloudVectorType projected_points_normals (threads);
291  std::vector<PointIndices> corresponding_input_indices (threads);
292 #endif
293 
294  // For all points
295 #ifdef _OPENMP
296 #pragma omp parallel for schedule (dynamic,1000) num_threads (threads)
297 #endif
298  for (int cp = 0; cp < static_cast<int> (indices_->size ()); ++cp)
299  {
300  // Allocate enough space to hold the results of nearest neighbor searches
301  // \note resize is irrelevant for a radiusSearch ().
302  std::vector<int> nn_indices;
303  std::vector<float> nn_sqr_dists;
304 
305  // Get the initial estimates of point positions and their neighborhoods
306  if (searchForNeighbors ((*indices_)[cp], nn_indices, nn_sqr_dists))
307  {
308  // Check the number of nearest neighbors for normal estimation (and later for polynomial fit as well)
309  if (nn_indices.size () >= 3)
310  {
311  // This thread's ID (range 0 to threads-1)
312 #ifdef _OPENMP
313  const int tn = omp_get_thread_num ();
314  // Size of projected points before computeMLSPointNormal () adds points
315  size_t pp_size = projected_points[tn].size ();
316 #else
317  PointCloudOut projected_points;
318  NormalCloud projected_points_normals;
319 #endif
320 
321  // Get a plane approximating the local surface's tangent and project point onto it
322  const int index = (*indices_)[cp];
323 
324  size_t mls_result_index = 0;
325  if (cache_mls_results_)
326  mls_result_index = index; // otherwise we give it a dummy location.
327 
328 #ifdef _OPENMP
329  computeMLSPointNormal (index, nn_indices, projected_points[tn], projected_points_normals[tn], corresponding_input_indices[tn], mls_results_[mls_result_index]);
330 
331  // Copy all information from the input cloud to the output points (not doing any interpolation)
332  for (size_t pp = pp_size; pp < projected_points[tn].size (); ++pp)
333  copyMissingFields (input_->points[(*indices_)[cp]], projected_points[tn][pp]);
334 #else
335  computeMLSPointNormal (index, nn_indices, projected_points, projected_points_normals, *corresponding_input_indices_, mls_results_[mls_result_index]);
336 
337  // Append projected points to output
338  output.insert (output.end (), projected_points.begin (), projected_points.end ());
339  if (compute_normals_)
340  normals_->insert (normals_->end (), projected_points_normals.begin (), projected_points_normals.end ());
341 #endif
342  }
343  }
344  }
345 
346 #ifdef _OPENMP
347  // Combine all threads' results into the output vectors
348  for (unsigned int tn = 0; tn < threads; ++tn)
349  {
350  output.insert (output.end (), projected_points[tn].begin (), projected_points[tn].end ());
351  corresponding_input_indices_->indices.insert (corresponding_input_indices_->indices.end (),
352  corresponding_input_indices[tn].indices.begin (), corresponding_input_indices[tn].indices.end ());
353  if (compute_normals_)
354  normals_->insert (normals_->end (), projected_points_normals[tn].begin (), projected_points_normals[tn].end ());
355  }
356 #endif
357 
358  // Perform the distinct-cloud or voxel-grid upsampling
359  performUpsampling (output);
360 }
361 
362 //////////////////////////////////////////////////////////////////////////////////////////////
363 template <typename PointInT, typename PointOutT> void
365 {
366 
367  if (upsample_method_ == DISTINCT_CLOUD)
368  {
369  corresponding_input_indices_.reset (new PointIndices);
370  for (size_t dp_i = 0; dp_i < distinct_cloud_->size (); ++dp_i) // dp_i = distinct_point_i
371  {
372  // Distinct cloud may have nan points, skip them
373  if (!std::isfinite (distinct_cloud_->points[dp_i].x))
374  continue;
375 
376  // Get 3D position of point
377  //Eigen::Vector3f pos = distinct_cloud_->points[dp_i].getVector3fMap ();
378  std::vector<int> nn_indices;
379  std::vector<float> nn_dists;
380  tree_->nearestKSearch (distinct_cloud_->points[dp_i], 1, nn_indices, nn_dists);
381  int input_index = nn_indices.front ();
382 
383  // If the closest point did not have a valid MLS fitting result
384  // OR if it is too far away from the sampled point
385  if (mls_results_[input_index].valid == false)
386  continue;
387 
388  Eigen::Vector3d add_point = distinct_cloud_->points[dp_i].getVector3fMap ().template cast<double> ();
389  MLSResult::MLSProjectionResults proj = mls_results_[input_index].projectPoint (add_point, projection_method_, 5 * nr_coeff_);
390  addProjectedPointNormal (input_index, proj.point, proj.normal, mls_results_[input_index].curvature, output, *normals_, *corresponding_input_indices_);
391  }
392  }
393 
394  // For the voxel grid upsampling method, generate the voxel grid and dilate it
395  // Then, project the newly obtained points to the MLS surface
396  if (upsample_method_ == VOXEL_GRID_DILATION)
397  {
398  corresponding_input_indices_.reset (new PointIndices);
399 
400  MLSVoxelGrid voxel_grid (input_, indices_, voxel_size_);
401  for (int iteration = 0; iteration < dilation_iteration_num_; ++iteration)
402  voxel_grid.dilate ();
403 
404  for (typename MLSVoxelGrid::HashMap::iterator m_it = voxel_grid.voxel_grid_.begin (); m_it != voxel_grid.voxel_grid_.end (); ++m_it)
405  {
406  // Get 3D position of point
407  Eigen::Vector3f pos;
408  voxel_grid.getPosition (m_it->first, pos);
409 
410  PointInT p;
411  p.x = pos[0];
412  p.y = pos[1];
413  p.z = pos[2];
414 
415  std::vector<int> nn_indices;
416  std::vector<float> nn_dists;
417  tree_->nearestKSearch (p, 1, nn_indices, nn_dists);
418  int input_index = nn_indices.front ();
419 
420  // If the closest point did not have a valid MLS fitting result
421  // OR if it is too far away from the sampled point
422  if (mls_results_[input_index].valid == false)
423  continue;
424 
425  Eigen::Vector3d add_point = p.getVector3fMap ().template cast<double> ();
426  MLSResult::MLSProjectionResults proj = mls_results_[input_index].projectPoint (add_point, projection_method_, 5 * nr_coeff_);
427  addProjectedPointNormal (input_index, proj.point, proj.normal, mls_results_[input_index].curvature, output, *normals_, *corresponding_input_indices_);
428  }
429  }
430 }
431 
432 //////////////////////////////////////////////////////////////////////////////////////////////
433 pcl::MLSResult::MLSResult (const Eigen::Vector3d &a_query_point,
434  const Eigen::Vector3d &a_mean,
435  const Eigen::Vector3d &a_plane_normal,
436  const Eigen::Vector3d &a_u,
437  const Eigen::Vector3d &a_v,
438  const Eigen::VectorXd &a_c_vec,
439  const int a_num_neighbors,
440  const float a_curvature,
441  const int a_order) :
442  query_point (a_query_point), mean (a_mean), plane_normal (a_plane_normal), u_axis (a_u), v_axis (a_v), c_vec (a_c_vec), num_neighbors (a_num_neighbors),
443  curvature (a_curvature), order (a_order), valid (true)
444 {}
445 
446 void
447 pcl::MLSResult::getMLSCoordinates (const Eigen::Vector3d &pt, double &u, double &v, double &w) const
448 {
449  Eigen::Vector3d delta = pt - mean;
450  u = delta.dot (u_axis);
451  v = delta.dot (v_axis);
452  w = delta.dot (plane_normal);
453 }
454 
455 void
456 pcl::MLSResult::getMLSCoordinates (const Eigen::Vector3d &pt, double &u, double &v) const
457 {
458  Eigen::Vector3d delta = pt - mean;
459  u = delta.dot (u_axis);
460  v = delta.dot (v_axis);
461 }
462 
463 double
464 pcl::MLSResult::getPolynomialValue (const double u, const double v) const
465 {
466  // Compute the polynomial's terms at the current point
467  // Example for second order: z = a + b*y + c*y^2 + d*x + e*x*y + f*x^2
468  int j = 0;
469  double u_pow = 1;
470  double result = 0;
471  for (int ui = 0; ui <= order; ++ui)
472  {
473  double v_pow = 1;
474  for (int vi = 0; vi <= order - ui; ++vi)
475  {
476  result += c_vec[j++] * u_pow * v_pow;
477  v_pow *= v;
478  }
479  u_pow *= u;
480  }
481 
482  return (result);
483 }
484 
486 pcl::MLSResult::getPolynomialPartialDerivative (const double u, const double v) const
487 {
488  // Compute the displacement along the normal using the fitted polynomial
489  // and compute the partial derivatives needed for estimating the normal
491  Eigen::VectorXd u_pow (order + 2), v_pow (order + 2);
492  int j = 0;
493 
494  d.z = d.z_u = d.z_v = d.z_uu = d.z_vv = d.z_uv = 0;
495  u_pow (0) = v_pow (0) = 1;
496  for (int ui = 0; ui <= order; ++ui)
497  {
498  for (int vi = 0; vi <= order - ui; ++vi)
499  {
500  // Compute displacement along normal
501  d.z += u_pow (ui) * v_pow (vi) * c_vec[j];
502 
503  // Compute partial derivatives
504  if (ui >= 1)
505  d.z_u += c_vec[j] * ui * u_pow (ui - 1) * v_pow (vi);
506 
507  if (vi >= 1)
508  d.z_v += c_vec[j] * vi * u_pow (ui) * v_pow (vi - 1);
509 
510  if (ui >= 1 && vi >= 1)
511  d.z_uv += c_vec[j] * ui * u_pow (ui - 1) * vi * v_pow (vi - 1);
512 
513  if (ui >= 2)
514  d.z_uu += c_vec[j] * ui * (ui - 1) * u_pow (ui - 2) * v_pow (vi);
515 
516  if (vi >= 2)
517  d.z_vv += c_vec[j] * vi * (vi - 1) * u_pow (ui) * v_pow (vi - 2);
518 
519  if (ui == 0)
520  v_pow (vi + 1) = v_pow (vi) * v;
521 
522  ++j;
523  }
524  u_pow (ui + 1) = u_pow (ui) * u;
525  }
526 
527  return (d);
528 }
529 
530 Eigen::Vector2f
531 pcl::MLSResult::calculatePrincipleCurvatures (const double u, const double v) const
532 {
533  Eigen::Vector2f k (1e-5, 1e-5);
534 
535  // Note: this use the Monge Patch to derive the Gaussian curvature and Mean Curvature found here http://mathworld.wolfram.com/MongePatch.html
536  // Then:
537  // k1 = H + sqrt(H^2 - K)
538  // k1 = H - sqrt(H^2 - K)
539  if (order > 1 && c_vec.size () >= (order + 1) * (order + 2) / 2 && std::isfinite (c_vec[0]))
540  {
542  const double Z = 1 + d.z_u * d.z_u + d.z_v * d.z_v;
543  const double Zlen = std::sqrt (Z);
544  const double K = (d.z_uu * d.z_vv - d.z_uv * d.z_uv) / (Z * Z);
545  const double H = ((1.0 + d.z_v * d.z_v) * d.z_uu - 2.0 * d.z_u * d.z_v * d.z_uv + (1.0 + d.z_u * d.z_u) * d.z_vv) / (2.0 * Zlen * Zlen * Zlen);
546  const double disc2 = H * H - K;
547  assert (disc2 >= 0.0);
548  const double disc = std::sqrt (disc2);
549  k[0] = H + disc;
550  k[1] = H - disc;
551 
552  if (std::abs (k[0]) > std::abs (k[1])) std::swap (k[0], k[1]);
553  }
554  else
555  {
556  PCL_ERROR ("No Polynomial fit data, unable to calculate the principle curvatures!\n");
557  }
558 
559  return (k);
560 }
561 
563 pcl::MLSResult::projectPointOrthogonalToPolynomialSurface (const double u, const double v, const double w) const
564 {
565  double gu = u;
566  double gv = v;
567  double gw = 0;
568 
569  MLSProjectionResults result;
570  result.normal = plane_normal;
571  if (order > 1 && c_vec.size () >= (order + 1) * (order + 2) / 2 && std::isfinite (c_vec[0]))
572  {
574  gw = d.z;
575  double err_total;
576  const double dist1 = std::abs (gw - w);
577  double dist2;
578  do
579  {
580  double e1 = (gu - u) + d.z_u * gw - d.z_u * w;
581  double e2 = (gv - v) + d.z_v * gw - d.z_v * w;
582 
583  const double F1u = 1 + d.z_uu * gw + d.z_u * d.z_u - d.z_uu * w;
584  const double F1v = d.z_uv * gw + d.z_u * d.z_v - d.z_uv * w;
585 
586  const double F2u = d.z_uv * gw + d.z_v * d.z_u - d.z_uv * w;
587  const double F2v = 1 + d.z_vv * gw + d.z_v * d.z_v - d.z_vv * w;
588 
589  Eigen::MatrixXd J (2, 2);
590  J (0, 0) = F1u;
591  J (0, 1) = F1v;
592  J (1, 0) = F2u;
593  J (1, 1) = F2v;
594 
595  Eigen::Vector2d err (e1, e2);
596  Eigen::Vector2d update = J.inverse () * err;
597  gu -= update (0);
598  gv -= update (1);
599 
600  d = getPolynomialPartialDerivative (gu, gv);
601  gw = d.z;
602  dist2 = std::sqrt ((gu - u) * (gu - u) + (gv - v) * (gv - v) + (gw - w) * (gw - w));
603 
604  err_total = std::sqrt (e1 * e1 + e2 * e2);
605 
606  } while (err_total > 1e-8 && dist2 < dist1);
607 
608  if (dist2 > dist1) // the optimization was diverging reset the coordinates for simple projection
609  {
610  gu = u;
611  gv = v;
613  gw = d.z;
614  }
615 
616  result.u = gu;
617  result.v = gv;
618  result.normal -= (d.z_u * u_axis + d.z_v * v_axis);
619  result.normal.normalize ();
620  }
621 
622  result.point = mean + gu * u_axis + gv * v_axis + gw * plane_normal;
623 
624  return (result);
625 }
626 
628 pcl::MLSResult::projectPointToMLSPlane (const double u, const double v) const
629 {
630  MLSProjectionResults result;
631  result.u = u;
632  result.v = v;
633  result.normal = plane_normal;
634  result.point = mean + u * u_axis + v * v_axis;
635 
636  return (result);
637 }
638 
640 pcl::MLSResult::projectPointSimpleToPolynomialSurface (const double u, const double v) const
641 {
642  MLSProjectionResults result;
643  double w = 0;
644 
645  result.u = u;
646  result.v = v;
647  result.normal = plane_normal;
648 
649  if (order > 1 && c_vec.size () >= (order + 1) * (order + 2) / 2 && std::isfinite (c_vec[0]))
650  {
652  w = d.z;
653  result.normal -= (d.z_u * u_axis + d.z_v * v_axis);
654  result.normal.normalize ();
655  }
656 
657  result.point = mean + u * u_axis + v * v_axis + w * plane_normal;
658 
659  return (result);
660 }
661 
663 pcl::MLSResult::projectPoint (const Eigen::Vector3d &pt, ProjectionMethod method, int required_neighbors) const
664 {
665  double u, v, w;
666  getMLSCoordinates (pt, u, v, w);
667 
669  if (order > 1 && num_neighbors >= required_neighbors && std::isfinite (c_vec[0]) && method != NONE)
670  {
671  if (method == ORTHOGONAL)
673  else // SIMPLE
675  }
676  else
677  {
678  proj = projectPointToMLSPlane (u, v);
679  }
680 
681  return (proj);
682 }
683 
685 pcl::MLSResult::projectQueryPoint (ProjectionMethod method, int required_neighbors) const
686 {
688  if (order > 1 && num_neighbors >= required_neighbors && std::isfinite (c_vec[0]) && method != NONE)
689  {
690  if (method == ORTHOGONAL)
691  {
692  double u, v, w;
693  getMLSCoordinates (query_point, u, v, w);
695  }
696  else // SIMPLE
697  {
698  // Projection onto MLS surface along Darboux normal to the height at (0,0)
699  proj.point = mean + (c_vec[0] * plane_normal);
700 
701  // Compute tangent vectors using the partial derivates evaluated at (0,0) which is c_vec[order_+1] and c_vec[1]
702  proj.normal = plane_normal - c_vec[order + 1] * u_axis - c_vec[1] * v_axis;
703  proj.normal.normalize ();
704  }
705  }
706  else
707  {
708  proj.normal = plane_normal;
709  proj.point = mean;
710  }
711 
712  return (proj);
713 }
714 
715 template <typename PointT> void
717  int index,
718  const std::vector<int> &nn_indices,
719  double search_radius,
720  int polynomial_order,
721  std::function<double(const double)> weight_func)
722 {
723  // Compute the plane coefficients
724  EIGEN_ALIGN16 Eigen::Matrix3d covariance_matrix;
725  Eigen::Vector4d xyz_centroid;
726 
727  // Estimate the XYZ centroid
728  pcl::compute3DCentroid (cloud, nn_indices, xyz_centroid);
729 
730  // Compute the 3x3 covariance matrix
731  pcl::computeCovarianceMatrix (cloud, nn_indices, xyz_centroid, covariance_matrix);
732  EIGEN_ALIGN16 Eigen::Vector3d::Scalar eigen_value;
733  EIGEN_ALIGN16 Eigen::Vector3d eigen_vector;
734  Eigen::Vector4d model_coefficients (0, 0, 0, 0);
735  pcl::eigen33 (covariance_matrix, eigen_value, eigen_vector);
736  model_coefficients.head<3> ().matrix () = eigen_vector;
737  model_coefficients[3] = -1 * model_coefficients.dot (xyz_centroid);
738 
739  query_point = cloud.points[index].getVector3fMap ().template cast<double> ();
740 
741  if (!std::isfinite(eigen_vector[0]) || !std::isfinite(eigen_vector[1]) || !std::isfinite(eigen_vector[2]))
742  {
743  // Invalid plane coefficients, this may happen if the input cloud is non-dense (it contains invalid points).
744  // Keep the input point and stop here.
745  valid = false;
746  mean = query_point;
747  return;
748  }
749 
750  // Projected query point
751  valid = true;
752  const double distance = query_point.dot (model_coefficients.head<3> ()) + model_coefficients[3];
753  mean = query_point - distance * model_coefficients.head<3> ();
754 
755  curvature = covariance_matrix.trace ();
756  // Compute the curvature surface change
757  if (curvature != 0)
758  curvature = std::abs (eigen_value / curvature);
759 
760  // Get a copy of the plane normal easy access
761  plane_normal = model_coefficients.head<3> ();
762 
763  // Local coordinate system (Darboux frame)
764  v_axis = plane_normal.unitOrthogonal ();
765  u_axis = plane_normal.cross (v_axis);
766 
767  // Perform polynomial fit to update point and normal
768  ////////////////////////////////////////////////////
769  num_neighbors = static_cast<int> (nn_indices.size ());
770  order = polynomial_order;
771  if (order > 1)
772  {
773  const int nr_coeff = (order + 1) * (order + 2) / 2;
774 
775  if (num_neighbors >= nr_coeff)
776  {
777  if (!weight_func)
778  weight_func = [=] (const double sq_dist) { return this->computeMLSWeight (sq_dist, search_radius * search_radius); };
779 
780  // Allocate matrices and vectors to hold the data used for the polynomial fit
781  Eigen::VectorXd weight_vec (num_neighbors);
782  Eigen::MatrixXd P (nr_coeff, num_neighbors);
783  Eigen::VectorXd f_vec (num_neighbors);
784  Eigen::MatrixXd P_weight_Pt (nr_coeff, nr_coeff);
785 
786  // Update neighborhood, since point was projected, and computing relative
787  // positions. Note updating only distances for the weights for speed
788  std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d> > de_meaned (num_neighbors);
789  for (size_t ni = 0; ni < static_cast<size_t>(num_neighbors); ++ni)
790  {
791  de_meaned[ni][0] = cloud.points[nn_indices[ni]].x - mean[0];
792  de_meaned[ni][1] = cloud.points[nn_indices[ni]].y - mean[1];
793  de_meaned[ni][2] = cloud.points[nn_indices[ni]].z - mean[2];
794  weight_vec (ni) = weight_func (de_meaned[ni].dot (de_meaned[ni]));
795  }
796 
797  // Go through neighbors, transform them in the local coordinate system,
798  // save height and the evaluation of the polynome's terms
799  for (size_t ni = 0; ni < static_cast<size_t>(num_neighbors); ++ni)
800  {
801  // Transforming coordinates
802  const double u_coord = de_meaned[ni].dot(u_axis);
803  const double v_coord = de_meaned[ni].dot(v_axis);
804  f_vec (ni) = de_meaned[ni].dot (plane_normal);
805 
806  // Compute the polynomial's terms at the current point
807  int j = 0;
808  double u_pow = 1;
809  for (int ui = 0; ui <= order; ++ui)
810  {
811  double v_pow = 1;
812  for (int vi = 0; vi <= order - ui; ++vi)
813  {
814  P (j++, ni) = u_pow * v_pow;
815  v_pow *= v_coord;
816  }
817  u_pow *= u_coord;
818  }
819  }
820 
821  // Computing coefficients
822  const Eigen::MatrixXd P_weight = P * weight_vec.asDiagonal(); // size will be (nr_coeff_, nn_indices.size ());
823  P_weight_Pt = P_weight * P.transpose ();
824  c_vec = P_weight * f_vec;
825  P_weight_Pt.llt ().solveInPlace (c_vec);
826  }
827  }
828 }
829 
830 //////////////////////////////////////////////////////////////////////////////////////////////
831 template <typename PointInT, typename PointOutT>
833  IndicesPtr &indices,
834  float voxel_size) :
835  voxel_grid_ (), data_size_ (), voxel_size_ (voxel_size)
836 {
837  pcl::getMinMax3D (*cloud, *indices, bounding_min_, bounding_max_);
838 
839  Eigen::Vector4f bounding_box_size = bounding_max_ - bounding_min_;
840  const double max_size = (std::max) ((std::max)(bounding_box_size.x (), bounding_box_size.y ()), bounding_box_size.z ());
841  // Put initial cloud in voxel grid
842  data_size_ = static_cast<uint64_t> (1.5 * max_size / voxel_size_);
843  for (size_t i = 0; i < indices->size (); ++i)
844  if (std::isfinite (cloud->points[(*indices)[i]].x))
845  {
846  Eigen::Vector3i pos;
847  getCellIndex (cloud->points[(*indices)[i]].getVector3fMap (), pos);
848 
849  uint64_t index_1d;
850  getIndexIn1D (pos, index_1d);
851  Leaf leaf;
852  voxel_grid_[index_1d] = leaf;
853  }
854 }
855 
856 //////////////////////////////////////////////////////////////////////////////////////////////
857 template <typename PointInT, typename PointOutT> void
859 {
860  HashMap new_voxel_grid = voxel_grid_;
861  for (typename MLSVoxelGrid::HashMap::iterator m_it = voxel_grid_.begin (); m_it != voxel_grid_.end (); ++m_it)
862  {
863  Eigen::Vector3i index;
864  getIndexIn3D (m_it->first, index);
865 
866  // Now dilate all of its voxels
867  for (int x = -1; x <= 1; ++x)
868  for (int y = -1; y <= 1; ++y)
869  for (int z = -1; z <= 1; ++z)
870  if (x != 0 || y != 0 || z != 0)
871  {
872  Eigen::Vector3i new_index;
873  new_index = index + Eigen::Vector3i (x, y, z);
874 
875  uint64_t index_1d;
876  getIndexIn1D (new_index, index_1d);
877  Leaf leaf;
878  new_voxel_grid[index_1d] = leaf;
879  }
880  }
881  voxel_grid_ = new_voxel_grid;
882 }
883 
884 
885 /////////////////////////////////////////////////////////////////////////////////////////////
886 template <typename PointInT, typename PointOutT> void
888  PointOutT &point_out) const
889 {
890  PointOutT temp = point_out;
891  copyPoint (point_in, point_out);
892  point_out.x = temp.x;
893  point_out.y = temp.y;
894  point_out.z = temp.z;
895 }
896 
897 #define PCL_INSTANTIATE_MovingLeastSquares(T,OutT) template class PCL_EXPORTS pcl::MovingLeastSquares<T,OutT>;
898 #define PCL_INSTANTIATE_MovingLeastSquaresOMP(T,OutT) template class PCL_EXPORTS pcl::MovingLeastSquaresOMP<T,OutT>;
899 
900 #endif // PCL_SURFACE_IMPL_MLS_H_
A point structure representing normal coordinates and the surface curvature estimate.
Data structure used to store the MLS polynomial partial derivatives.
Definition: mls.h:70
bool valid
If True, the mls results data is valid, otherwise False.
Definition: mls.h:224
Eigen::Vector3d plane_normal
The normal of the local plane of the query point.
Definition: mls.h:217
void addProjectedPointNormal(int index, const Eigen::Vector3d &point, const Eigen::Vector3d &normal, double curvature, PointCloudOut &projected_points, NormalCloud &projected_points_normals, PointIndices &corresponding_input_indices) const
This is a helper function for add projected points.
Definition: mls.hpp:248
double z_u
The partial derivative dz/du.
Definition: mls.h:73
MLSResult()
Definition: mls.h:93
typename PointCloudIn::ConstPtr PointCloudInConstPtr
Definition: mls.h:275
search::KdTree is a wrapper class which inherits the pcl::KdTree class for performing search function...
Definition: kdtree.h:61
A helper functor that can set a specific value in a field if the field exists.
Definition: point_traits.h:283
std::vector< PointT, Eigen::aligned_allocator< PointT > > points
The point data.
Definition: point_cloud.h:426
Eigen::VectorXd c_vec
The polynomial coefficients Example: z = c_vec[0] + c_vec[1]*v + c_vec[2]*v^2 + c_vec[3]*u + c_vec[4]...
Definition: mls.h:220
double u
The u-coordinate of the projected point in local MLS frame.
Definition: mls.h:85
Eigen::Vector2f calculatePrincipleCurvatures(const double u, const double v) const
Calculate the principle curvatures using the polynomial surface.
Definition: mls.hpp:531
void getIndexIn1D(const Eigen::Vector3i &index, uint64_t &index_1d) const
Definition: mls.h:615
PolynomialPartialDerivative getPolynomialPartialDerivative(const double u, const double v) const
Calculate the polynomial&#39;s first and second partial derivatives.
Definition: mls.hpp:486
ProjectionMethod
Definition: mls.h:62
double z_vv
The partial derivative d^2z/dv^2.
Definition: mls.h:76
iterator end()
Definition: point_cloud.h:459
Defines some geometrical functions and utility functions.
Eigen::Vector4f bounding_max_
Definition: mls.h:649
std::size_t size() const
Definition: point_cloud.h:464
std::vector< int > indices
Definition: PointIndices.h:19
void push_back(const PointT &pt)
Insert a new point in the cloud, at the end of the container.
Definition: point_cloud.h:496
double z_uv
The partial derivative d^2z/dudv.
Definition: mls.h:77
void copyMissingFields(const PointInT &point_in, PointOutT &point_out) const
Definition: mls.hpp:887
MLSProjectionResults projectQueryPoint(ProjectionMethod method, int required_neighbors=0) const
Project the query point used to generate the mls surface about using the specified method...
Definition: mls.hpp:685
Project to the closest point on the polynonomial surface.
Definition: mls.h:66
void process(PointCloudOut &output) override
Base method for surface reconstruction for all points given in <setInputCloud (), setIndices ()> ...
Definition: mls.hpp:57
uint32_t height
The point cloud height (if organized as an image-structure).
Definition: point_cloud.h:431
int order
The order of the polynomial.
Definition: mls.h:223
Eigen::Vector4f bounding_min_
Definition: mls.h:649
MLSProjectionResults projectPointSimpleToPolynomialSurface(const double u, const double v) const
Project a point along the MLS plane normal to the polynomial surface.
Definition: mls.hpp:640
MLSProjectionResults projectPoint(const Eigen::Vector3d &pt, ProjectionMethod method, int required_neighbors=0) const
Project a point using the specified method.
Definition: mls.hpp:663
double z_uu
The partial derivative d^2z/du^2.
Definition: mls.h:75
Data structure used to store the MLS projection results.
Definition: mls.h:81
Eigen::Vector3d point
The projected point.
Definition: mls.h:87
uint32_t width
The point cloud width (if organized as an image-structure).
Definition: point_cloud.h:429
double v
The u-coordinate of the projected point in local MLS frame.
Definition: mls.h:86
double z_v
The partial derivative dz/dv.
Definition: mls.h:74
boost::shared_ptr< Indices > IndicesPtr
Definition: pcl_base.h:61
Eigen::Vector3d normal
The projected point&#39;s normal.
Definition: mls.h:88
void getMLSCoordinates(const Eigen::Vector3d &pt, double &u, double &v, double &w) const
Given a point calculate it&#39;s 3D location in the MLS frame.
Definition: mls.hpp:447
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.
Data structure used to store the results of the MLS fitting.
Definition: mls.h:60
int num_neighbors
The number of neighbors used to create the mls surface.
Definition: mls.h:221
void performUpsampling(PointCloudOut &output)
Perform upsampling for the distinct-cloud and voxel-grid methods.
Definition: mls.hpp:364
std::vector< PointCloud< PointOutT >, Eigen::aligned_allocator< PointCloud< PointOutT > > > CloudVectorType
Definition: point_cloud.h:443
void getMinMax3D(const pcl::PointCloud< PointT > &cloud, PointT &min_pt, PointT &max_pt)
Get the minimum and maximum values on each of the 3 (x-y-z) dimensions in a given pointcloud...
Definition: common.hpp:242
float distance(const PointT &p1, const PointT &p2)
Definition: geometry.h:60
Eigen::Vector3d u_axis
The axis corresponding to the u-coordinates of the local plane of the query point.
Definition: mls.h:218
Eigen::Vector3d mean
The mean point of all the neighbors.
Definition: mls.h:216
Eigen::Vector3d v_axis
The axis corresponding to the v-coordinates of the local plane of the query point.
Definition: mls.h:219
Project to the mls plane.
Definition: mls.h:64
Eigen::Vector3d query_point
The query point about which the mls surface was generated.
Definition: mls.h:215
pcl::PCLHeader header
The point cloud header.
Definition: point_cloud.h:423
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:253
void performProcessing(PointCloudOut &output) override
Abstract surface reconstruction method.
Definition: mls.hpp:280
Definition: norms.h:54
A minimalistic implementation of a voxel grid, necessary for the point cloud upsampling.
Definition: mls.h:602
MLSVoxelGrid(PointCloudInConstPtr &cloud, IndicesPtr &indices, float voxel_size)
Definition: mls.hpp:832
void computeMLSSurface(const pcl::PointCloud< PointT > &cloud, int index, const std::vector< int > &nn_indices, double search_radius, int polynomial_order=2, std::function< double(const double)> weight_func={})
Smooth a given point and its neighborghood using Moving Least Squares.
Definition: mls.hpp:716
OrganizedNeighbor is a class for optimized nearest neigbhor search in organized point clouds...
Definition: organized.h:62
void getIndexIn3D(uint64_t index_1d, Eigen::Vector3i &index_3d) const
Definition: mls.h:622
void getPosition(const uint64_t &index_1d, Eigen::Vector3f &point) const
Definition: mls.h:639
float curvature
The curvature at the query point.
Definition: mls.h:222
iterator begin()
Definition: point_cloud.h:458
MLSProjectionResults projectPointOrthogonalToPolynomialSurface(const double u, const double v, const double w) const
Project a point orthogonal to the polynomial surface.
Definition: mls.hpp:563
double getPolynomialValue(const double u, const double v) const
Calculate the polynomial.
Definition: mls.hpp:464
void computeMLSPointNormal(int index, const std::vector< int > &nn_indices, PointCloudOut &projected_points, NormalCloud &projected_points_normals, PointIndices &corresponding_input_indices, MLSResult &mls_result) const
Smooth a given point and its neighborghood using Moving Least Squares.
Definition: mls.hpp:170
double z
The z component of the polynomial evaluated at z(u, v).
Definition: mls.h:72
MLSProjectionResults projectPointToMLSPlane(const double u, const double v) const
Project a point onto the MLS plane.
Definition: mls.hpp:628
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
iterator insert(iterator position, const PointT &pt)
Insert a new point in the cloud, given an iterator.
Definition: point_cloud.h:524
void copyPoint(const PointInT &point_in, PointOutT &point_out)
Copy the fields of a source point into a target point.
Definition: copy_point.hpp:138
typename KdTree::Ptr KdTreePtr
Definition: mls.h:265
void getCellIndex(const Eigen::Vector3f &p, Eigen::Vector3i &index) const
Definition: mls.h:632
Define methods for centroid estimation and covariance matrix calculus.
std::map< uint64_t, Leaf > HashMap
Definition: mls.h:647