Point Cloud Library (PCL)  1.11.1
organized_multi_plane_segmentation.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 the copyright holder(s) 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  *
37  *
38  */
39 
40 #ifndef PCL_SEGMENTATION_IMPL_ORGANIZED_MULTI_PLANE_SEGMENTATION_H_
41 #define PCL_SEGMENTATION_IMPL_ORGANIZED_MULTI_PLANE_SEGMENTATION_H_
42 
43 #include <pcl/segmentation/boost.h>
44 #include <pcl/segmentation/organized_connected_component_segmentation.h>
45 #include <pcl/segmentation/organized_multi_plane_segmentation.h>
46 #include <pcl/common/centroid.h>
47 #include <pcl/common/eigen.h>
48 
49 /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
50 template <typename PointT> pcl::PointCloud<PointT>
51 projectToPlaneFromViewpoint (pcl::PointCloud<PointT>& cloud, Eigen::Vector4f& normal, Eigen::Vector3f& centroid, Eigen::Vector3f& vp)
52 {
53  Eigen::Vector3f norm (normal[0], normal[1], normal[2]); //(region.coefficients_[0], region.coefficients_[1], region.coefficients_[2]);
54  pcl::PointCloud<PointT> projected_cloud;
55  projected_cloud.resize (cloud.size ());
56  for (std::size_t i = 0; i < cloud.size (); i++)
57  {
58  Eigen::Vector3f pt (cloud[i].x, cloud[i].y, cloud[i].z);
59  //Eigen::Vector3f intersection = (vp, pt, norm, centroid);
60  float u = norm.dot ((centroid - vp)) / norm.dot ((pt - vp));
61  Eigen::Vector3f intersection (vp + u * (pt - vp));
62  projected_cloud[i].x = intersection[0];
63  projected_cloud[i].y = intersection[1];
64  projected_cloud[i].z = intersection[2];
65  }
66 
67  return (projected_cloud);
68 }
69 
70 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
71 template<typename PointT, typename PointNT, typename PointLT> void
72 pcl::OrganizedMultiPlaneSegmentation<PointT, PointNT, PointLT>::segment (std::vector<ModelCoefficients>& model_coefficients,
73  std::vector<PointIndices>& inlier_indices)
74 {
76  std::vector<pcl::PointIndices> label_indices;
77  std::vector<Eigen::Vector4f, Eigen::aligned_allocator<Eigen::Vector4f> > centroids;
78  std::vector <Eigen::Matrix3f, Eigen::aligned_allocator<Eigen::Matrix3f> > covariances;
79  segment (model_coefficients, inlier_indices, centroids, covariances, labels, label_indices);
80 }
81 
82 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
83 template<typename PointT, typename PointNT, typename PointLT> void
84 pcl::OrganizedMultiPlaneSegmentation<PointT, PointNT, PointLT>::segment (std::vector<ModelCoefficients>& model_coefficients,
85  std::vector<PointIndices>& inlier_indices,
86  std::vector<Eigen::Vector4f, Eigen::aligned_allocator<Eigen::Vector4f> >& centroids,
87  std::vector <Eigen::Matrix3f, Eigen::aligned_allocator<Eigen::Matrix3f> >& covariances,
89  std::vector<pcl::PointIndices>& label_indices)
90 {
91  if (!initCompute ())
92  return;
93 
94  // Check that the normals are present
95  if (!normals_)
96  {
97  PCL_ERROR( "[pcl::%s::segment] Must specify normals.\n", getClassName().c_str());
98  return;
99  }
100 
101  // Check that we got the same number of points and normals
102  if (normals_->size () != input_->size ())
103  {
104  PCL_ERROR("[pcl::%s::segment] Number of points in input cloud (%zu) and normal "
105  "cloud (%zu) do not match!\n",
106  getClassName().c_str(),
107  static_cast<std::size_t>(input_->size()),
108  static_cast<std::size_t>(normals_->size()));
109  return;
110  }
111 
112  // Check that the cloud is organized
113  if (!input_->isOrganized ())
114  {
115  PCL_ERROR ("[pcl::%s::segment] Organized point cloud is required for this plane extraction method!\n",
116  getClassName ().c_str ());
117  return;
118  }
119 
120  // Calculate range part of planes' hessian normal form
121  std::vector<float> plane_d (input_->size ());
122 
123  for (std::size_t i = 0; i < input_->size (); ++i)
124  plane_d[i] = (*input_)[i].getVector3fMap ().dot ((*normals_)[i].getNormalVector3fMap ());
125 
126  // Make a comparator
127  //PlaneCoefficientComparator<PointT,PointNT> plane_comparator (plane_d);
128  compare_->setPlaneCoeffD (plane_d);
129  compare_->setInputCloud (input_);
130  compare_->setInputNormals (normals_);
131  compare_->setAngularThreshold (static_cast<float> (angular_threshold_));
132  compare_->setDistanceThreshold (static_cast<float> (distance_threshold_), true);
133 
134  // Set up the output
135  OrganizedConnectedComponentSegmentation<PointT,PointLT> connected_component (compare_);
136  connected_component.setInputCloud (input_);
137  connected_component.segment (labels, label_indices);
138 
139  Eigen::Vector4f clust_centroid = Eigen::Vector4f::Zero ();
140  Eigen::Vector4f vp = Eigen::Vector4f::Zero ();
141  Eigen::Matrix3f clust_cov;
143  model.values.resize (4);
144 
145  // Fit Planes to each cluster
146  for (const auto &label_index : label_indices)
147  {
148  if (static_cast<unsigned> (label_index.indices.size ()) > min_inliers_)
149  {
150  pcl::computeMeanAndCovarianceMatrix (*input_, label_index.indices, clust_cov, clust_centroid);
151  Eigen::Vector4f plane_params;
152 
153  EIGEN_ALIGN16 Eigen::Vector3f::Scalar eigen_value;
154  EIGEN_ALIGN16 Eigen::Vector3f eigen_vector;
155  pcl::eigen33 (clust_cov, eigen_value, eigen_vector);
156  plane_params[0] = eigen_vector[0];
157  plane_params[1] = eigen_vector[1];
158  plane_params[2] = eigen_vector[2];
159  plane_params[3] = 0;
160  plane_params[3] = -1 * plane_params.dot (clust_centroid);
161 
162  vp -= clust_centroid;
163  float cos_theta = vp.dot (plane_params);
164  if (cos_theta < 0)
165  {
166  plane_params *= -1;
167  plane_params[3] = 0;
168  plane_params[3] = -1 * plane_params.dot (clust_centroid);
169  }
170 
171  // Compute the curvature surface change
172  float curvature;
173  float eig_sum = clust_cov.coeff (0) + clust_cov.coeff (4) + clust_cov.coeff (8);
174  if (eig_sum != 0)
175  curvature = std::abs (eigen_value / eig_sum);
176  else
177  curvature = 0;
178 
179  if (curvature < maximum_curvature_)
180  {
181  model.values[0] = plane_params[0];
182  model.values[1] = plane_params[1];
183  model.values[2] = plane_params[2];
184  model.values[3] = plane_params[3];
185  model_coefficients.push_back (model);
186  inlier_indices.push_back (label_index);
187  centroids.push_back (clust_centroid);
188  covariances.push_back (clust_cov);
189  }
190  }
191  }
192  deinitCompute ();
193 }
194 
195 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
196 template<typename PointT, typename PointNT, typename PointLT> void
198 {
199  std::vector<ModelCoefficients> model_coefficients;
200  std::vector<PointIndices> inlier_indices;
201  PointCloudLPtr labels (new PointCloudL);
202  std::vector<pcl::PointIndices> label_indices;
203  std::vector<pcl::PointIndices> boundary_indices;
204  pcl::PointCloud<PointT> boundary_cloud;
205  std::vector<Eigen::Vector4f, Eigen::aligned_allocator<Eigen::Vector4f> > centroids;
206  std::vector <Eigen::Matrix3f, Eigen::aligned_allocator<Eigen::Matrix3f> > covariances;
207  segment (model_coefficients, inlier_indices, centroids, covariances, *labels, label_indices);
208  regions.resize (model_coefficients.size ());
209  boundary_indices.resize (model_coefficients.size ());
210 
211  for (std::size_t i = 0; i < model_coefficients.size (); i++)
212  {
213  boundary_cloud.resize (0);
214  pcl::OrganizedConnectedComponentSegmentation<PointT,PointLT>::findLabeledRegionBoundary (inlier_indices[i].indices[0], labels, boundary_indices[i]);
215  boundary_cloud.points.resize (boundary_indices[i].indices.size ());
216  for (std::size_t j = 0; j < boundary_indices[i].indices.size (); j++)
217  boundary_cloud[j] = (*input_)[boundary_indices[i].indices[j]];
218 
219  Eigen::Vector3f centroid = Eigen::Vector3f (centroids[i][0],centroids[i][1],centroids[i][2]);
220  Eigen::Vector4f model = Eigen::Vector4f (model_coefficients[i].values[0],
221  model_coefficients[i].values[1],
222  model_coefficients[i].values[2],
223  model_coefficients[i].values[3]);
224  regions[i] = PlanarRegion<PointT> (centroid,
225  covariances[i],
226  static_cast<unsigned int> (inlier_indices[i].indices.size ()),
227  boundary_cloud.points,
228  model);
229  }
230 }
231 
232 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
233 template<typename PointT, typename PointNT, typename PointLT> void
235 {
236  std::vector<ModelCoefficients> model_coefficients;
237  std::vector<PointIndices> inlier_indices;
238  PointCloudLPtr labels (new PointCloudL);
239  std::vector<pcl::PointIndices> label_indices;
240  std::vector<pcl::PointIndices> boundary_indices;
241  pcl::PointCloud<PointT> boundary_cloud;
242  std::vector<Eigen::Vector4f, Eigen::aligned_allocator<Eigen::Vector4f> > centroids;
243  std::vector <Eigen::Matrix3f, Eigen::aligned_allocator<Eigen::Matrix3f> > covariances;
244  segment (model_coefficients, inlier_indices, centroids, covariances, *labels, label_indices);
245  refine (model_coefficients, inlier_indices, labels, label_indices);
246  regions.resize (model_coefficients.size ());
247  boundary_indices.resize (model_coefficients.size ());
248 
249  for (std::size_t i = 0; i < model_coefficients.size (); i++)
250  {
251  boundary_cloud.resize (0);
252  int max_inlier_idx = static_cast<int> (inlier_indices[i].indices.size ()) - 1;
253  pcl::OrganizedConnectedComponentSegmentation<PointT,PointLT>::findLabeledRegionBoundary (inlier_indices[i].indices[max_inlier_idx], labels, boundary_indices[i]);
254  boundary_cloud.points.resize (boundary_indices[i].indices.size ());
255  for (std::size_t j = 0; j < boundary_indices[i].indices.size (); j++)
256  boundary_cloud[j] = (*input_)[boundary_indices[i].indices[j]];
257 
258  Eigen::Vector3f centroid = Eigen::Vector3f (centroids[i][0],centroids[i][1],centroids[i][2]);
259  Eigen::Vector4f model = Eigen::Vector4f (model_coefficients[i].values[0],
260  model_coefficients[i].values[1],
261  model_coefficients[i].values[2],
262  model_coefficients[i].values[3]);
263 
264  Eigen::Vector3f vp (0.0, 0.0, 0.0);
265  if (project_points_)
266  boundary_cloud = projectToPlaneFromViewpoint (boundary_cloud, model, centroid, vp);
267 
268  regions[i] = PlanarRegion<PointT> (centroid,
269  covariances[i],
270  static_cast<unsigned int> (inlier_indices[i].indices.size ()),
271  boundary_cloud.points,
272  model);
273  }
274 }
275 
276 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
277 template<typename PointT, typename PointNT, typename PointLT> void
279  std::vector<ModelCoefficients>& model_coefficients,
280  std::vector<PointIndices>& inlier_indices,
281  PointCloudLPtr& labels,
282  std::vector<pcl::PointIndices>& label_indices,
283  std::vector<pcl::PointIndices>& boundary_indices)
284 {
285  pcl::PointCloud<PointT> boundary_cloud;
286  std::vector<Eigen::Vector4f, Eigen::aligned_allocator<Eigen::Vector4f> > centroids;
287  std::vector <Eigen::Matrix3f, Eigen::aligned_allocator<Eigen::Matrix3f> > covariances;
288  segment (model_coefficients, inlier_indices, centroids, covariances, *labels, label_indices);
289  refine (model_coefficients, inlier_indices, labels, label_indices);
290  regions.resize (model_coefficients.size ());
291  boundary_indices.resize (model_coefficients.size ());
292 
293  for (std::size_t i = 0; i < model_coefficients.size (); i++)
294  {
295  boundary_cloud.resize (0);
296  int max_inlier_idx = static_cast<int> (inlier_indices[i].indices.size ()) - 1;
297  pcl::OrganizedConnectedComponentSegmentation<PointT,PointLT>::findLabeledRegionBoundary (inlier_indices[i].indices[max_inlier_idx], labels, boundary_indices[i]);
298  boundary_cloud.points.resize (boundary_indices[i].indices.size ());
299  for (std::size_t j = 0; j < boundary_indices[i].indices.size (); j++)
300  boundary_cloud[j] = (*input_)[boundary_indices[i].indices[j]];
301 
302  Eigen::Vector3f centroid = Eigen::Vector3f (centroids[i][0],centroids[i][1],centroids[i][2]);
303  Eigen::Vector4f model = Eigen::Vector4f (model_coefficients[i].values[0],
304  model_coefficients[i].values[1],
305  model_coefficients[i].values[2],
306  model_coefficients[i].values[3]);
307 
308  Eigen::Vector3f vp (0.0, 0.0, 0.0);
309  if (project_points_ && !boundary_cloud.points.empty ())
310  boundary_cloud = projectToPlaneFromViewpoint (boundary_cloud, model, centroid, vp);
311 
312  regions[i] = PlanarRegion<PointT> (centroid,
313  covariances[i],
314  static_cast<unsigned int> (inlier_indices[i].indices.size ()),
315  boundary_cloud.points,
316  model);
317  }
318 }
319 
320 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
321 template<typename PointT, typename PointNT, typename PointLT> void
322 pcl::OrganizedMultiPlaneSegmentation<PointT, PointNT, PointLT>::refine (std::vector<ModelCoefficients>& model_coefficients,
323  std::vector<PointIndices>& inlier_indices,
324  PointCloudLPtr& labels,
325  std::vector<pcl::PointIndices>& label_indices)
326 {
327  //List of labels to grow, and index of model corresponding to each label
328  std::vector<bool> grow_labels;
329  std::vector<int> label_to_model;
330  grow_labels.resize (label_indices.size (), false);
331  label_to_model.resize (label_indices.size (), 0);
332 
333  for (std::size_t i = 0; i < model_coefficients.size (); i++)
334  {
335  int model_label = (*labels)[inlier_indices[i].indices[0]].label;
336  label_to_model[model_label] = static_cast<int> (i);
337  grow_labels[model_label] = true;
338  }
339 
340  //refinement_compare_->setDistanceThreshold (0.015f, true);
341  refinement_compare_->setInputCloud (input_);
342  refinement_compare_->setLabels (labels);
343  refinement_compare_->setModelCoefficients (model_coefficients);
344  refinement_compare_->setRefineLabels (grow_labels);
345  refinement_compare_->setLabelToModel (label_to_model);
346 
347  //Do a first pass over the image, top to bottom, left to right
348  unsigned int current_row = 0;
349  unsigned int next_row = labels->width;
350  for (std::size_t rowIdx = 0; rowIdx < labels->height - 1; ++rowIdx, current_row = next_row, next_row += labels->width)
351  {
352 
353  for (unsigned colIdx = 0; colIdx < labels->width - 1; ++colIdx)
354  {
355  int current_label = (*labels)[current_row+colIdx].label;
356  int right_label = (*labels)[current_row+colIdx+1].label;
357  if (current_label < 0 || right_label < 0)
358  continue;
359 
360  //Check right
361  //bool test1 = false;
362  if (refinement_compare_->compare (current_row+colIdx, current_row+colIdx+1))
363  {
364  //test1 = true;
365  (*labels)[current_row+colIdx+1].label = current_label;
366  label_indices[current_label].indices.push_back (current_row+colIdx+1);
367  inlier_indices[label_to_model[current_label]].indices.push_back (current_row+colIdx+1);
368  }
369 
370  int lower_label = (*labels)[next_row+colIdx].label;
371  if (lower_label < 0)
372  continue;
373 
374  //Check down
375  if (refinement_compare_->compare (current_row+colIdx, next_row+colIdx))
376  {
377  (*labels)[next_row+colIdx].label = current_label;
378  label_indices[current_label].indices.push_back (next_row+colIdx);
379  inlier_indices[label_to_model[current_label]].indices.push_back (next_row+colIdx);
380  }
381 
382  }//col
383  }//row
384 
385  //Do a second pass over the image
386  current_row = labels->width * (labels->height - 1);
387  unsigned int prev_row = current_row - labels->width;
388  for (std::size_t rowIdx = 0; rowIdx < labels->height - 1; ++rowIdx, current_row = prev_row, prev_row -= labels->width)
389  {
390  for (int colIdx = labels->width - 1; colIdx >= 0; --colIdx)
391  {
392  int current_label = (*labels)[current_row+colIdx].label;
393  int left_label = (*labels)[current_row+colIdx-1].label;
394  if (current_label < 0 || left_label < 0)
395  continue;
396 
397  //Check left
398  if (refinement_compare_->compare (current_row+colIdx, current_row+colIdx-1))
399  {
400  (*labels)[current_row+colIdx-1].label = current_label;
401  label_indices[current_label].indices.push_back (current_row+colIdx-1);
402  inlier_indices[label_to_model[current_label]].indices.push_back (current_row+colIdx-1);
403  }
404 
405  int upper_label = (*labels)[prev_row+colIdx].label;
406  if (upper_label < 0)
407  continue;
408  //Check up
409  if (refinement_compare_->compare (current_row+colIdx, prev_row+colIdx))
410  {
411  (*labels)[prev_row+colIdx].label = current_label;
412  label_indices[current_label].indices.push_back (prev_row+colIdx);
413  inlier_indices[label_to_model[current_label]].indices.push_back (prev_row+colIdx);
414  }
415  }//col
416  }//row
417 }
418 
419 #define PCL_INSTANTIATE_OrganizedMultiPlaneSegmentation(T,NT,LT) template class PCL_EXPORTS pcl::OrganizedMultiPlaneSegmentation<T,NT,LT>;
420 
421 #endif // PCL_SEGMENTATION_IMPL_MULTI_PLANE_SEGMENTATION_H_
Define methods for centroid estimation and covariance matrix calculus.
OrganizedConnectedComponentSegmentation allows connected components to be found within organized poin...
static void findLabeledRegionBoundary(int start_idx, PointCloudLPtr labels, pcl::PointIndices &boundary_indices)
Find the boundary points / contour of a connected component.
void segment(pcl::PointCloud< PointLT > &labels, std::vector< pcl::PointIndices > &label_indices) const
Perform the connected component segmentation.
void segment(std::vector< PlanarRegion< PointT >, Eigen::aligned_allocator< PlanarRegion< PointT > > > &regions)
Segmentation of all planes in a point cloud given by setInputCloud(), setIndices()
void segment(std::vector< ModelCoefficients > &model_coefficients, std::vector< PointIndices > &inlier_indices, std::vector< Eigen::Vector4f, Eigen::aligned_allocator< Eigen::Vector4f > > &centroids, std::vector< Eigen::Matrix3f, Eigen::aligned_allocator< Eigen::Matrix3f > > &covariances, pcl::PointCloud< PointLT > &labels, std::vector< pcl::PointIndices > &label_indices)
Segmentation of all planes in a point cloud given by setInputCloud(), setIndices()
void segmentAndRefine(std::vector< PlanarRegion< PointT >, Eigen::aligned_allocator< PlanarRegion< PointT > > > &regions)
Perform a segmentation, as well as an additional refinement step.
void refine(std::vector< ModelCoefficients > &model_coefficients, std::vector< PointIndices > &inlier_indices, PointCloudLPtr &labels, std::vector< pcl::PointIndices > &label_indices)
Perform a refinement of an initial segmentation, by comparing points to adjacent regions detected by ...
virtual void setInputCloud(const PointCloudConstPtr &cloud)
Provide a pointer to the input dataset.
Definition: pcl_base.hpp:65
PlanarRegion represents a set of points that lie in a plane.
Definition: planar_region.h:52
PointCloud represents the base class in PCL for storing collections of 3D points.
Definition: point_cloud.h:181
void resize(std::size_t count)
Resizes the container to contain count elements.
Definition: point_cloud.h:478
std::size_t size() const
Definition: point_cloud.h:459
std::vector< PointT, Eigen::aligned_allocator< PointT > > points
The point data.
Definition: point_cloud.h:411
unsigned int computeMeanAndCovarianceMatrix(const pcl::PointCloud< PointT > &cloud, Eigen::Matrix< Scalar, 3, 3 > &covariance_matrix, Eigen::Matrix< Scalar, 4, 1 > &centroid)
Compute the normalized 3x3 covariance matrix and the centroid of a given set of points in a single lo...
Definition: centroid.hpp:485
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
__device__ __host__ __forceinline__ float norm(const float3 &v1, const float3 &v2)
std::vector< float > values