Point Cloud Library (PCL)  1.8.1-dev
kdtree_flann.hpp
1 /*
2  * Software License Agreement (BSD License)
3  *
4  * Point Cloud Library (PCL) - www.pointclouds.org
5  * Copyright (c) 2009-2011, Willow Garage, Inc.
6  * Copyright (c) 2012-, Open Perception, Inc.
7  *
8  * All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  *
14  * * Redistributions of source code must retain the above copyright
15  * notice, this list of conditions and the following disclaimer.
16  * * Redistributions in binary form must reproduce the above
17  * copyright notice, this list of conditions and the following
18  * disclaimer in the documentation and/or other materials provided
19  * with the distribution.
20  * * Neither the name of the copyright holder(s) nor the names of its
21  * contributors may be used to endorse or promote products derived
22  * from this software without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
27  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
28  * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
29  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
30  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
31  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
32  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
34  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35  * POSSIBILITY OF SUCH DAMAGE.
36  *
37  */
38 
39 #ifndef PCL_KDTREE_KDTREE_IMPL_FLANN_H_
40 #define PCL_KDTREE_KDTREE_IMPL_FLANN_H_
41 
42 #include <cstdio>
43 #include <pcl/kdtree/kdtree_flann.h>
44 #include <pcl/kdtree/flann.h>
45 #include <pcl/console/print.h>
46 
47 ///////////////////////////////////////////////////////////////////////////////////////////
48 template <typename PointT, typename Dist>
50  : pcl::KdTree<PointT> (sorted)
51  , flann_index_ (), cloud_ ()
52  , index_mapping_ (), identity_mapping_ (false)
53  , dim_ (0), total_nr_points_ (0)
54  , param_k_ (::flann::SearchParams (-1 , epsilon_))
55  , param_radius_ (::flann::SearchParams (-1, epsilon_, sorted))
56 {
57 }
58 
59 ///////////////////////////////////////////////////////////////////////////////////////////
60 template <typename PointT, typename Dist>
62  : pcl::KdTree<PointT> (false)
63  , flann_index_ (), cloud_ ()
64  , index_mapping_ (), identity_mapping_ (false)
65  , dim_ (0), total_nr_points_ (0)
66  , param_k_ (::flann::SearchParams (-1 , epsilon_))
67  , param_radius_ (::flann::SearchParams (-1, epsilon_, false))
68 {
69  *this = k;
70 }
71 
72 ///////////////////////////////////////////////////////////////////////////////////////////
73 template <typename PointT, typename Dist> void
75 {
76  epsilon_ = eps;
77  param_k_ = ::flann::SearchParams (-1 , epsilon_);
78  param_radius_ = ::flann::SearchParams (-1 , epsilon_, sorted_);
79 }
80 
81 ///////////////////////////////////////////////////////////////////////////////////////////
82 template <typename PointT, typename Dist> void
84 {
85  sorted_ = sorted;
86  param_k_ = ::flann::SearchParams (-1, epsilon_);
87  param_radius_ = ::flann::SearchParams (-1, epsilon_, sorted_);
88 }
89 
90 ///////////////////////////////////////////////////////////////////////////////////////////
91 template <typename PointT, typename Dist> void
93 {
94  cleanup (); // Perform an automatic cleanup of structures
95 
96  epsilon_ = 0.0f; // default error bound value
97  dim_ = point_representation_->getNumberOfDimensions (); // Number of dimensions - default is 3 = xyz
98 
99  input_ = cloud;
100  indices_ = indices;
101 
102  // Allocate enough data
103  if (!input_)
104  {
105  PCL_ERROR ("[pcl::KdTreeFLANN::setInputCloud] Invalid input!\n");
106  return;
107  }
108  if (indices != NULL)
109  {
110  convertCloudToArray (*input_, *indices_);
111  }
112  else
113  {
114  convertCloudToArray (*input_);
115  }
116  total_nr_points_ = static_cast<int> (index_mapping_.size ());
117  if (total_nr_points_ == 0)
118  {
119  PCL_ERROR ("[pcl::KdTreeFLANN::setInputCloud] Cannot create a KDTree with an empty input cloud!\n");
120  return;
121  }
122 
123  flann_index_.reset (new FLANNIndex (::flann::Matrix<float> (cloud_.get (),
124  index_mapping_.size (),
125  dim_),
126  ::flann::KDTreeSingleIndexParams (15))); // max 15 points/leaf
127  flann_index_->buildIndex ();
128 }
129 
130 ///////////////////////////////////////////////////////////////////////////////////////////
131 template <typename PointT, typename Dist> int
133  std::vector<int> &k_indices,
134  std::vector<float> &k_distances) const
135 {
136  assert (point_representation_->isValid (point) && "Invalid (NaN, Inf) point coordinates given to nearestKSearch!");
137 
138  if (k > total_nr_points_)
139  k = total_nr_points_;
140 
141  k_indices.resize (k);
142  k_distances.resize (k);
143 
144  std::vector<float> query (dim_);
145  point_representation_->vectorize (static_cast<PointT> (point), query);
146 
147  ::flann::Matrix<int> k_indices_mat (&k_indices[0], 1, k);
148  ::flann::Matrix<float> k_distances_mat (&k_distances[0], 1, k);
149  // Wrap the k_indices and k_distances vectors (no data copy)
150  flann_index_->knnSearch (::flann::Matrix<float> (&query[0], 1, dim_),
151  k_indices_mat, k_distances_mat,
152  k, param_k_);
153 
154  // Do mapping to original point cloud
155  if (!identity_mapping_)
156  {
157  for (size_t i = 0; i < static_cast<size_t> (k); ++i)
158  {
159  int& neighbor_index = k_indices[i];
160  neighbor_index = index_mapping_[neighbor_index];
161  }
162  }
163 
164  return (k);
165 }
166 
167 ///////////////////////////////////////////////////////////////////////////////////////////
168 template <typename PointT, typename Dist> int
169 pcl::KdTreeFLANN<PointT, Dist>::radiusSearch (const PointT &point, double radius, std::vector<int> &k_indices,
170  std::vector<float> &k_sqr_dists, unsigned int max_nn) const
171 {
172  assert (point_representation_->isValid (point) && "Invalid (NaN, Inf) point coordinates given to radiusSearch!");
173 
174  std::vector<float> query (dim_);
175  point_representation_->vectorize (static_cast<PointT> (point), query);
176 
177  // Has max_nn been set properly?
178  if (max_nn == 0 || max_nn > static_cast<unsigned int> (total_nr_points_))
179  max_nn = total_nr_points_;
180 
181  std::vector<std::vector<int> > indices(1);
182  std::vector<std::vector<float> > dists(1);
183 
184  ::flann::SearchParams params (param_radius_);
185  if (max_nn == static_cast<unsigned int>(total_nr_points_))
186  params.max_neighbors = -1; // return all neighbors in radius
187  else
188  params.max_neighbors = max_nn;
189 
190  int neighbors_in_radius = flann_index_->radiusSearch (::flann::Matrix<float> (&query[0], 1, dim_),
191  indices,
192  dists,
193  static_cast<float> (radius * radius),
194  params);
195 
196  k_indices = indices[0];
197  k_sqr_dists = dists[0];
198 
199  // Do mapping to original point cloud
200  if (!identity_mapping_)
201  {
202  for (int i = 0; i < neighbors_in_radius; ++i)
203  {
204  int& neighbor_index = k_indices[i];
205  neighbor_index = index_mapping_[neighbor_index];
206  }
207  }
208 
209  return (neighbors_in_radius);
210 }
211 
212 ///////////////////////////////////////////////////////////////////////////////////////////
213 template <typename PointT, typename Dist> void
215 {
216  // Data array cleanup
217  index_mapping_.clear ();
218 
219  if (indices_)
220  indices_.reset ();
221 }
222 
223 ///////////////////////////////////////////////////////////////////////////////////////////
224 template <typename PointT, typename Dist> void
226 {
227  // No point in doing anything if the array is empty
228  if (cloud.points.empty ())
229  {
230  cloud_.reset ();
231  return;
232  }
233 
234  int original_no_of_points = static_cast<int> (cloud.points.size ());
235 
236  cloud_.reset (new float[original_no_of_points * dim_]);
237  float* cloud_ptr = cloud_.get ();
238  index_mapping_.reserve (original_no_of_points);
239  identity_mapping_ = true;
240 
241  for (int cloud_index = 0; cloud_index < original_no_of_points; ++cloud_index)
242  {
243  // Check if the point is invalid
244  if (!point_representation_->isValid (cloud.points[cloud_index]))
245  {
246  identity_mapping_ = false;
247  continue;
248  }
249 
250  index_mapping_.push_back (cloud_index);
251 
252  point_representation_->vectorize (cloud.points[cloud_index], cloud_ptr);
253  cloud_ptr += dim_;
254  }
255 }
256 
257 ///////////////////////////////////////////////////////////////////////////////////////////
258 template <typename PointT, typename Dist> void
259 pcl::KdTreeFLANN<PointT, Dist>::convertCloudToArray (const PointCloud &cloud, const std::vector<int> &indices)
260 {
261  // No point in doing anything if the array is empty
262  if (cloud.points.empty ())
263  {
264  cloud_.reset ();
265  return;
266  }
267 
268  int original_no_of_points = static_cast<int> (indices.size ());
269 
270  cloud_.reset (new float[original_no_of_points * dim_]);
271  float* cloud_ptr = cloud_.get ();
272  index_mapping_.reserve (original_no_of_points);
273  // its a subcloud -> false
274  // true only identity:
275  // - indices size equals cloud size
276  // - indices only contain values between 0 and cloud.size - 1
277  // - no index is multiple times in the list
278  // => index is complete
279  // But we can not guarantee that => identity_mapping_ = false
280  identity_mapping_ = false;
281 
282  for (std::vector<int>::const_iterator iIt = indices.begin (); iIt != indices.end (); ++iIt)
283  {
284  // Check if the point is invalid
285  if (!point_representation_->isValid (cloud.points[*iIt]))
286  continue;
287 
288  // map from 0 - N -> indices [0] - indices [N]
289  index_mapping_.push_back (*iIt); // If the returned index should be for the indices vector
290 
291  point_representation_->vectorize (cloud.points[*iIt], cloud_ptr);
292  cloud_ptr += dim_;
293  }
294 }
295 
296 #define PCL_INSTANTIATE_KdTreeFLANN(T) template class PCL_EXPORTS pcl::KdTreeFLANN<T>;
297 
298 #endif //#ifndef _PCL_KDTREE_KDTREE_IMPL_FLANN_H_
299 
int radiusSearch(const PointT &point, double radius, std::vector< int > &k_indices, std::vector< float > &k_sqr_distances, unsigned int max_nn=0) const
Search for all the nearest neighbors of the query point in a given radius.
KdTreeFLANN is a generic type of 3D spatial locator using kD-tree structures.
Definition: kdtree_flann.h:69
void setInputCloud(const PointCloudConstPtr &cloud, const IndicesConstPtr &indices=IndicesConstPtr())
Provide a pointer to the input dataset.
int nearestKSearch(const PointT &point, int k, std::vector< int > &k_indices, std::vector< float > &k_sqr_distances) const
Search for k-nearest neighbors for the given query point.
void setEpsilon(float eps)
Set the search epsilon precision (error bound) for nearest neighbors searches.
void setSortedResults(bool sorted)
KdTreeFLANN(bool sorted=true)
Default Constructor for KdTreeFLANN.
std::vector< PointT, Eigen::aligned_allocator< PointT > > points
The point data.
Definition: point_cloud.h:410
boost::shared_ptr< const std::vector< int > > IndicesConstPtr
Definition: kdtree.h:60
A point structure representing Euclidean xyz coordinates, and the RGB color.
KdTree represents the base spatial locator class for kd-tree implementations.
Definition: kdtree.h:56
boost::shared_ptr< const PointCloud > PointCloudConstPtr
Definition: kdtree.h:64