Point Cloud Library (PCL)  1.14.0-dev
extract_clusters.hpp
1 /*
2  * Software License Agreement (BSD License)
3  *
4  * Copyright (c) 2009, Willow Garage, Inc.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * * Redistributions of source code must retain the above copyright
12  * notice, this list of conditions and the following disclaimer.
13  * * Redistributions in binary form must reproduce the above
14  * copyright notice, this list of conditions and the following
15  * disclaimer in the documentation and/or other materials provided
16  * with the distribution.
17  * * Neither the name of the copyright holder(s) nor the names of its
18  * contributors may be used to endorse or promote products derived
19  * from this software without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
25  * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
27  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
29  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
31  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32  * POSSIBILITY OF SUCH DAMAGE.
33  *
34  * $Id$
35  *
36  */
37 
38 #ifndef PCL_SEGMENTATION_IMPL_EXTRACT_CLUSTERS_H_
39 #define PCL_SEGMENTATION_IMPL_EXTRACT_CLUSTERS_H_
40 
41 #include <pcl/segmentation/extract_clusters.h>
42 #include <pcl/search/organized.h> // for OrganizedNeighbor
43 
44 //////////////////////////////////////////////////////////////////////////////////////////////
45 template <typename PointT> void
47  const typename search::Search<PointT>::Ptr &tree,
48  float tolerance, std::vector<PointIndices> &clusters,
49  unsigned int min_pts_per_cluster,
50  unsigned int max_pts_per_cluster)
51 {
52  if (tree->getInputCloud ()->size () != cloud.size ())
53  {
54  PCL_ERROR("[pcl::extractEuclideanClusters] Tree built for a different point cloud "
55  "dataset (%zu) than the input cloud (%zu)!\n",
56  static_cast<std::size_t>(tree->getInputCloud()->size()),
57  static_cast<std::size_t>(cloud.size()));
58  return;
59  }
60  // Check if the tree is sorted -- if it is we don't need to check the first element
61  int nn_start_idx = tree->getSortedResults () ? 1 : 0;
62  // Create a bool vector of processed point indices, and initialize it to false
63  std::vector<bool> processed (cloud.size (), false);
64 
65  Indices nn_indices;
66  std::vector<float> nn_distances;
67  // Process all points in the indices vector
68  for (int i = 0; i < static_cast<int> (cloud.size ()); ++i)
69  {
70  if (processed[i])
71  continue;
72 
73  Indices seed_queue;
74  int sq_idx = 0;
75  seed_queue.push_back (i);
76 
77  processed[i] = true;
78 
79  while (sq_idx < static_cast<int> (seed_queue.size ()))
80  {
81  // Search for sq_idx
82  if (!tree->radiusSearch (seed_queue[sq_idx], tolerance, nn_indices, nn_distances))
83  {
84  sq_idx++;
85  continue;
86  }
87 
88  for (std::size_t j = nn_start_idx; j < nn_indices.size (); ++j) // can't assume sorted (default isn't!)
89  {
90  if (nn_indices[j] == UNAVAILABLE || processed[nn_indices[j]]) // Has this point been processed before ?
91  continue;
92 
93  // Perform a simple Euclidean clustering
94  seed_queue.push_back (nn_indices[j]);
95  processed[nn_indices[j]] = true;
96  }
97 
98  sq_idx++;
99  }
100 
101  // If this queue is satisfactory, add to the clusters
102  if (seed_queue.size () >= min_pts_per_cluster && seed_queue.size () <= max_pts_per_cluster)
103  {
105  r.indices.resize (seed_queue.size ());
106  for (std::size_t j = 0; j < seed_queue.size (); ++j)
107  r.indices[j] = seed_queue[j];
108 
109  // After clustering, indices are out of order, so sort them
110  std::sort (r.indices.begin (), r.indices.end ());
111 
112  r.header = cloud.header;
113  clusters.push_back (r); // We could avoid a copy by working directly in the vector
114  }
115  else
116  {
117  PCL_DEBUG("[pcl::extractEuclideanClusters] This cluster has %zu points, which is not between %u and %u points, so it is not a final cluster\n",
118  seed_queue.size (), min_pts_per_cluster, max_pts_per_cluster);
119  }
120  }
121 }
122 
123 //////////////////////////////////////////////////////////////////////////////////////////////
124 template <typename PointT> void
126  const Indices &indices,
127  const typename search::Search<PointT>::Ptr &tree,
128  float tolerance, std::vector<PointIndices> &clusters,
129  unsigned int min_pts_per_cluster,
130  unsigned int max_pts_per_cluster)
131 {
132  // \note If the tree was created over <cloud, indices>, we guarantee a 1-1 mapping between what the tree returns
133  //and indices[i]
134  if (tree->getInputCloud()->size() != cloud.size()) {
135  PCL_ERROR("[pcl::extractEuclideanClusters] Tree built for a different point cloud "
136  "dataset (%zu) than the input cloud (%zu)!\n",
137  static_cast<std::size_t>(tree->getInputCloud()->size()),
138  static_cast<std::size_t>(cloud.size()));
139  return;
140  }
141  if (tree->getIndices()->size() != indices.size()) {
142  PCL_ERROR("[pcl::extractEuclideanClusters] Tree built for a different set of "
143  "indices (%zu) than the input set (%zu)!\n",
144  static_cast<std::size_t>(tree->getIndices()->size()),
145  indices.size());
146  return;
147  }
148  // Check if the tree is sorted -- if it is we don't need to check the first element
149  int nn_start_idx = tree->getSortedResults () ? 1 : 0;
150 
151  // Create a bool vector of processed point indices, and initialize it to false
152  std::vector<bool> processed (cloud.size (), false);
153 
154  Indices nn_indices;
155  std::vector<float> nn_distances;
156  // Process all points in the indices vector
157  for (const auto &index : indices)
158  {
159  if (processed[index])
160  continue;
161 
162  Indices seed_queue;
163  int sq_idx = 0;
164  seed_queue.push_back (index);
165 
166  processed[index] = true;
167 
168  while (sq_idx < static_cast<int> (seed_queue.size ()))
169  {
170  // Search for sq_idx
171  int ret = tree->radiusSearch (cloud[seed_queue[sq_idx]], tolerance, nn_indices, nn_distances);
172  if( ret == -1)
173  {
174  PCL_ERROR("[pcl::extractEuclideanClusters] Received error code -1 from radiusSearch\n");
175  return;
176  }
177  if (!ret)
178  {
179  sq_idx++;
180  continue;
181  }
182 
183  for (std::size_t j = nn_start_idx; j < nn_indices.size (); ++j) // can't assume sorted (default isn't!)
184  {
185  if (nn_indices[j] == UNAVAILABLE || processed[nn_indices[j]]) // Has this point been processed before ?
186  continue;
187 
188  // Perform a simple Euclidean clustering
189  seed_queue.push_back (nn_indices[j]);
190  processed[nn_indices[j]] = true;
191  }
192 
193  sq_idx++;
194  }
195 
196  // If this queue is satisfactory, add to the clusters
197  if (seed_queue.size () >= min_pts_per_cluster && seed_queue.size () <= max_pts_per_cluster)
198  {
200  r.indices.resize (seed_queue.size ());
201  for (std::size_t j = 0; j < seed_queue.size (); ++j)
202  // This is the only place where indices come into play
203  r.indices[j] = seed_queue[j];
204 
205  // After clustering, indices are out of order, so sort them
206  std::sort (r.indices.begin (), r.indices.end ());
207 
208  r.header = cloud.header;
209  clusters.push_back (r); // We could avoid a copy by working directly in the vector
210  }
211  else
212  {
213  PCL_DEBUG("[pcl::extractEuclideanClusters] This cluster has %zu points, which is not between %u and %u points, so it is not a final cluster\n",
214  seed_queue.size (), min_pts_per_cluster, max_pts_per_cluster);
215  }
216  }
217 }
218 
219 //////////////////////////////////////////////////////////////////////////////////////////////
220 //////////////////////////////////////////////////////////////////////////////////////////////
221 //////////////////////////////////////////////////////////////////////////////////////////////
222 
223 template <typename PointT> void
224 pcl::EuclideanClusterExtraction<PointT>::extract (std::vector<PointIndices> &clusters)
225 {
226  if (!initCompute () ||
227  (input_ && input_->points.empty ()) ||
228  (indices_ && indices_->empty ()))
229  {
230  clusters.clear ();
231  return;
232  }
233 
234  // Initialize the spatial locator
235  if (!tree_)
236  {
237  if (input_->isOrganized ())
238  tree_.reset (new pcl::search::OrganizedNeighbor<PointT> ());
239  else
240  tree_.reset (new pcl::search::KdTree<PointT> (false));
241  }
242 
243  // Send the input dataset to the spatial locator
244  tree_->setInputCloud (input_, indices_);
245  extractEuclideanClusters (*input_, *indices_, tree_, static_cast<float> (cluster_tolerance_), clusters, min_pts_per_cluster_, max_pts_per_cluster_);
246 
247  //tree_->setInputCloud (input_);
248  //extractEuclideanClusters (*input_, tree_, cluster_tolerance_, clusters, min_pts_per_cluster_, max_pts_per_cluster_);
249 
250  // Sort the clusters based on their size (largest one first)
251  std::sort (clusters.rbegin (), clusters.rend (), comparePointClusters);
252 
253  deinitCompute ();
254 }
255 
256 #define PCL_INSTANTIATE_EuclideanClusterExtraction(T) template class PCL_EXPORTS pcl::EuclideanClusterExtraction<T>;
257 #define PCL_INSTANTIATE_extractEuclideanClusters(T) template void PCL_EXPORTS pcl::extractEuclideanClusters<T>(const pcl::PointCloud<T> &, const typename pcl::search::Search<T>::Ptr &, float , std::vector<pcl::PointIndices> &, unsigned int, unsigned int);
258 #define PCL_INSTANTIATE_extractEuclideanClusters_indices(T) template void PCL_EXPORTS pcl::extractEuclideanClusters<T>(const pcl::PointCloud<T> &, const pcl::Indices &, const typename pcl::search::Search<T>::Ptr &, float , std::vector<pcl::PointIndices> &, unsigned int, unsigned int);
259 
260 #endif // PCL_EXTRACT_CLUSTERS_IMPL_H_
void extract(std::vector< PointIndices > &clusters)
Cluster extraction in a PointCloud given by <setInputCloud (), setIndices ()>
PointCloud represents the base class in PCL for storing collections of 3D points.
Definition: point_cloud.h:173
pcl::PCLHeader header
The point cloud header.
Definition: point_cloud.h:392
std::size_t size() const
Definition: point_cloud.h:443
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 neighbor search in organized projectable point clo...
Definition: organized.h:65
virtual bool getSortedResults()
Gets whether the results should be sorted (ascending in the distance) or not Otherwise the results ma...
Definition: search.hpp:68
virtual IndicesConstPtr getIndices() const
Get a pointer to the vector of indices used.
Definition: search.h:131
shared_ptr< pcl::search::Search< PointT > > Ptr
Definition: search.h:81
virtual PointCloudConstPtr getInputCloud() const
Get a pointer to the input point cloud dataset.
Definition: search.h:124
virtual int radiusSearch(const PointT &point, double radius, Indices &k_indices, std::vector< float > &k_sqr_distances, unsigned int max_nn=0) const =0
Search for all the nearest neighbors of the query point in a given radius.
void extractEuclideanClusters(const PointCloud< PointT > &cloud, const typename search::Search< PointT >::Ptr &tree, float tolerance, std::vector< PointIndices > &clusters, unsigned int min_pts_per_cluster=1, unsigned int max_pts_per_cluster=(std::numeric_limits< int >::max)())
Decompose a region of space into clusters based on the Euclidean distance between points.
bool comparePointClusters(const pcl::PointIndices &a, const pcl::PointIndices &b)
Sort clusters method (for std::sort).
IndicesAllocator<> Indices
Type used for indices in PCL.
Definition: types.h:133
::pcl::PCLHeader header
Definition: PointIndices.h:18