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