Point Cloud Library (PCL)  1.13.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  // These two lines should not be needed: (can anyone confirm?) -FF
110  std::sort (r.indices.begin (), r.indices.end ());
111  r.indices.erase (std::unique (r.indices.begin (), r.indices.end ()), r.indices.end ());
112 
113  r.header = cloud.header;
114  clusters.push_back (r); // We could avoid a copy by working directly in the vector
115  }
116  else
117  {
118  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",
119  seed_queue.size (), min_pts_per_cluster, max_pts_per_cluster);
120  }
121  }
122 }
123 
124 //////////////////////////////////////////////////////////////////////////////////////////////
125 template <typename PointT> void
127  const Indices &indices,
128  const typename search::Search<PointT>::Ptr &tree,
129  float tolerance, std::vector<PointIndices> &clusters,
130  unsigned int min_pts_per_cluster,
131  unsigned int max_pts_per_cluster)
132 {
133  // \note If the tree was created over <cloud, indices>, we guarantee a 1-1 mapping between what the tree returns
134  //and indices[i]
135  if (tree->getInputCloud()->size() != cloud.size()) {
136  PCL_ERROR("[pcl::extractEuclideanClusters] Tree built for a different point cloud "
137  "dataset (%zu) than the input cloud (%zu)!\n",
138  static_cast<std::size_t>(tree->getInputCloud()->size()),
139  static_cast<std::size_t>(cloud.size()));
140  return;
141  }
142  if (tree->getIndices()->size() != indices.size()) {
143  PCL_ERROR("[pcl::extractEuclideanClusters] Tree built for a different set of "
144  "indices (%zu) than the input set (%zu)!\n",
145  static_cast<std::size_t>(tree->getIndices()->size()),
146  indices.size());
147  return;
148  }
149  // Check if the tree is sorted -- if it is we don't need to check the first element
150  int nn_start_idx = tree->getSortedResults () ? 1 : 0;
151 
152  // Create a bool vector of processed point indices, and initialize it to false
153  std::vector<bool> processed (cloud.size (), false);
154 
155  Indices nn_indices;
156  std::vector<float> nn_distances;
157  // Process all points in the indices vector
158  for (const auto &index : indices)
159  {
160  if (processed[index])
161  continue;
162 
163  Indices seed_queue;
164  int sq_idx = 0;
165  seed_queue.push_back (index);
166 
167  processed[index] = true;
168 
169  while (sq_idx < static_cast<int> (seed_queue.size ()))
170  {
171  // Search for sq_idx
172  int ret = tree->radiusSearch (cloud[seed_queue[sq_idx]], tolerance, nn_indices, nn_distances);
173  if( ret == -1)
174  {
175  PCL_ERROR("[pcl::extractEuclideanClusters] Received error code -1 from radiusSearch\n");
176  return;
177  }
178  if (!ret)
179  {
180  sq_idx++;
181  continue;
182  }
183 
184  for (std::size_t j = nn_start_idx; j < nn_indices.size (); ++j) // can't assume sorted (default isn't!)
185  {
186  if (nn_indices[j] == UNAVAILABLE || processed[nn_indices[j]]) // Has this point been processed before ?
187  continue;
188 
189  // Perform a simple Euclidean clustering
190  seed_queue.push_back (nn_indices[j]);
191  processed[nn_indices[j]] = true;
192  }
193 
194  sq_idx++;
195  }
196 
197  // If this queue is satisfactory, add to the clusters
198  if (seed_queue.size () >= min_pts_per_cluster && seed_queue.size () <= max_pts_per_cluster)
199  {
201  r.indices.resize (seed_queue.size ());
202  for (std::size_t j = 0; j < seed_queue.size (); ++j)
203  // This is the only place where indices come into play
204  r.indices[j] = seed_queue[j];
205 
206  // These two lines should not be needed: (can anyone confirm?) -FF
207  //r.indices.assign(seed_queue.begin(), seed_queue.end());
208  std::sort (r.indices.begin (), r.indices.end ());
209  r.indices.erase (std::unique (r.indices.begin (), r.indices.end ()), r.indices.end ());
210 
211  r.header = cloud.header;
212  clusters.push_back (r); // We could avoid a copy by working directly in the vector
213  }
214  else
215  {
216  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",
217  seed_queue.size (), min_pts_per_cluster, max_pts_per_cluster);
218  }
219  }
220 }
221 
222 //////////////////////////////////////////////////////////////////////////////////////////////
223 //////////////////////////////////////////////////////////////////////////////////////////////
224 //////////////////////////////////////////////////////////////////////////////////////////////
225 
226 template <typename PointT> void
227 pcl::EuclideanClusterExtraction<PointT>::extract (std::vector<PointIndices> &clusters)
228 {
229  if (!initCompute () ||
230  (input_ && input_->points.empty ()) ||
231  (indices_ && indices_->empty ()))
232  {
233  clusters.clear ();
234  return;
235  }
236 
237  // Initialize the spatial locator
238  if (!tree_)
239  {
240  if (input_->isOrganized ())
241  tree_.reset (new pcl::search::OrganizedNeighbor<PointT> ());
242  else
243  tree_.reset (new pcl::search::KdTree<PointT> (false));
244  }
245 
246  // Send the input dataset to the spatial locator
247  tree_->setInputCloud (input_, indices_);
248  extractEuclideanClusters (*input_, *indices_, tree_, static_cast<float> (cluster_tolerance_), clusters, min_pts_per_cluster_, max_pts_per_cluster_);
249 
250  //tree_->setInputCloud (input_);
251  //extractEuclideanClusters (*input_, tree_, cluster_tolerance_, clusters, min_pts_per_cluster_, max_pts_per_cluster_);
252 
253  // Sort the clusters based on their size (largest one first)
254  std::sort (clusters.rbegin (), clusters.rend (), comparePointClusters);
255 
256  deinitCompute ();
257 }
258 
259 #define PCL_INSTANTIATE_EuclideanClusterExtraction(T) template class PCL_EXPORTS pcl::EuclideanClusterExtraction<T>;
260 #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);
261 #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);
262 
263 #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 point clouds.
Definition: organized.h:61
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:130
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:123
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