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