Point Cloud Library (PCL)  1.11.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 
43 //////////////////////////////////////////////////////////////////////////////////////////////
44 template <typename PointT> void
46  const typename search::Search<PointT>::Ptr &tree,
47  float tolerance, std::vector<PointIndices> &clusters,
48  unsigned int min_pts_per_cluster,
49  unsigned int max_pts_per_cluster)
50 {
51  if (tree->getInputCloud ()->size () != cloud.size ())
52  {
53  PCL_ERROR("[pcl::extractEuclideanClusters] Tree built for a different point cloud "
54  "dataset (%zu) than the input cloud (%zu)!\n",
55  static_cast<std::size_t>(tree->getInputCloud()->size()),
56  static_cast<std::size_t>(cloud.size()));
57  return;
58  }
59  // Check if the tree is sorted -- if it is we don't need to check the first element
60  int nn_start_idx = tree->getSortedResults () ? 1 : 0;
61  // Create a bool vector of processed point indices, and initialize it to false
62  std::vector<bool> processed (cloud.size (), false);
63 
64  std::vector<int> nn_indices;
65  std::vector<float> nn_distances;
66  // Process all points in the indices vector
67  for (int i = 0; i < static_cast<int> (cloud.size ()); ++i)
68  {
69  if (processed[i])
70  continue;
71 
72  std::vector<int> seed_queue;
73  int sq_idx = 0;
74  seed_queue.push_back (i);
75 
76  processed[i] = true;
77 
78  while (sq_idx < static_cast<int> (seed_queue.size ()))
79  {
80  // Search for sq_idx
81  if (!tree->radiusSearch (seed_queue[sq_idx], tolerance, nn_indices, nn_distances))
82  {
83  sq_idx++;
84  continue;
85  }
86 
87  for (std::size_t j = nn_start_idx; j < nn_indices.size (); ++j) // can't assume sorted (default isn't!)
88  {
89  if (nn_indices[j] == -1 || processed[nn_indices[j]]) // Has this point been processed before ?
90  continue;
91 
92  // Perform a simple Euclidean clustering
93  seed_queue.push_back (nn_indices[j]);
94  processed[nn_indices[j]] = true;
95  }
96 
97  sq_idx++;
98  }
99 
100  // If this queue is satisfactory, add to the clusters
101  if (seed_queue.size () >= min_pts_per_cluster && seed_queue.size () <= max_pts_per_cluster)
102  {
104  r.indices.resize (seed_queue.size ());
105  for (std::size_t j = 0; j < seed_queue.size (); ++j)
106  r.indices[j] = seed_queue[j];
107 
108  // These two lines should not be needed: (can anyone confirm?) -FF
109  std::sort (r.indices.begin (), r.indices.end ());
110  r.indices.erase (std::unique (r.indices.begin (), r.indices.end ()), 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  }
116 }
117 
118 //////////////////////////////////////////////////////////////////////////////////////////////
119 /** @todo: fix the return value, make sure the exit is not needed anymore*/
120 template <typename PointT> void
122  const std::vector<int> &indices,
123  const typename search::Search<PointT>::Ptr &tree,
124  float tolerance, std::vector<PointIndices> &clusters,
125  unsigned int min_pts_per_cluster,
126  unsigned int max_pts_per_cluster)
127 {
128  // \note If the tree was created over <cloud, indices>, we guarantee a 1-1 mapping between what the tree returns
129  //and indices[i]
130  if (tree->getInputCloud()->size() != cloud.size()) {
131  PCL_ERROR("[pcl::extractEuclideanClusters] Tree built for a different point cloud "
132  "dataset (%zu) than the input cloud (%zu)!\n",
133  static_cast<std::size_t>(tree->getInputCloud()->size()),
134  static_cast<std::size_t>(cloud.size()));
135  return;
136  }
137  if (tree->getIndices()->size() != indices.size()) {
138  PCL_ERROR("[pcl::extractEuclideanClusters] Tree built for a different set of "
139  "indices (%zu) than the input set (%zu)!\n",
140  static_cast<std::size_t>(tree->getIndices()->size()),
141  indices.size());
142  return;
143  }
144  // Check if the tree is sorted -- if it is we don't need to check the first element
145  int nn_start_idx = tree->getSortedResults () ? 1 : 0;
146 
147  // Create a bool vector of processed point indices, and initialize it to false
148  std::vector<bool> processed (cloud.size (), false);
149 
150  std::vector<int> nn_indices;
151  std::vector<float> nn_distances;
152  // Process all points in the indices vector
153  for (const int &index : indices)
154  {
155  if (processed[index])
156  continue;
157 
158  std::vector<int> seed_queue;
159  int sq_idx = 0;
160  seed_queue.push_back (index);
161 
162  processed[index] = true;
163 
164  while (sq_idx < static_cast<int> (seed_queue.size ()))
165  {
166  // Search for sq_idx
167  int ret = tree->radiusSearch (cloud[seed_queue[sq_idx]], tolerance, nn_indices, nn_distances);
168  if( ret == -1)
169  {
170  PCL_ERROR("[pcl::extractEuclideanClusters] Received error code -1 from radiusSearch\n");
171  exit(0);
172  }
173  if (!ret)
174  {
175  sq_idx++;
176  continue;
177  }
178 
179  for (std::size_t j = nn_start_idx; j < nn_indices.size (); ++j) // can't assume sorted (default isn't!)
180  {
181  if (nn_indices[j] == -1 || processed[nn_indices[j]]) // Has this point been processed before ?
182  continue;
183 
184  // Perform a simple Euclidean clustering
185  seed_queue.push_back (nn_indices[j]);
186  processed[nn_indices[j]] = true;
187  }
188 
189  sq_idx++;
190  }
191 
192  // If this queue is satisfactory, add to the clusters
193  if (seed_queue.size () >= min_pts_per_cluster && seed_queue.size () <= max_pts_per_cluster)
194  {
196  r.indices.resize (seed_queue.size ());
197  for (std::size_t j = 0; j < seed_queue.size (); ++j)
198  // This is the only place where indices come into play
199  r.indices[j] = seed_queue[j];
200 
201  // These two lines should not be needed: (can anyone confirm?) -FF
202  //r.indices.assign(seed_queue.begin(), seed_queue.end());
203  std::sort (r.indices.begin (), r.indices.end ());
204  r.indices.erase (std::unique (r.indices.begin (), r.indices.end ()), r.indices.end ());
205 
206  r.header = cloud.header;
207  clusters.push_back (r); // We could avoid a copy by working directly in the vector
208  }
209  }
210 }
211 
212 //////////////////////////////////////////////////////////////////////////////////////////////
213 //////////////////////////////////////////////////////////////////////////////////////////////
214 //////////////////////////////////////////////////////////////////////////////////////////////
215 
216 template <typename PointT> void
217 pcl::EuclideanClusterExtraction<PointT>::extract (std::vector<PointIndices> &clusters)
218 {
219  if (!initCompute () ||
220  (input_ && input_->points.empty ()) ||
221  (indices_ && indices_->empty ()))
222  {
223  clusters.clear ();
224  return;
225  }
226 
227  // Initialize the spatial locator
228  if (!tree_)
229  {
230  if (input_->isOrganized ())
231  tree_.reset (new pcl::search::OrganizedNeighbor<PointT> ());
232  else
233  tree_.reset (new pcl::search::KdTree<PointT> (false));
234  }
235 
236  // Send the input dataset to the spatial locator
237  tree_->setInputCloud (input_, indices_);
238  extractEuclideanClusters (*input_, *indices_, tree_, static_cast<float> (cluster_tolerance_), clusters, min_pts_per_cluster_, max_pts_per_cluster_);
239 
240  //tree_->setInputCloud (input_);
241  //extractEuclideanClusters (*input_, tree_, cluster_tolerance_, clusters, min_pts_per_cluster_, max_pts_per_cluster_);
242 
243  // Sort the clusters based on their size (largest one first)
244  std::sort (clusters.rbegin (), clusters.rend (), comparePointClusters);
245 
246  deinitCompute ();
247 }
248 
249 #define PCL_INSTANTIATE_EuclideanClusterExtraction(T) template class PCL_EXPORTS pcl::EuclideanClusterExtraction<T>;
250 #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);
251 #define PCL_INSTANTIATE_extractEuclideanClusters_indices(T) template void PCL_EXPORTS pcl::extractEuclideanClusters<T>(const pcl::PointCloud<T> &, const std::vector<int> &, const typename pcl::search::Search<T>::Ptr &, float , std::vector<pcl::PointIndices> &, unsigned int, unsigned int);
252 
253 #endif // PCL_EXTRACT_CLUSTERS_IMPL_H_
pcl::EuclideanClusterExtraction::extract
void extract(std::vector< PointIndices > &clusters)
Cluster extraction in a PointCloud given by <setInputCloud (), setIndices ()>
Definition: extract_clusters.hpp:217
pcl::search::Search::getInputCloud
virtual PointCloudConstPtr getInputCloud() const
Get a pointer to the input point cloud dataset.
Definition: search.h:125
pcl::PointIndices::indices
Indices indices
Definition: PointIndices.h:23
pcl::search::Search::radiusSearch
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.
pcl::search::Search::getSortedResults
virtual bool getSortedResults()
Gets whether the results should be sorted (ascending in the distance) or not Otherwise the results ma...
Definition: search.hpp:68
pcl::PointIndices::header
::pcl::PCLHeader header
Definition: PointIndices.h:21
pcl::PointCloud
PointCloud represents the base class in PCL for storing collections of 3D points.
Definition: distances.h:55
pcl::gpu::comparePointClusters
bool comparePointClusters(const pcl::PointIndices &a, const pcl::PointIndices &b)
Sort clusters method (for std::sort).
Definition: gpu_extract_clusters.h:161
pcl::search::Search::getIndices
virtual IndicesConstPtr getIndices() const
Get a pointer to the vector of indices used.
Definition: search.h:132
pcl::search::KdTree< PointT >
pcl::search::Search::Ptr
shared_ptr< pcl::search::Search< PointT > > Ptr
Definition: search.h:81
pcl::PointIndices
Definition: PointIndices.h:13
pcl::PointCloud::header
pcl::PCLHeader header
The point cloud header.
Definition: point_cloud.h:408
pcl::search::OrganizedNeighbor
OrganizedNeighbor is a class for optimized nearest neigbhor search in organized point clouds.
Definition: organized.h:63
pcl::PointCloud::size
std::size_t size() const
Definition: point_cloud.h:459
pcl::extractEuclideanClusters
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.
Definition: extract_clusters.hpp:45