Point Cloud Library (PCL)  1.14.1-dev
extract_labeled_clusters.hpp
1 /*
2  * Software License Agreement (BSD License)
3  *
4  * Copyright (c) 2011, 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 #ifndef PCL_SEGMENTATION_IMPL_EXTRACT_LABELED_CLUSTERS_H_
38 #define PCL_SEGMENTATION_IMPL_EXTRACT_LABELED_CLUSTERS_H_
39 
40 #include <pcl/segmentation/extract_labeled_clusters.h>
41 
42 //////////////////////////////////////////////////////////////////////////////////////////////
43 template <typename PointT>
44 void
46  const PointCloud<PointT>& cloud,
47  const typename search::Search<PointT>::Ptr& tree,
48  float tolerance,
49  std::vector<std::vector<PointIndices>>& labeled_clusters,
50  unsigned int min_pts_per_cluster,
51  unsigned int max_pts_per_cluster)
52 {
53  if (tree->getInputCloud()->size() != cloud.size()) {
54  PCL_ERROR("[pcl::extractLabeledEuclideanClusters] Tree built for a different point "
55  "cloud dataset (%lu) than the input cloud (%lu)!\n",
56  tree->getInputCloud()->size(),
57  cloud.size());
58  return;
59  }
60  // If tree gives sorted results, we can skip the first one because it is the query point itself
61  const std::size_t 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 
68  // Process all points in the indices vector
69  for (index_t i = 0; i < static_cast<index_t>(cloud.size()); ++i) {
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  // Search for sq_idx
81  int ret = tree->radiusSearch(seed_queue[sq_idx],
82  tolerance,
83  nn_indices,
84  nn_distances,
85  std::numeric_limits<int>::max());
86  if (ret == -1)
87  PCL_ERROR("radiusSearch on tree came back with error -1");
88  if (!ret) {
89  sq_idx++;
90  continue;
91  }
92 
93  for (std::size_t j = nn_start_idx; j < nn_indices.size(); ++j)
94  {
95  if (processed[nn_indices[j]]) // Has this point been processed before ?
96  continue;
97  if (cloud[i].label == cloud[nn_indices[j]].label) {
98  // Perform a simple Euclidean clustering
99  seed_queue.push_back(nn_indices[j]);
100  processed[nn_indices[j]] = true;
101  }
102  }
103 
104  sq_idx++;
105  }
106 
107  // If this queue is satisfactory, add to the clusters
108  if (seed_queue.size() >= min_pts_per_cluster &&
109  seed_queue.size() <= max_pts_per_cluster) {
111  r.indices.resize(seed_queue.size());
112  for (std::size_t j = 0; j < seed_queue.size(); ++j)
113  r.indices[j] = seed_queue[j];
114  // After clustering, indices are out of order, so sort them
115  std::sort(r.indices.begin(), r.indices.end());
116 
117  r.header = cloud.header;
118  labeled_clusters[cloud[i].label].push_back(
119  r); // We could avoid a copy by working directly in the vector
120  }
121  }
122 }
123 //////////////////////////////////////////////////////////////////////////////////////////////
124 //////////////////////////////////////////////////////////////////////////////////////////////
125 //////////////////////////////////////////////////////////////////////////////////////////////
126 
127 template <typename PointT>
128 void
130  std::vector<std::vector<PointIndices>>& labeled_clusters)
131 {
132  if (!initCompute() || (input_ && input_->empty()) ||
133  (indices_ && indices_->empty())) {
134  labeled_clusters.clear();
135  return;
136  }
137 
138  // Initialize the spatial locator
139  if (!tree_) {
140  if (input_->isOrganized())
141  tree_.reset(new pcl::search::OrganizedNeighbor<PointT>());
142  else
143  tree_.reset(new pcl::search::KdTree<PointT>(false));
144  }
145 
146  // Send the input dataset to the spatial locator
147  tree_->setInputCloud(input_);
149  tree_,
150  static_cast<float>(cluster_tolerance_),
151  labeled_clusters,
152  min_pts_per_cluster_,
153  max_pts_per_cluster_);
154 
155  // Sort the clusters based on their size (largest one first)
156  for (auto& labeled_cluster : labeled_clusters)
157  std::sort(labeled_cluster.rbegin(), labeled_cluster.rend(), comparePointClusters);
158 
159  deinitCompute();
160 }
161 
162 #define PCL_INSTANTIATE_LabeledEuclideanClusterExtraction(T) \
163  template class PCL_EXPORTS pcl::LabeledEuclideanClusterExtraction<T>;
164 #define PCL_INSTANTIATE_extractLabeledEuclideanClusters(T) \
165  template void PCL_EXPORTS pcl::extractLabeledEuclideanClusters<T>( \
166  const pcl::PointCloud<T>&, \
167  const typename pcl::search::Search<T>::Ptr&, \
168  float, \
169  std::vector<std::vector<pcl::PointIndices>>&, \
170  unsigned int, \
171  unsigned int);
172 
173 #endif // PCL_EXTRACT_CLUSTERS_IMPL_H_
void extract(std::vector< std::vector< PointIndices >> &labeled_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 projectable point clo...
Definition: organized.h:65
virtual bool getSortedResults()
Gets whether the results should be sorted (ascending in the distance) or not Otherwise the results ma...
Definition: search.hpp:68
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:124
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 extractLabeledEuclideanClusters(const PointCloud< PointT > &cloud, const typename search::Search< PointT >::Ptr &tree, float tolerance, std::vector< std::vector< PointIndices >> &labeled_clusters, unsigned int min_pts_per_cluster=1, unsigned int max_pts_per_cluster=std::numeric_limits< unsigned 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).
detail::int_type_t< detail::index_type_size, detail::index_type_signed > index_t
Type used for an index in PCL.
Definition: types.h:112
IndicesAllocator<> Indices
Type used for indices in PCL.
Definition: types.h:133
::pcl::PCLHeader header
Definition: PointIndices.h:18