Point Cloud Library (PCL)  1.11.1-dev
convex_hull.hpp
1 /*
2  * Software License Agreement (BSD License)
3  *
4  * Point Cloud Library (PCL) - www.pointclouds.org
5  * Copyright (c) 2010-2012, 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 #include <pcl/pcl_config.h>
41 #ifdef HAVE_QHULL
42 
43 #ifndef PCL_SURFACE_IMPL_CONVEX_HULL_H_
44 #define PCL_SURFACE_IMPL_CONVEX_HULL_H_
45 
46 #include <pcl/surface/convex_hull.h>
47 #include <pcl/common/common.h>
48 #include <pcl/common/eigen.h>
49 #include <pcl/common/transforms.h>
50 #include <pcl/common/io.h>
51 #include <cstdio>
52 #include <cstdlib>
53 #include <pcl/surface/qhull.h>
54 
55 //////////////////////////////////////////////////////////////////////////
56 template <typename PointInT> void
58 {
59  PCL_DEBUG ("[pcl::%s::calculateInputDimension] WARNING: Input dimension not specified. Automatically determining input dimension.\n", getClassName ().c_str ());
60  Eigen::Vector4d xyz_centroid;
61  compute3DCentroid (*input_, *indices_, xyz_centroid);
62  EIGEN_ALIGN16 Eigen::Matrix3d covariance_matrix = Eigen::Matrix3d::Zero ();
63  computeCovarianceMatrixNormalized (*input_, *indices_, xyz_centroid, covariance_matrix);
64 
65  EIGEN_ALIGN16 Eigen::Vector3d eigen_values;
66  pcl::eigen33 (covariance_matrix, eigen_values);
67 
68  if (std::abs (eigen_values[0]) < std::numeric_limits<double>::epsilon () || std::abs (eigen_values[0] / eigen_values[2]) < 1.0e-3)
69  dimension_ = 2;
70  else
71  dimension_ = 3;
72 }
73 
74 //////////////////////////////////////////////////////////////////////////
75 template <typename PointInT> void
76 pcl::ConvexHull<PointInT>::performReconstruction2D (PointCloud &hull, std::vector<pcl::Vertices> &polygons,
77  bool)
78 {
79  int dimension = 2;
80  bool xy_proj_safe = true;
81  bool yz_proj_safe = true;
82  bool xz_proj_safe = true;
83 
84  // Check the input's normal to see which projection to use
85  PointInT p0 = (*input_)[(*indices_)[0]];
86  PointInT p1 = (*input_)[(*indices_)[indices_->size () - 1]];
87  PointInT p2 = (*input_)[(*indices_)[indices_->size () / 2]];
88  Eigen::Array4f dy1dy2 = (p1.getArray4fMap () - p0.getArray4fMap ()) / (p2.getArray4fMap () - p0.getArray4fMap ());
89  while (!( (dy1dy2[0] != dy1dy2[1]) || (dy1dy2[2] != dy1dy2[1]) ) )
90  {
91  p0 = (*input_)[(*indices_)[rand () % indices_->size ()]];
92  p1 = (*input_)[(*indices_)[rand () % indices_->size ()]];
93  p2 = (*input_)[(*indices_)[rand () % indices_->size ()]];
94  dy1dy2 = (p1.getArray4fMap () - p0.getArray4fMap ()) / (p2.getArray4fMap () - p0.getArray4fMap ());
95  }
96 
97  pcl::PointCloud<PointInT> normal_calc_cloud;
98  normal_calc_cloud.resize (3);
99  normal_calc_cloud[0] = p0;
100  normal_calc_cloud[1] = p1;
101  normal_calc_cloud[2] = p2;
102 
103  Eigen::Vector4d normal_calc_centroid;
104  Eigen::Matrix3d normal_calc_covariance;
105  pcl::compute3DCentroid (normal_calc_cloud, normal_calc_centroid);
106  pcl::computeCovarianceMatrixNormalized (normal_calc_cloud, normal_calc_centroid, normal_calc_covariance);
107 
108  // Need to set -1 here. See eigen33 for explanations.
109  Eigen::Vector3d::Scalar eigen_value;
110  Eigen::Vector3d plane_params;
111  pcl::eigen33 (normal_calc_covariance, eigen_value, plane_params);
112  float theta_x = std::abs (static_cast<float> (plane_params.dot (x_axis_)));
113  float theta_y = std::abs (static_cast<float> (plane_params.dot (y_axis_)));
114  float theta_z = std::abs (static_cast<float> (plane_params.dot (z_axis_)));
115 
116  // Check for degenerate cases of each projection
117  // We must avoid projections in which the plane projects as a line
118  if (theta_z > projection_angle_thresh_)
119  {
120  xz_proj_safe = false;
121  yz_proj_safe = false;
122  }
123  if (theta_x > projection_angle_thresh_)
124  {
125  xz_proj_safe = false;
126  xy_proj_safe = false;
127  }
128  if (theta_y > projection_angle_thresh_)
129  {
130  xy_proj_safe = false;
131  yz_proj_safe = false;
132  }
133 
134  // True if qhull should free points in qh_freeqhull() or reallocation
135  boolT ismalloc = True;
136  // output from qh_produce_output(), use NULL to skip qh_produce_output()
137  FILE *outfile = nullptr;
138 
139 #ifndef HAVE_QHULL_2011
140  if (compute_area_)
141  outfile = stderr;
142 #endif
143 
144  // option flags for qhull, see qh_opt.htm
145  const char* flags = qhull_flags.c_str ();
146  // error messages from qhull code
147  FILE *errfile = stderr;
148 
149  // Array of coordinates for each point
150  coordT *points = reinterpret_cast<coordT*> (calloc (indices_->size () * dimension, sizeof (coordT)));
151 
152  // Build input data, using appropriate projection
153  int j = 0;
154  if (xy_proj_safe)
155  {
156  for (std::size_t i = 0; i < indices_->size (); ++i, j+=dimension)
157  {
158  points[j + 0] = static_cast<coordT> ((*input_)[(*indices_)[i]].x);
159  points[j + 1] = static_cast<coordT> ((*input_)[(*indices_)[i]].y);
160  }
161  }
162  else if (yz_proj_safe)
163  {
164  for (std::size_t i = 0; i < indices_->size (); ++i, j+=dimension)
165  {
166  points[j + 0] = static_cast<coordT> ((*input_)[(*indices_)[i]].y);
167  points[j + 1] = static_cast<coordT> ((*input_)[(*indices_)[i]].z);
168  }
169  }
170  else if (xz_proj_safe)
171  {
172  for (std::size_t i = 0; i < indices_->size (); ++i, j+=dimension)
173  {
174  points[j + 0] = static_cast<coordT> ((*input_)[(*indices_)[i]].x);
175  points[j + 1] = static_cast<coordT> ((*input_)[(*indices_)[i]].z);
176  }
177  }
178  else
179  {
180  // This should only happen if we had invalid input
181  PCL_ERROR ("[pcl::%s::performReconstruction2D] Invalid input!\n", getClassName ().c_str ());
182  }
183 
184  // Compute convex hull
185  int exitcode = qh_new_qhull (dimension, static_cast<int> (indices_->size ()), points, ismalloc, const_cast<char*> (flags), outfile, errfile);
186 #ifdef HAVE_QHULL_2011
187  if (compute_area_)
188  {
189  qh_prepare_output();
190  }
191 #endif
192 
193  // 0 if no error from qhull or it doesn't find any vertices
194  if (exitcode != 0 || qh num_vertices == 0)
195  {
196  PCL_ERROR ("[pcl::%s::performReconstrution2D] ERROR: qhull was unable to compute a convex hull for the given point cloud (%lu)!\n", getClassName ().c_str (), indices_->size ());
197 
198  hull.resize (0);
199  hull.width = hull.height = 0;
200  polygons.resize (0);
201 
202  qh_freeqhull (!qh_ALL);
203  int curlong, totlong;
204  qh_memfreeshort (&curlong, &totlong);
205 
206  return;
207  }
208 
209  // Qhull returns the area in volume for 2D
210  if (compute_area_)
211  {
212  total_area_ = qh totvol;
213  total_volume_ = 0.0;
214  }
215 
216  int num_vertices = qh num_vertices;
217  hull.resize (num_vertices);
218  memset (&hull.points[0], hull.size (), sizeof (PointInT));
219 
220  vertexT * vertex;
221  int i = 0;
222 
223  std::vector<std::pair<int, Eigen::Vector4f>, Eigen::aligned_allocator<std::pair<int, Eigen::Vector4f> > > idx_points (num_vertices);
224  idx_points.resize (hull.size ());
225  memset (&idx_points[0], hull.size (), sizeof (std::pair<int, Eigen::Vector4f>));
226 
227  FORALLvertices
228  {
229  hull[i] = (*input_)[(*indices_)[qh_pointid (vertex->point)]];
230  idx_points[i].first = qh_pointid (vertex->point);
231  ++i;
232  }
233 
234  // Sort
235  Eigen::Vector4f centroid;
236  pcl::compute3DCentroid (hull, centroid);
237  if (xy_proj_safe)
238  {
239  for (std::size_t j = 0; j < hull.size (); j++)
240  {
241  idx_points[j].second[0] = hull[j].x - centroid[0];
242  idx_points[j].second[1] = hull[j].y - centroid[1];
243  }
244  }
245  else if (yz_proj_safe)
246  {
247  for (std::size_t j = 0; j < hull.size (); j++)
248  {
249  idx_points[j].second[0] = hull[j].y - centroid[1];
250  idx_points[j].second[1] = hull[j].z - centroid[2];
251  }
252  }
253  else if (xz_proj_safe)
254  {
255  for (std::size_t j = 0; j < hull.size (); j++)
256  {
257  idx_points[j].second[0] = hull[j].x - centroid[0];
258  idx_points[j].second[1] = hull[j].z - centroid[2];
259  }
260  }
261  std::sort (idx_points.begin (), idx_points.end (), comparePoints2D);
262 
263  polygons.resize (1);
264  polygons[0].vertices.resize (hull.size ());
265 
266  hull_indices_.header = input_->header;
267  hull_indices_.indices.clear ();
268  hull_indices_.indices.reserve (hull.size ());
269 
270  for (int j = 0; j < static_cast<int> (hull.size ()); j++)
271  {
272  hull_indices_.indices.push_back ((*indices_)[idx_points[j].first]);
273  hull[j] = (*input_)[(*indices_)[idx_points[j].first]];
274  polygons[0].vertices[j] = static_cast<unsigned int> (j);
275  }
276 
277  qh_freeqhull (!qh_ALL);
278  int curlong, totlong;
279  qh_memfreeshort (&curlong, &totlong);
280 
281  hull.width = hull.size ();
282  hull.height = 1;
283  hull.is_dense = false;
284  return;
285 }
286 
287 #ifdef __GNUC__
288 #pragma GCC diagnostic ignored "-Wold-style-cast"
289 #endif
290 //////////////////////////////////////////////////////////////////////////
291 template <typename PointInT> void
293  PointCloud &hull, std::vector<pcl::Vertices> &polygons, bool fill_polygon_data)
294 {
295  int dimension = 3;
296 
297  // True if qhull should free points in qh_freeqhull() or reallocation
298  boolT ismalloc = True;
299  // output from qh_produce_output(), use NULL to skip qh_produce_output()
300  FILE *outfile = nullptr;
301 
302 #ifndef HAVE_QHULL_2011
303  if (compute_area_)
304  outfile = stderr;
305 #endif
306 
307  // option flags for qhull, see qh_opt.htm
308  const char *flags = qhull_flags.c_str ();
309  // error messages from qhull code
310  FILE *errfile = stderr;
311 
312  // Array of coordinates for each point
313  coordT *points = reinterpret_cast<coordT*> (calloc (indices_->size () * dimension, sizeof (coordT)));
314 
315  int j = 0;
316  for (std::size_t i = 0; i < indices_->size (); ++i, j+=dimension)
317  {
318  points[j + 0] = static_cast<coordT> ((*input_)[(*indices_)[i]].x);
319  points[j + 1] = static_cast<coordT> ((*input_)[(*indices_)[i]].y);
320  points[j + 2] = static_cast<coordT> ((*input_)[(*indices_)[i]].z);
321  }
322 
323  // Compute convex hull
324  int exitcode = qh_new_qhull (dimension, static_cast<int> (indices_->size ()), points, ismalloc, const_cast<char*> (flags), outfile, errfile);
325 #ifdef HAVE_QHULL_2011
326  if (compute_area_)
327  {
328  qh_prepare_output();
329  }
330 #endif
331 
332  // 0 if no error from qhull
333  if (exitcode != 0)
334  {
335  PCL_ERROR("[pcl::%s::performReconstrution3D] ERROR: qhull was unable to compute a "
336  "convex hull for the given point cloud (%zu)!\n",
337  getClassName().c_str(),
338  static_cast<std::size_t>(input_->size()));
339 
340  hull.resize (0);
341  hull.width = hull.height = 0;
342  polygons.resize (0);
343 
344  qh_freeqhull (!qh_ALL);
345  int curlong, totlong;
346  qh_memfreeshort (&curlong, &totlong);
347 
348  return;
349  }
350 
351  qh_triangulate ();
352 
353  int num_facets = qh num_facets;
354 
355  int num_vertices = qh num_vertices;
356  hull.resize (num_vertices);
357 
358  vertexT * vertex;
359  int i = 0;
360  // Max vertex id
361  unsigned int max_vertex_id = 0;
362  FORALLvertices
363  {
364  if (vertex->id + 1 > max_vertex_id)
365  max_vertex_id = vertex->id + 1;
366  }
367 
368  ++max_vertex_id;
369  std::vector<int> qhid_to_pcidx (max_vertex_id);
370 
371  hull_indices_.header = input_->header;
372  hull_indices_.indices.clear ();
373  hull_indices_.indices.reserve (num_vertices);
374 
375  FORALLvertices
376  {
377  // Add vertices to hull point_cloud and store index
378  hull_indices_.indices.push_back ((*indices_)[qh_pointid (vertex->point)]);
379  hull[i] = (*input_)[hull_indices_.indices.back ()];
380 
381  qhid_to_pcidx[vertex->id] = i; // map the vertex id of qhull to the point cloud index
382  ++i;
383  }
384 
385  if (compute_area_)
386  {
387  total_area_ = qh totarea;
388  total_volume_ = qh totvol;
389  }
390 
391  if (fill_polygon_data)
392  {
393  polygons.resize (num_facets);
394  int dd = 0;
395 
396  facetT * facet;
397  FORALLfacets
398  {
399  polygons[dd].vertices.resize (3);
400 
401  // Needed by FOREACHvertex_i_
402  int vertex_n, vertex_i;
403  FOREACHvertex_i_ ((*facet).vertices)
404  //facet_vertices.vertices.push_back (qhid_to_pcidx[vertex->id]);
405  polygons[dd].vertices[vertex_i] = qhid_to_pcidx[vertex->id];
406  ++dd;
407  }
408  }
409  // Deallocates memory (also the points)
410  qh_freeqhull (!qh_ALL);
411  int curlong, totlong;
412  qh_memfreeshort (&curlong, &totlong);
413 
414  hull.width = hull.size ();
415  hull.height = 1;
416  hull.is_dense = false;
417 }
418 #ifdef __GNUC__
419 #pragma GCC diagnostic warning "-Wold-style-cast"
420 #endif
421 
422 //////////////////////////////////////////////////////////////////////////
423 template <typename PointInT> void
424 pcl::ConvexHull<PointInT>::performReconstruction (PointCloud &hull, std::vector<pcl::Vertices> &polygons,
425  bool fill_polygon_data)
426 {
427  if (dimension_ == 0)
428  calculateInputDimension ();
429  if (dimension_ == 2)
430  performReconstruction2D (hull, polygons, fill_polygon_data);
431  else if (dimension_ == 3)
432  performReconstruction3D (hull, polygons, fill_polygon_data);
433  else
434  PCL_ERROR ("[pcl::%s::performReconstruction] Error: invalid input dimension requested: %d\n",getClassName ().c_str (),dimension_);
435 }
436 
437 //////////////////////////////////////////////////////////////////////////
438 template <typename PointInT> void
440 {
441  points.header = input_->header;
442  if (!initCompute () || input_->points.empty () || indices_->empty ())
443  {
444  points.clear ();
445  return;
446  }
447 
448  // Perform the actual surface reconstruction
449  std::vector<pcl::Vertices> polygons;
450  performReconstruction (points, polygons, false);
451 
452  points.width = points.size ();
453  points.height = 1;
454  points.is_dense = true;
455 
456  deinitCompute ();
457 }
458 
459 
460 //////////////////////////////////////////////////////////////////////////
461 template <typename PointInT> void
463 {
464  // Perform reconstruction
465  pcl::PointCloud<PointInT> hull_points;
466  performReconstruction (hull_points, output.polygons, true);
467 
468  // Convert the PointCloud into a PCLPointCloud2
469  pcl::toPCLPointCloud2 (hull_points, output.cloud);
470 }
471 
472 //////////////////////////////////////////////////////////////////////////
473 template <typename PointInT> void
474 pcl::ConvexHull<PointInT>::performReconstruction (std::vector<pcl::Vertices> &polygons)
475 {
476  pcl::PointCloud<PointInT> hull_points;
477  performReconstruction (hull_points, polygons, true);
478 }
479 
480 //////////////////////////////////////////////////////////////////////////
481 template <typename PointInT> void
482 pcl::ConvexHull<PointInT>::reconstruct (PointCloud &points, std::vector<pcl::Vertices> &polygons)
483 {
484  points.header = input_->header;
485  if (!initCompute () || input_->points.empty () || indices_->empty ())
486  {
487  points.clear ();
488  return;
489  }
490 
491  // Perform the actual surface reconstruction
492  performReconstruction (points, polygons, true);
493 
494  points.width = points.size ();
495  points.height = 1;
496  points.is_dense = true;
497 
498  deinitCompute ();
499 }
500 //////////////////////////////////////////////////////////////////////////
501 template <typename PointInT> void
503 {
504  hull_point_indices = hull_indices_;
505 }
506 
507 #define PCL_INSTANTIATE_ConvexHull(T) template class PCL_EXPORTS pcl::ConvexHull<T>;
508 
509 #endif // PCL_SURFACE_IMPL_CONVEX_HULL_H_
510 #endif
pcl::PolygonMesh::cloud
::pcl::PCLPointCloud2 cloud
Definition: PolygonMesh.h:21
pcl::PointCloud::height
std::uint32_t height
The point cloud height (if organized as an image-structure).
Definition: point_cloud.h:393
common.h
pcl::ConvexHull::getHullPointIndices
void getHullPointIndices(pcl::PointIndices &hull_point_indices) const
Retrieve the indices of the input point cloud that for the convex hull.
Definition: convex_hull.hpp:502
pcl::PointCloud::points
std::vector< PointT, Eigen::aligned_allocator< PointT > > points
The point data.
Definition: point_cloud.h:388
pcl::comparePoints2D
bool comparePoints2D(const std::pair< int, Eigen::Vector4f > &p1, const std::pair< int, Eigen::Vector4f > &p2)
Sort 2D points in a vector structure.
Definition: convex_hull.h:59
pcl::ConvexHull::performReconstruction3D
void performReconstruction3D(PointCloud &points, std::vector< pcl::Vertices > &polygons, bool fill_polygon_data=false)
The reconstruction method for 3D data.
Definition: convex_hull.hpp:292
pcl::ConvexHull::performReconstruction2D
void performReconstruction2D(PointCloud &points, std::vector< pcl::Vertices > &polygons, bool fill_polygon_data=false)
The reconstruction method for 2D data.
Definition: convex_hull.hpp:76
pcl::computeCovarianceMatrixNormalized
unsigned int computeCovarianceMatrixNormalized(const pcl::PointCloud< PointT > &cloud, const Eigen::Matrix< Scalar, 4, 1 > &centroid, Eigen::Matrix< Scalar, 3, 3 > &covariance_matrix)
Compute normalized the 3x3 covariance matrix of a given set of points.
Definition: centroid.hpp:251
pcl::ConvexHull::reconstruct
void reconstruct(PointCloud &points, std::vector< pcl::Vertices > &polygons)
Compute a convex hull for all points given.
Definition: convex_hull.hpp:482
pcl::PointCloud< PointInT >
pcl::eigen33
void eigen33(const Matrix &mat, typename Matrix::Scalar &eigenvalue, Vector &eigenvector)
determines the eigenvector and eigenvalue of the smallest eigenvalue of the symmetric positive semi d...
Definition: eigen.hpp:296
pcl::PointCloud::width
std::uint32_t width
The point cloud width (if organized as an image-structure).
Definition: point_cloud.h:391
pcl::PolygonMesh
Definition: PolygonMesh.h:14
pcl::PointCloud::is_dense
bool is_dense
True if no points are invalid (e.g., have NaN or Inf values in any of their floating point fields).
Definition: point_cloud.h:396
pcl::PointCloud::resize
void resize(std::size_t count)
Resizes the container to contain count elements.
Definition: point_cloud.h:455
pcl::PointIndices
Definition: PointIndices.h:11
pcl::PointCloud::header
pcl::PCLHeader header
The point cloud header.
Definition: point_cloud.h:385
pcl::PointCloud::size
std::size_t size() const
Definition: point_cloud.h:436
pcl::ConvexHull::calculateInputDimension
void calculateInputDimension()
Automatically determines the dimension of input data - 2D or 3D.
Definition: convex_hull.hpp:57
pcl::PointCloud::clear
void clear()
Removes all points in a cloud and sets the width and height to 0.
Definition: point_cloud.h:668
pcl::PolygonMesh::polygons
std::vector< ::pcl::Vertices > polygons
Definition: PolygonMesh.h:23
pcl::compute3DCentroid
unsigned int compute3DCentroid(ConstCloudIterator< PointT > &cloud_iterator, Eigen::Matrix< Scalar, 4, 1 > &centroid)
Compute the 3D (X-Y-Z) centroid of a set of points and return it as a 3D vector.
Definition: centroid.hpp:56
pcl::toPCLPointCloud2
void toPCLPointCloud2(const pcl::PointCloud< PointT > &cloud, pcl::PCLPointCloud2 &msg)
Convert a pcl::PointCloud<T> object to a PCLPointCloud2 binary data blob.
Definition: conversions.h:240
pcl::ConvexHull::performReconstruction
void performReconstruction(PointCloud &points, std::vector< pcl::Vertices > &polygons, bool fill_polygon_data=false)
The actual reconstruction method.
Definition: convex_hull.hpp:424