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