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