Point Cloud Library (PCL)  1.7.1
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_ (NULL)
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_ (NULL)
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_,
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  if (cloud_)
218  {
219  free (cloud_);
220  cloud_ = NULL;
221  }
222  index_mapping_.clear ();
223 
224  if (indices_)
225  indices_.reset ();
226 }
227 
228 ///////////////////////////////////////////////////////////////////////////////////////////
229 template <typename PointT, typename Dist> void
231 {
232  // No point in doing anything if the array is empty
233  if (cloud.points.empty ())
234  {
235  cloud_ = NULL;
236  return;
237  }
238 
239  int original_no_of_points = static_cast<int> (cloud.points.size ());
240 
241  cloud_ = static_cast<float*> (malloc (original_no_of_points * dim_ * sizeof (float)));
242  float* cloud_ptr = cloud_;
243  index_mapping_.reserve (original_no_of_points);
244  identity_mapping_ = true;
245 
246  for (int cloud_index = 0; cloud_index < original_no_of_points; ++cloud_index)
247  {
248  // Check if the point is invalid
249  if (!point_representation_->isValid (cloud.points[cloud_index]))
250  {
251  identity_mapping_ = false;
252  continue;
253  }
254 
255  index_mapping_.push_back (cloud_index);
256 
257  point_representation_->vectorize (cloud.points[cloud_index], cloud_ptr);
258  cloud_ptr += dim_;
259  }
260 }
261 
262 ///////////////////////////////////////////////////////////////////////////////////////////
263 template <typename PointT, typename Dist> void
264 pcl::KdTreeFLANN<PointT, Dist>::convertCloudToArray (const PointCloud &cloud, const std::vector<int> &indices)
265 {
266  // No point in doing anything if the array is empty
267  if (cloud.points.empty ())
268  {
269  cloud_ = NULL;
270  return;
271  }
272 
273  int original_no_of_points = static_cast<int> (indices.size ());
274 
275  cloud_ = static_cast<float*> (malloc (original_no_of_points * dim_ * sizeof (float)));
276  float* cloud_ptr = cloud_;
277  index_mapping_.reserve (original_no_of_points);
278  // its a subcloud -> false
279  // true only identity:
280  // - indices size equals cloud size
281  // - indices only contain values between 0 and cloud.size - 1
282  // - no index is multiple times in the list
283  // => index is complete
284  // But we can not guarantee that => identity_mapping_ = false
285  identity_mapping_ = false;
286 
287  for (std::vector<int>::const_iterator iIt = indices.begin (); iIt != indices.end (); ++iIt)
288  {
289  // Check if the point is invalid
290  if (!point_representation_->isValid (cloud.points[*iIt]))
291  continue;
292 
293  // map from 0 - N -> indices [0] - indices [N]
294  index_mapping_.push_back (*iIt); // If the returned index should be for the indices vector
295 
296  point_representation_->vectorize (cloud.points[*iIt], cloud_ptr);
297  cloud_ptr += dim_;
298  }
299 }
300 
301 #define PCL_INSTANTIATE_KdTreeFLANN(T) template class PCL_EXPORTS pcl::KdTreeFLANN<T>;
302 
303 #endif //#ifndef _PCL_KDTREE_KDTREE_IMPL_FLANN_H_
304 
void setSortedResults(bool sorted)
boost::shared_ptr< const std::vector< int > > IndicesConstPtr
Definition: kdtree.h:59
KdTreeFLANN(bool sorted=true)
Default Constructor for KdTreeFLANN.
void setEpsilon(float eps)
Set the search epsilon precision (error bound) for nearest neighbors searches.
void setInputCloud(const PointCloudConstPtr &cloud, const IndicesConstPtr &indices=IndicesConstPtr())
Provide a pointer to the input dataset.
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.
KdTree represents the base spatial locator class for kd-tree implementations.
Definition: kdtree.h:55
A point structure representing Euclidean xyz coordinates, and the RGB color.
std::vector< PointT, Eigen::aligned_allocator< PointT > > points
The point data.
Definition: point_cloud.h:410
boost::shared_ptr< const PointCloud > PointCloudConstPtr
Definition: kdtree.h:63
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.