Point Cloud Library (PCL)  1.14.1-dev
cpc_segmentation.hpp
1 /*
2  * Software License Agreement (BSD License)
3  *
4  * Point Cloud Library (PCL) - www.pointclouds.org
5  * Copyright (c) 2014-, Open Perception, 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 #ifndef PCL_SEGMENTATION_IMPL_CPC_SEGMENTATION_HPP_
39 #define PCL_SEGMENTATION_IMPL_CPC_SEGMENTATION_HPP_
40 
41 #include <pcl/sample_consensus/sac_model_plane.h> // for SampleConsensusModelPlane
42 #include <pcl/segmentation/cpc_segmentation.h>
43 
44 template <typename PointT>
46 
47 template <typename PointT>
49 
50 template <typename PointT> void
52 {
53  if (supervoxels_set_)
54  {
55  // Calculate for every Edge if the connection is convex or invalid
56  // This effectively performs the segmentation.
57  calculateConvexConnections (sv_adjacency_list_);
58 
59  // Correct edge relations using extended convexity definition if k>0
60  applyKconvexity (k_factor_);
61 
62  // Determine whether to use cutting planes
63  doGrouping ();
64 
65  grouping_data_valid_ = true;
66 
67  applyCuttingPlane (max_cuts_);
68 
69  // merge small segments
70  mergeSmallSegments ();
71  }
72  else
73  PCL_WARN ("[pcl::CPCSegmentation::segment] WARNING: Call function setInputSupervoxels first. Nothing has been done. \n");
74 }
75 
76 template <typename PointT> void
77 pcl::CPCSegmentation<PointT>::applyCuttingPlane (std::uint32_t depth_levels_left)
78 {
79  using SegLabel2ClusterMap = std::map<std::uint32_t, pcl::PointCloud<WeightSACPointType>::Ptr>;
80 
81  pcl::console::print_info ("Cutting at level %d (maximum %d)\n", max_cuts_ - depth_levels_left + 1, max_cuts_);
82  // stop if we reached the 0 level
83  if (depth_levels_left <= 0)
84  return;
85 
86  pcl::IndicesPtr support_indices (new pcl::Indices);
87  SegLabel2ClusterMap seg_to_edge_points_map;
88  std::map<std::uint32_t, std::vector<EdgeID> > seg_to_edgeIDs_map;
89  EdgeIterator edge_itr, edge_itr_end, next_edge;
90  boost::tie (edge_itr, edge_itr_end) = boost::edges (sv_adjacency_list_);
91  for (next_edge = edge_itr; edge_itr != edge_itr_end; edge_itr = next_edge)
92  {
93  next_edge++; // next_edge iterator is necessary, because removing an edge invalidates the iterator to the current edge
94  std::uint32_t source_sv_label = sv_adjacency_list_[boost::source (*edge_itr, sv_adjacency_list_)];
95  std::uint32_t target_sv_label = sv_adjacency_list_[boost::target (*edge_itr, sv_adjacency_list_)];
96 
97  std::uint32_t source_segment_label = sv_label_to_seg_label_map_[source_sv_label];
98  std::uint32_t target_segment_label = sv_label_to_seg_label_map_[target_sv_label];
99 
100  // do not process edges which already split two segments
101  if (source_segment_label != target_segment_label)
102  continue;
103 
104  // if edge has been used for cutting already do not use it again
105  if (sv_adjacency_list_[*edge_itr].used_for_cutting)
106  continue;
107  // get centroids of vertices
108  const pcl::PointXYZRGBA source_centroid = sv_label_to_supervoxel_map_[source_sv_label]->centroid_;
109  const pcl::PointXYZRGBA target_centroid = sv_label_to_supervoxel_map_[target_sv_label]->centroid_;
110 
111  // stores the information about the edge cloud (used for the weighted ransac)
112  // we use the normal to express the direction of the connection
113  // we use the intensity to express the normal differences between supervoxel patches. <=0: Convex, >0: Concave
114  WeightSACPointType edge_centroid;
115  edge_centroid.getVector3fMap () = (source_centroid.getVector3fMap () + target_centroid.getVector3fMap ()) / 2;
116 
117  // we use the normal to express the direction of the connection!
118  edge_centroid.getNormalVector3fMap () = (target_centroid.getVector3fMap () - source_centroid.getVector3fMap ()).normalized ();
119 
120  // we use the intensity to express the normal differences between supervoxel patches. <=0: Convex, >0: Concave
121  edge_centroid.intensity = sv_adjacency_list_[*edge_itr].is_convex ? -sv_adjacency_list_[*edge_itr].normal_difference : sv_adjacency_list_[*edge_itr].normal_difference;
122  if (seg_to_edge_points_map.find (source_segment_label) == seg_to_edge_points_map.end ())
123  {
124  seg_to_edge_points_map[source_segment_label] = pcl::PointCloud<WeightSACPointType>::Ptr (new pcl::PointCloud<WeightSACPointType> ());
125  }
126  seg_to_edge_points_map[source_segment_label]->push_back (edge_centroid);
127  seg_to_edgeIDs_map[source_segment_label].push_back (*edge_itr);
128  }
129  bool cut_found = false;
130  // do the following processing for each segment separately
131  for (const auto &seg_to_edge_points : seg_to_edge_points_map)
132  {
133  // if too small do not process
134  if (seg_to_edge_points.second->size () < min_segment_size_for_cutting_)
135  {
136  continue;
137  }
138 
139  std::vector<double> weights;
140  weights.resize (seg_to_edge_points.second->size ());
141  for (std::size_t cp = 0; cp < seg_to_edge_points.second->size (); ++cp)
142  {
143  float& cur_weight = (*seg_to_edge_points.second)[cp].intensity;
144  cur_weight = cur_weight < concavity_tolerance_threshold_ ? 0 : 1;
145  weights[cp] = cur_weight;
146  }
147 
148  pcl::PointCloud<WeightSACPointType>::Ptr edge_cloud_cluster = seg_to_edge_points.second;
150 
151  WeightedRandomSampleConsensus weight_sac (model_p, seed_resolution_, true);
152 
153  weight_sac.setWeights (weights, use_directed_weights_);
154  weight_sac.setMaxIterations (ransac_itrs_);
155 
156  // if not enough inliers are found
157  if (!weight_sac.computeModel ())
158  {
159  continue;
160  }
161 
162  Eigen::VectorXf model_coefficients;
163  weight_sac.getModelCoefficients (model_coefficients);
164 
165  model_coefficients[3] += std::numeric_limits<float>::epsilon ();
166 
167  weight_sac.getInliers (*support_indices);
168 
169  // the support_indices which are actually cut (if not locally constrain: cut_support_indices = support_indices
170  pcl::Indices cut_support_indices;
171 
172  if (use_local_constrains_)
173  {
174  Eigen::Vector3f plane_normal (model_coefficients[0], model_coefficients[1], model_coefficients[2]);
175  // Cut the connections.
176  // We only iterate through the points which are within the support (when we are local, otherwise all points in the segment).
177  // We also just actually cut when the edge goes through the plane. This is why we check the planedistance
178  std::vector<pcl::PointIndices> cluster_indices;
181  tree->setInputCloud (edge_cloud_cluster);
182  euclidean_clusterer.setClusterTolerance (seed_resolution_);
183  euclidean_clusterer.setMinClusterSize (1);
184  euclidean_clusterer.setMaxClusterSize (25000);
185  euclidean_clusterer.setSearchMethod (tree);
186  euclidean_clusterer.setInputCloud (edge_cloud_cluster);
187  euclidean_clusterer.setIndices (support_indices);
188  euclidean_clusterer.extract (cluster_indices);
189 // sv_adjacency_list_[seg_to_edgeID_map[seg_to_edge_points.first][point_index]].used_for_cutting = true;
190 
191  for (const auto &cluster_index : cluster_indices)
192  {
193  // get centroids of vertices
194  float cluster_score = 0;
195 // std::cout << "Cluster has " << cluster_indices[cc].indices.size () << " points" << std::endl;
196  for (const auto &current_index : cluster_index.indices)
197  {
198  double index_score = weights[current_index];
199  if (use_directed_weights_)
200  index_score *= 1.414 * (std::abs (plane_normal.dot (edge_cloud_cluster->at (current_index).getNormalVector3fMap ())));
201  cluster_score += index_score;
202  }
203  // check if the score is below the threshold. If that is the case this segment should not be split
204  cluster_score /= cluster_index.indices.size ();
205 // std::cout << "Cluster score: " << cluster_score << std::endl;
206  if (cluster_score >= min_cut_score_)
207  {
208  cut_support_indices.insert (cut_support_indices.end (), cluster_index.indices.begin (), cluster_index.indices.end ());
209  }
210  }
211  if (cut_support_indices.empty ())
212  {
213 // std::cout << "Could not find planes which exceed required minimum score (threshold " << min_cut_score_ << "), not cutting" << std::endl;
214  continue;
215  }
216  }
217  else
218  {
219  double current_score = weight_sac.getBestScore ();
220  cut_support_indices = *support_indices;
221  // check if the score is below the threshold. If that is the case this segment should not be split
222  if (current_score < min_cut_score_)
223  {
224 // std::cout << "Score too low, no cutting" << std::endl;
225  continue;
226  }
227  }
228 
229  int number_connections_cut = 0;
230  for (const auto &point_index : cut_support_indices)
231  {
232  if (use_clean_cutting_)
233  {
234  // skip edges where both centroids are on one side of the cutting plane
235  std::uint32_t source_sv_label = sv_adjacency_list_[boost::source (seg_to_edgeIDs_map[seg_to_edge_points.first][point_index], sv_adjacency_list_)];
236  std::uint32_t target_sv_label = sv_adjacency_list_[boost::target (seg_to_edgeIDs_map[seg_to_edge_points.first][point_index], sv_adjacency_list_)];
237  // get centroids of vertices
238  const pcl::PointXYZRGBA source_centroid = sv_label_to_supervoxel_map_[source_sv_label]->centroid_;
239  const pcl::PointXYZRGBA target_centroid = sv_label_to_supervoxel_map_[target_sv_label]->centroid_;
240  // this makes a clean cut
241  if (pcl::pointToPlaneDistanceSigned (source_centroid, model_coefficients) * pcl::pointToPlaneDistanceSigned (target_centroid, model_coefficients) > 0)
242  {
243  continue;
244  }
245  }
246  sv_adjacency_list_[seg_to_edgeIDs_map[seg_to_edge_points.first][point_index]].used_for_cutting = true;
247  if (sv_adjacency_list_[seg_to_edgeIDs_map[seg_to_edge_points.first][point_index]].is_valid)
248  {
249  ++number_connections_cut;
250  sv_adjacency_list_[seg_to_edgeIDs_map[seg_to_edge_points.first][point_index]].is_valid = false;
251  }
252  }
253 // std::cout << "We cut " << number_connections_cut << " connections" << std::endl;
254  if (number_connections_cut > 0)
255  cut_found = true;
256  }
257 
258  // if not cut has been performed we can stop the recursion
259  if (cut_found)
260  {
261  doGrouping ();
262  --depth_levels_left;
263  applyCuttingPlane (depth_levels_left);
264  }
265  else
266  pcl::console::print_info ("Could not find any more cuts, stopping recursion\n");
267 }
268 
269 /******************************************* Directional weighted RANSAC definitions ******************************************************************/
270 
271 
272 template <typename PointT> bool
274 {
275  // Warn and exit if no threshold was set
276  if (threshold_ == std::numeric_limits<double>::max ())
277  {
278  PCL_ERROR ("[pcl::CPCSegmentation<PointT>::WeightedRandomSampleConsensus::computeModel] No threshold set!\n");
279  return (false);
280  }
281 
282  iterations_ = 0;
283  best_score_ = -std::numeric_limits<double>::max ();
284 
285  pcl::Indices selection;
286  Eigen::VectorXf model_coefficients;
287 
288  unsigned skipped_count = 0;
289  // suppress infinite loops by just allowing 10 x maximum allowed iterations for invalid model parameters!
290  const unsigned max_skip = max_iterations_ * 10;
291 
292  // Iterate
293  while (iterations_ < max_iterations_ && skipped_count < max_skip)
294  {
295  // Get X samples which satisfy the model criteria and which have a weight > 0
296  sac_model_->setIndices (model_pt_indices_);
297  sac_model_->getSamples (iterations_, selection);
298 
299  if (selection.empty ())
300  {
301  PCL_ERROR ("[pcl::CPCSegmentation<PointT>::WeightedRandomSampleConsensus::computeModel] No samples could be selected!\n");
302  break;
303  }
304 
305  // Search for inliers in the point cloud for the current plane model M
306  if (!sac_model_->computeModelCoefficients (selection, model_coefficients))
307  {
308  //++iterations_;
309  ++skipped_count;
310  continue;
311  }
312  // weight distances to get the score (only using connected inliers)
313  sac_model_->setIndices (full_cloud_pt_indices_);
314 
315  pcl::IndicesPtr current_inliers (new pcl::Indices);
316  sac_model_->selectWithinDistance (model_coefficients, threshold_, *current_inliers);
317  double current_score = 0;
318  Eigen::Vector3f plane_normal (model_coefficients[0], model_coefficients[1], model_coefficients[2]);
319  for (const auto &current_index : *current_inliers)
320  {
321  double index_score = weights_[current_index];
322  if (use_directed_weights_)
323  // the sqrt(2) factor was used in the paper and was meant for making the scores better comparable between directed and undirected weights
324  index_score *= 1.414 * (std::abs (plane_normal.dot (point_cloud_ptr_->at (current_index).getNormalVector3fMap ())));
325 
326  current_score += index_score;
327  }
328  // normalize by the total number of inliers
329  current_score /= current_inliers->size ();
330 
331  // Better match ?
332  if (current_score > best_score_)
333  {
334  best_score_ = current_score;
335  // Save the current model/inlier/coefficients selection as being the best so far
336  model_ = selection;
337  model_coefficients_ = model_coefficients;
338  }
339 
340  ++iterations_;
341  PCL_DEBUG ("[pcl::CPCSegmentation<PointT>::WeightedRandomSampleConsensus::computeModel] Trial %d (max %d): score is %f (best is: %f so far).\n", iterations_, max_iterations_, current_score, best_score_);
342  if (iterations_ > max_iterations_)
343  {
344  PCL_DEBUG ("[pcl::CPCSegmentation<PointT>::WeightedRandomSampleConsensus::computeModel] RANSAC reached the maximum number of trials.\n");
345  break;
346  }
347  }
348 // std::cout << "Took us " << iterations_ - 1 << " iterations" << std::endl;
349  PCL_DEBUG ("[pcl::CPCSegmentation<PointT>::WeightedRandomSampleConsensus::computeModel] Model: %lu size, %f score.\n", model_.size (), best_score_);
350 
351  if (model_.empty ())
352  {
353  inliers_.clear ();
354  return (false);
355  }
356 
357  // Get the set of inliers that correspond to the best model found so far
358  sac_model_->selectWithinDistance (model_coefficients_, threshold_, inliers_);
359  return (true);
360 }
361 
362 #endif // PCL_SEGMENTATION_IMPL_CPC_SEGMENTATION_HPP_
A segmentation algorithm partitioning a supervoxel graph.
void segment()
Merge supervoxels using cuts through local convexities.
~CPCSegmentation() override
EuclideanClusterExtraction represents a segmentation class for cluster extraction in an Euclidean sen...
void extract(std::vector< PointIndices > &clusters)
Cluster extraction in a PointCloud given by <setInputCloud (), setIndices ()>
void setClusterTolerance(double tolerance)
Set the spatial cluster tolerance as a measure in the L2 Euclidean space.
void setSearchMethod(const KdTreePtr &tree)
Provide a pointer to the search object.
void setMaxClusterSize(pcl::uindex_t max_cluster_size)
Set the maximum number of points that a cluster needs to contain in order to be considered valid.
void setMinClusterSize(pcl::uindex_t min_cluster_size)
Set the minimum number of points that a cluster needs to contain in order to be considered valid.
virtual void setInputCloud(const PointCloudConstPtr &cloud)
Provide a pointer to the input dataset.
Definition: pcl_base.hpp:65
virtual void setIndices(const IndicesPtr &indices)
Provide a pointer to the vector of indices that represents the input data.
Definition: pcl_base.hpp:72
PointCloud represents the base class in PCL for storing collections of 3D points.
Definition: point_cloud.h:173
const PointT & at(int column, int row) const
Obtain the point given by the (column, row) coordinates.
Definition: point_cloud.h:262
shared_ptr< PointCloud< PointT > > Ptr
Definition: point_cloud.h:413
SampleConsensusModelPlane defines a model for 3D plane segmentation.
shared_ptr< SampleConsensusModelPlane< PointT > > Ptr
search::KdTree is a wrapper class which inherits the pcl::KdTree class for performing search function...
Definition: kdtree.h:62
shared_ptr< KdTree< PointT, Tree > > Ptr
Definition: kdtree.h:75
double pointToPlaneDistanceSigned(const Point &p, double a, double b, double c, double d)
Get the distance from a point to a plane (signed) defined by ax+by+cz+d=0.
PCL_EXPORTS void print_info(const char *format,...)
Print an info message on stream with colors.
int cp(int from, int to)
Returns field copy operation code.
Definition: repacks.hpp:54
IndicesAllocator<> Indices
Type used for indices in PCL.
Definition: types.h:133
shared_ptr< Indices > IndicesPtr
Definition: pcl_base.h:58
A point structure representing Euclidean xyz coordinates, and the RGBA color.