Point Cloud Library (PCL)  1.11.0
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.points.size ());
56  for (std::size_t i = 0; i < cloud.points.size (); i++)
57  {
58  Eigen::Vector3f pt (cloud.points[i].x, cloud.points[i].y, cloud.points[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 (static_cast<int> (normals_->points.size ()) != static_cast<int> (input_->points.size ()))
103  {
104  PCL_ERROR ("[pcl::%s::segment] Number of points in input cloud (%lu) and normal cloud (%lu) do not match!\n",
105  getClassName ().c_str (), input_->points.size (),
106  normals_->points.size ());
107  return;
108  }
109 
110  // Check that the cloud is organized
111  if (!input_->isOrganized ())
112  {
113  PCL_ERROR ("[pcl::%s::segment] Organized point cloud is required for this plane extraction method!\n",
114  getClassName ().c_str ());
115  return;
116  }
117 
118  // Calculate range part of planes' hessian normal form
119  std::vector<float> plane_d (input_->points.size ());
120 
121  for (std::size_t i = 0; i < input_->size (); ++i)
122  plane_d[i] = input_->points[i].getVector3fMap ().dot (normals_->points[i].getNormalVector3fMap ());
123 
124  // Make a comparator
125  //PlaneCoefficientComparator<PointT,PointNT> plane_comparator (plane_d);
126  compare_->setPlaneCoeffD (plane_d);
127  compare_->setInputCloud (input_);
128  compare_->setInputNormals (normals_);
129  compare_->setAngularThreshold (static_cast<float> (angular_threshold_));
130  compare_->setDistanceThreshold (static_cast<float> (distance_threshold_), true);
131 
132  // Set up the output
133  OrganizedConnectedComponentSegmentation<PointT,PointLT> connected_component (compare_);
134  connected_component.setInputCloud (input_);
135  connected_component.segment (labels, label_indices);
136 
137  Eigen::Vector4f clust_centroid = Eigen::Vector4f::Zero ();
138  Eigen::Vector4f vp = Eigen::Vector4f::Zero ();
139  Eigen::Matrix3f clust_cov;
141  model.values.resize (4);
142 
143  // Fit Planes to each cluster
144  for (const auto &label_index : label_indices)
145  {
146  if (static_cast<unsigned> (label_index.indices.size ()) > min_inliers_)
147  {
148  pcl::computeMeanAndCovarianceMatrix (*input_, label_index.indices, clust_cov, clust_centroid);
149  Eigen::Vector4f plane_params;
150 
151  EIGEN_ALIGN16 Eigen::Vector3f::Scalar eigen_value;
152  EIGEN_ALIGN16 Eigen::Vector3f eigen_vector;
153  pcl::eigen33 (clust_cov, eigen_value, eigen_vector);
154  plane_params[0] = eigen_vector[0];
155  plane_params[1] = eigen_vector[1];
156  plane_params[2] = eigen_vector[2];
157  plane_params[3] = 0;
158  plane_params[3] = -1 * plane_params.dot (clust_centroid);
159 
160  vp -= clust_centroid;
161  float cos_theta = vp.dot (plane_params);
162  if (cos_theta < 0)
163  {
164  plane_params *= -1;
165  plane_params[3] = 0;
166  plane_params[3] = -1 * plane_params.dot (clust_centroid);
167  }
168 
169  // Compute the curvature surface change
170  float curvature;
171  float eig_sum = clust_cov.coeff (0) + clust_cov.coeff (4) + clust_cov.coeff (8);
172  if (eig_sum != 0)
173  curvature = std::abs (eigen_value / eig_sum);
174  else
175  curvature = 0;
176 
177  if (curvature < maximum_curvature_)
178  {
179  model.values[0] = plane_params[0];
180  model.values[1] = plane_params[1];
181  model.values[2] = plane_params[2];
182  model.values[3] = plane_params[3];
183  model_coefficients.push_back (model);
184  inlier_indices.push_back (label_index);
185  centroids.push_back (clust_centroid);
186  covariances.push_back (clust_cov);
187  }
188  }
189  }
190  deinitCompute ();
191 }
192 
193 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
194 template<typename PointT, typename PointNT, typename PointLT> void
196 {
197  std::vector<ModelCoefficients> model_coefficients;
198  std::vector<PointIndices> inlier_indices;
199  PointCloudLPtr labels (new PointCloudL);
200  std::vector<pcl::PointIndices> label_indices;
201  std::vector<pcl::PointIndices> boundary_indices;
202  pcl::PointCloud<PointT> boundary_cloud;
203  std::vector<Eigen::Vector4f, Eigen::aligned_allocator<Eigen::Vector4f> > centroids;
204  std::vector <Eigen::Matrix3f, Eigen::aligned_allocator<Eigen::Matrix3f> > covariances;
205  segment (model_coefficients, inlier_indices, centroids, covariances, *labels, label_indices);
206  regions.resize (model_coefficients.size ());
207  boundary_indices.resize (model_coefficients.size ());
208 
209  for (std::size_t i = 0; i < model_coefficients.size (); i++)
210  {
211  boundary_cloud.resize (0);
212  pcl::OrganizedConnectedComponentSegmentation<PointT,PointLT>::findLabeledRegionBoundary (inlier_indices[i].indices[0], labels, boundary_indices[i]);
213  boundary_cloud.points.resize (boundary_indices[i].indices.size ());
214  for (std::size_t j = 0; j < boundary_indices[i].indices.size (); j++)
215  boundary_cloud.points[j] = input_->points[boundary_indices[i].indices[j]];
216 
217  Eigen::Vector3f centroid = Eigen::Vector3f (centroids[i][0],centroids[i][1],centroids[i][2]);
218  Eigen::Vector4f model = Eigen::Vector4f (model_coefficients[i].values[0],
219  model_coefficients[i].values[1],
220  model_coefficients[i].values[2],
221  model_coefficients[i].values[3]);
222  regions[i] = PlanarRegion<PointT> (centroid,
223  covariances[i],
224  static_cast<unsigned int> (inlier_indices[i].indices.size ()),
225  boundary_cloud.points,
226  model);
227  }
228 }
229 
230 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
231 template<typename PointT, typename PointNT, typename PointLT> void
233 {
234  std::vector<ModelCoefficients> model_coefficients;
235  std::vector<PointIndices> inlier_indices;
236  PointCloudLPtr labels (new PointCloudL);
237  std::vector<pcl::PointIndices> label_indices;
238  std::vector<pcl::PointIndices> boundary_indices;
239  pcl::PointCloud<PointT> boundary_cloud;
240  std::vector<Eigen::Vector4f, Eigen::aligned_allocator<Eigen::Vector4f> > centroids;
241  std::vector <Eigen::Matrix3f, Eigen::aligned_allocator<Eigen::Matrix3f> > covariances;
242  segment (model_coefficients, inlier_indices, centroids, covariances, *labels, label_indices);
243  refine (model_coefficients, inlier_indices, labels, label_indices);
244  regions.resize (model_coefficients.size ());
245  boundary_indices.resize (model_coefficients.size ());
246 
247  for (std::size_t i = 0; i < model_coefficients.size (); i++)
248  {
249  boundary_cloud.resize (0);
250  int max_inlier_idx = static_cast<int> (inlier_indices[i].indices.size ()) - 1;
251  pcl::OrganizedConnectedComponentSegmentation<PointT,PointLT>::findLabeledRegionBoundary (inlier_indices[i].indices[max_inlier_idx], labels, boundary_indices[i]);
252  boundary_cloud.points.resize (boundary_indices[i].indices.size ());
253  for (std::size_t j = 0; j < boundary_indices[i].indices.size (); j++)
254  boundary_cloud.points[j] = input_->points[boundary_indices[i].indices[j]];
255 
256  Eigen::Vector3f centroid = Eigen::Vector3f (centroids[i][0],centroids[i][1],centroids[i][2]);
257  Eigen::Vector4f model = Eigen::Vector4f (model_coefficients[i].values[0],
258  model_coefficients[i].values[1],
259  model_coefficients[i].values[2],
260  model_coefficients[i].values[3]);
261 
262  Eigen::Vector3f vp (0.0, 0.0, 0.0);
263  if (project_points_)
264  boundary_cloud = projectToPlaneFromViewpoint (boundary_cloud, model, centroid, vp);
265 
266  regions[i] = PlanarRegion<PointT> (centroid,
267  covariances[i],
268  static_cast<unsigned int> (inlier_indices[i].indices.size ()),
269  boundary_cloud.points,
270  model);
271  }
272 }
273 
274 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
275 template<typename PointT, typename PointNT, typename PointLT> void
277  std::vector<ModelCoefficients>& model_coefficients,
278  std::vector<PointIndices>& inlier_indices,
279  PointCloudLPtr& labels,
280  std::vector<pcl::PointIndices>& label_indices,
281  std::vector<pcl::PointIndices>& boundary_indices)
282 {
283  pcl::PointCloud<PointT> boundary_cloud;
284  std::vector<Eigen::Vector4f, Eigen::aligned_allocator<Eigen::Vector4f> > centroids;
285  std::vector <Eigen::Matrix3f, Eigen::aligned_allocator<Eigen::Matrix3f> > covariances;
286  segment (model_coefficients, inlier_indices, centroids, covariances, *labels, label_indices);
287  refine (model_coefficients, inlier_indices, labels, label_indices);
288  regions.resize (model_coefficients.size ());
289  boundary_indices.resize (model_coefficients.size ());
290 
291  for (std::size_t i = 0; i < model_coefficients.size (); i++)
292  {
293  boundary_cloud.resize (0);
294  int max_inlier_idx = static_cast<int> (inlier_indices[i].indices.size ()) - 1;
295  pcl::OrganizedConnectedComponentSegmentation<PointT,PointLT>::findLabeledRegionBoundary (inlier_indices[i].indices[max_inlier_idx], labels, boundary_indices[i]);
296  boundary_cloud.points.resize (boundary_indices[i].indices.size ());
297  for (std::size_t j = 0; j < boundary_indices[i].indices.size (); j++)
298  boundary_cloud.points[j] = input_->points[boundary_indices[i].indices[j]];
299 
300  Eigen::Vector3f centroid = Eigen::Vector3f (centroids[i][0],centroids[i][1],centroids[i][2]);
301  Eigen::Vector4f model = Eigen::Vector4f (model_coefficients[i].values[0],
302  model_coefficients[i].values[1],
303  model_coefficients[i].values[2],
304  model_coefficients[i].values[3]);
305 
306  Eigen::Vector3f vp (0.0, 0.0, 0.0);
307  if (project_points_ && !boundary_cloud.points.empty ())
308  boundary_cloud = projectToPlaneFromViewpoint (boundary_cloud, model, centroid, vp);
309 
310  regions[i] = PlanarRegion<PointT> (centroid,
311  covariances[i],
312  static_cast<unsigned int> (inlier_indices[i].indices.size ()),
313  boundary_cloud.points,
314  model);
315  }
316 }
317 
318 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
319 template<typename PointT, typename PointNT, typename PointLT> void
320 pcl::OrganizedMultiPlaneSegmentation<PointT, PointNT, PointLT>::refine (std::vector<ModelCoefficients>& model_coefficients,
321  std::vector<PointIndices>& inlier_indices,
322  PointCloudLPtr& labels,
323  std::vector<pcl::PointIndices>& label_indices)
324 {
325  //List of labels to grow, and index of model corresponding to each label
326  std::vector<bool> grow_labels;
327  std::vector<int> label_to_model;
328  grow_labels.resize (label_indices.size (), false);
329  label_to_model.resize (label_indices.size (), 0);
330 
331  for (std::size_t i = 0; i < model_coefficients.size (); i++)
332  {
333  int model_label = (*labels)[inlier_indices[i].indices[0]].label;
334  label_to_model[model_label] = static_cast<int> (i);
335  grow_labels[model_label] = true;
336  }
337 
338  //refinement_compare_->setDistanceThreshold (0.015f, true);
339  refinement_compare_->setInputCloud (input_);
340  refinement_compare_->setLabels (labels);
341  refinement_compare_->setModelCoefficients (model_coefficients);
342  refinement_compare_->setRefineLabels (grow_labels);
343  refinement_compare_->setLabelToModel (label_to_model);
344 
345  //Do a first pass over the image, top to bottom, left to right
346  unsigned int current_row = 0;
347  unsigned int next_row = labels->width;
348  for (std::size_t rowIdx = 0; rowIdx < labels->height - 1; ++rowIdx, current_row = next_row, next_row += labels->width)
349  {
350 
351  for (unsigned colIdx = 0; colIdx < labels->width - 1; ++colIdx)
352  {
353  int current_label = (*labels)[current_row+colIdx].label;
354  int right_label = (*labels)[current_row+colIdx+1].label;
355  if (current_label < 0 || right_label < 0)
356  continue;
357 
358  //Check right
359  //bool test1 = false;
360  if (refinement_compare_->compare (current_row+colIdx, current_row+colIdx+1))
361  {
362  //test1 = true;
363  labels->points[current_row+colIdx+1].label = current_label;
364  label_indices[current_label].indices.push_back (current_row+colIdx+1);
365  inlier_indices[label_to_model[current_label]].indices.push_back (current_row+colIdx+1);
366  }
367 
368  int lower_label = (*labels)[next_row+colIdx].label;
369  if (lower_label < 0)
370  continue;
371 
372  //Check down
373  if (refinement_compare_->compare (current_row+colIdx, next_row+colIdx))
374  {
375  labels->points[next_row+colIdx].label = current_label;
376  label_indices[current_label].indices.push_back (next_row+colIdx);
377  inlier_indices[label_to_model[current_label]].indices.push_back (next_row+colIdx);
378  }
379 
380  }//col
381  }//row
382 
383  //Do a second pass over the image
384  current_row = labels->width * (labels->height - 1);
385  unsigned int prev_row = current_row - labels->width;
386  for (std::size_t rowIdx = 0; rowIdx < labels->height - 1; ++rowIdx, current_row = prev_row, prev_row -= labels->width)
387  {
388  for (int colIdx = labels->width - 1; colIdx >= 0; --colIdx)
389  {
390  int current_label = (*labels)[current_row+colIdx].label;
391  int left_label = (*labels)[current_row+colIdx-1].label;
392  if (current_label < 0 || left_label < 0)
393  continue;
394 
395  //Check left
396  if (refinement_compare_->compare (current_row+colIdx, current_row+colIdx-1))
397  {
398  labels->points[current_row+colIdx-1].label = current_label;
399  label_indices[current_label].indices.push_back (current_row+colIdx-1);
400  inlier_indices[label_to_model[current_label]].indices.push_back (current_row+colIdx-1);
401  }
402 
403  int upper_label = (*labels)[prev_row+colIdx].label;
404  if (upper_label < 0)
405  continue;
406  //Check up
407  if (refinement_compare_->compare (current_row+colIdx, prev_row+colIdx))
408  {
409  labels->points[prev_row+colIdx].label = current_label;
410  label_indices[current_label].indices.push_back (prev_row+colIdx);
411  inlier_indices[label_to_model[current_label]].indices.push_back (prev_row+colIdx);
412  }
413  }//col
414  }//row
415 }
416 
417 #define PCL_INSTANTIATE_OrganizedMultiPlaneSegmentation(T,NT,LT) template class PCL_EXPORTS pcl::OrganizedMultiPlaneSegmentation<T,NT,LT>;
418 
419 #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< 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:180
std::vector< PointT, Eigen::aligned_allocator< PointT > > points
The point data.
Definition: point_cloud.h:410
void resize(std::size_t n)
Resize the cloud.
Definition: point_cloud.h:455
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:489
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