Point Cloud Library (PCL)  1.9.1-dev
ppf_registration.hpp
1 /*
2  * Software License Agreement (BSD License)
3  *
4  * Point Cloud Library (PCL) - www.pointclouds.org
5  * Copyright (c) 2011, Alexandru-Eugen Ichim
6  * Willow Garage, Inc
7  * Copyright (c) 2012-, Open Perception, Inc.
8  *
9  * All rights reserved.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  *
15  * * Redistributions of source code must retain the above copyright
16  * notice, this list of conditions and the following disclaimer.
17  * * Redistributions in binary form must reproduce the above
18  * copyright notice, this list of conditions and the following
19  * disclaimer in the documentation and/or other materials provided
20  * with the distribution.
21  * * Neither the name of the copyright holder(s) nor the names of its
22  * contributors may be used to endorse or promote products derived
23  * from this software without specific prior written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
26  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
27  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
28  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
29  * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
30  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
31  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
32  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
33  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36  * POSSIBILITY OF SUCH DAMAGE.
37  *
38  * $Id$
39  *
40  */
41 
42 
43 #ifndef PCL_REGISTRATION_IMPL_PPF_REGISTRATION_H_
44 #define PCL_REGISTRATION_IMPL_PPF_REGISTRATION_H_
45 
46 #include <pcl/registration/ppf_registration.h>
47 #include <pcl/features/ppf.h>
48 #include <pcl/common/transforms.h>
49 
50 #include <pcl/features/pfh.h>
51 //////////////////////////////////////////////////////////////////////////////////////////////
52 template <typename PointSource, typename PointTarget> void
54 {
56 
57  scene_search_tree_ = typename pcl::KdTreeFLANN<PointTarget>::Ptr (new pcl::KdTreeFLANN<PointTarget>);
58  scene_search_tree_->setInputCloud (target_);
59 }
60 
61 //////////////////////////////////////////////////////////////////////////////////////////////
62 template <typename PointSource, typename PointTarget> void
64 {
65  if (!search_method_)
66  {
67  PCL_ERROR("[pcl::PPFRegistration::computeTransformation] Search method not set - skipping computeTransformation!\n");
68  return;
69  }
70 
71  if (guess != Eigen::Matrix4f::Identity ())
72  {
73  PCL_ERROR("[pcl::PPFRegistration::computeTransformation] setting initial transform (guess) not implemented!\n");
74  }
75 
76  PoseWithVotesList voted_poses;
77  std::vector <std::vector <unsigned int> > accumulator_array;
78  accumulator_array.resize (input_->points.size ());
79 
80  size_t aux_size = static_cast<size_t> (std::floor (2 * M_PI / search_method_->getAngleDiscretizationStep ()));
81  for (size_t i = 0; i < input_->points.size (); ++i)
82  {
83  std::vector<unsigned int> aux (aux_size);
84  accumulator_array[i] = aux;
85  }
86  PCL_INFO ("Accumulator array size: %u x %u.\n", accumulator_array.size (), accumulator_array.back ().size ());
87 
88  // Consider every <scene_reference_point_sampling_rate>-th point as the reference point => fix s_r
89  float f1, f2, f3, f4;
90  for (size_t scene_reference_index = 0; scene_reference_index < target_->points.size (); scene_reference_index += scene_reference_point_sampling_rate_)
91  {
92  Eigen::Vector3f scene_reference_point = target_->points[scene_reference_index].getVector3fMap (),
93  scene_reference_normal = target_->points[scene_reference_index].getNormalVector3fMap ();
94 
95  float rotation_angle_sg = std::acos (scene_reference_normal.dot (Eigen::Vector3f::UnitX ()));
96  bool parallel_to_x_sg = (scene_reference_normal.y() == 0.0f && scene_reference_normal.z() == 0.0f);
97  Eigen::Vector3f rotation_axis_sg = (parallel_to_x_sg)?(Eigen::Vector3f::UnitY ()):(scene_reference_normal.cross (Eigen::Vector3f::UnitX ()). normalized());
98  Eigen::AngleAxisf rotation_sg (rotation_angle_sg, rotation_axis_sg);
99  Eigen::Affine3f transform_sg (Eigen::Translation3f ( rotation_sg * ((-1) * scene_reference_point)) * rotation_sg);
100 
101  // For every other point in the scene => now have pair (s_r, s_i) fixed
102  std::vector<int> indices;
103  std::vector<float> distances;
104  scene_search_tree_->radiusSearch (target_->points[scene_reference_index],
105  search_method_->getModelDiameter () /2,
106  indices,
107  distances);
108  for(const size_t &scene_point_index : indices)
109 // for(size_t i = 0; i < target_->points.size (); ++i)
110  {
111  //size_t scene_point_index = i;
112  if (scene_reference_index != scene_point_index)
113  {
114  if (/*pcl::computePPFPairFeature*/pcl::computePairFeatures (target_->points[scene_reference_index].getVector4fMap (),
115  target_->points[scene_reference_index].getNormalVector4fMap (),
116  target_->points[scene_point_index].getVector4fMap (),
117  target_->points[scene_point_index].getNormalVector4fMap (),
118  f1, f2, f3, f4))
119  {
120  std::vector<std::pair<size_t, size_t> > nearest_indices;
121  search_method_->nearestNeighborSearch (f1, f2, f3, f4, nearest_indices);
122 
123  // Compute alpha_s angle
124  Eigen::Vector3f scene_point = target_->points[scene_point_index].getVector3fMap ();
125 
126  Eigen::Vector3f scene_point_transformed = transform_sg * scene_point;
127  float alpha_s = std::atan2 ( -scene_point_transformed(2), scene_point_transformed(1));
128  if (std::sin (alpha_s) * scene_point_transformed(2) < 0.0f)
129  alpha_s *= (-1);
130  alpha_s *= (-1);
131 
132  // Go through point pairs in the model with the same discretized feature
133  for (const auto &nearest_index : nearest_indices)
134  {
135  size_t model_reference_index = nearest_index.first;
136  size_t model_point_index = nearest_index.second;
137  // Calculate angle alpha = alpha_m - alpha_s
138  float alpha = search_method_->alpha_m_[model_reference_index][model_point_index] - alpha_s;
139  unsigned int alpha_discretized = static_cast<unsigned int> (std::floor (alpha) + std::floor (M_PI / search_method_->getAngleDiscretizationStep ()));
140  accumulator_array[model_reference_index][alpha_discretized] ++;
141  }
142  }
143  else PCL_ERROR ("[pcl::PPFRegistration::computeTransformation] Computing pair feature vector between points %u and %u went wrong.\n", scene_reference_index, scene_point_index);
144  }
145  }
146 
147  size_t max_votes_i = 0, max_votes_j = 0;
148  unsigned int max_votes = 0;
149 
150  for (size_t i = 0; i < accumulator_array.size (); ++i)
151  for (size_t j = 0; j < accumulator_array.back ().size (); ++j)
152  {
153  if (accumulator_array[i][j] > max_votes)
154  {
155  max_votes = accumulator_array[i][j];
156  max_votes_i = i;
157  max_votes_j = j;
158  }
159  // Reset accumulator_array for the next set of iterations with a new scene reference point
160  accumulator_array[i][j] = 0;
161  }
162 
163  Eigen::Vector3f model_reference_point = input_->points[max_votes_i].getVector3fMap (),
164  model_reference_normal = input_->points[max_votes_i].getNormalVector3fMap ();
165  float rotation_angle_mg = std::acos (model_reference_normal.dot (Eigen::Vector3f::UnitX ()));
166  bool parallel_to_x_mg = (model_reference_normal.y() == 0.0f && model_reference_normal.z() == 0.0f);
167  Eigen::Vector3f rotation_axis_mg = (parallel_to_x_mg)?(Eigen::Vector3f::UnitY ()):(model_reference_normal.cross (Eigen::Vector3f::UnitX ()). normalized());
168  Eigen::AngleAxisf rotation_mg (rotation_angle_mg, rotation_axis_mg);
169  Eigen::Affine3f transform_mg (Eigen::Translation3f ( rotation_mg * ((-1) * model_reference_point)) * rotation_mg);
170  Eigen::Affine3f max_transform =
171  transform_sg.inverse () *
172  Eigen::AngleAxisf ((static_cast<float> (max_votes_j) - std::floor (static_cast<float> (M_PI) / search_method_->getAngleDiscretizationStep ())) * search_method_->getAngleDiscretizationStep (), Eigen::Vector3f::UnitX ()) *
173  transform_mg;
174 
175  voted_poses.push_back (PoseWithVotes (max_transform, max_votes));
176  }
177  PCL_DEBUG ("Done with the Hough Transform ...\n");
178 
179  // Cluster poses for filtering out outliers and obtaining more precise results
180  PoseWithVotesList results;
181  clusterPoses (voted_poses, results);
182 
183  pcl::transformPointCloud (*input_, output, results.front ().pose);
184 
185  transformation_ = final_transformation_ = results.front ().pose.matrix ();
186  converged_ = true;
187 }
188 
189 
190 //////////////////////////////////////////////////////////////////////////////////////////////
191 template <typename PointSource, typename PointTarget> void
194 {
195  PCL_INFO ("Clustering poses ...\n");
196  // Start off by sorting the poses by the number of votes
197  sort(poses.begin (), poses.end (), poseWithVotesCompareFunction);
198 
199  std::vector<PoseWithVotesList> clusters;
200  std::vector<std::pair<size_t, unsigned int> > cluster_votes;
201  for (size_t poses_i = 0; poses_i < poses.size(); ++ poses_i)
202  {
203  bool found_cluster = false;
204  for (size_t clusters_i = 0; clusters_i < clusters.size(); ++ clusters_i)
205  {
206  if (posesWithinErrorBounds (poses[poses_i].pose, clusters[clusters_i].front ().pose))
207  {
208  found_cluster = true;
209  clusters[clusters_i].push_back (poses[poses_i]);
210  cluster_votes[clusters_i].second += poses[poses_i].votes;
211  break;
212  }
213  }
214 
215  if (!found_cluster)
216  {
217  // Create a new cluster with the current pose
218  PoseWithVotesList new_cluster;
219  new_cluster.push_back (poses[poses_i]);
220  clusters.push_back (new_cluster);
221  cluster_votes.push_back (std::pair<size_t, unsigned int> (clusters.size () - 1, poses[poses_i].votes));
222  }
223  }
224 
225  // Sort clusters by total number of votes
226  std::sort (cluster_votes.begin (), cluster_votes.end (), clusterVotesCompareFunction);
227  // Compute pose average and put them in result vector
228  /// @todo some kind of threshold for determining whether a cluster has enough votes or not...
229  /// now just taking the first three clusters
230  result.clear ();
231  size_t max_clusters = (clusters.size () < 3) ? clusters.size () : 3;
232  for (size_t cluster_i = 0; cluster_i < max_clusters; ++ cluster_i)
233  {
234  PCL_INFO ("Winning cluster has #votes: %d and #poses voted: %d.\n", cluster_votes[cluster_i].second, clusters[cluster_votes[cluster_i].first].size ());
235  Eigen::Vector3f translation_average (0.0, 0.0, 0.0);
236  Eigen::Vector4f rotation_average (0.0, 0.0, 0.0, 0.0);
237  for (typename PoseWithVotesList::iterator v_it = clusters[cluster_votes[cluster_i].first].begin (); v_it != clusters[cluster_votes[cluster_i].first].end (); ++ v_it)
238  {
239  translation_average += v_it->pose.translation ();
240  /// averaging rotations by just averaging the quaternions in 4D space - reference "On Averaging Rotations" by CLAUS GRAMKOW
241  rotation_average += Eigen::Quaternionf (v_it->pose.rotation ()).coeffs ();
242  }
243 
244  translation_average /= static_cast<float> (clusters[cluster_votes[cluster_i].first].size ());
245  rotation_average /= static_cast<float> (clusters[cluster_votes[cluster_i].first].size ());
246 
247  Eigen::Affine3f transform_average;
248  transform_average.translation ().matrix () = translation_average;
249  transform_average.linear ().matrix () = Eigen::Quaternionf (rotation_average).normalized().toRotationMatrix ();
250 
251  result.push_back (PoseWithVotes (transform_average, cluster_votes[cluster_i].second));
252  }
253 }
254 
255 
256 //////////////////////////////////////////////////////////////////////////////////////////////
257 template <typename PointSource, typename PointTarget> bool
259  Eigen::Affine3f &pose2)
260 {
261  float position_diff = (pose1.translation () - pose2.translation ()).norm ();
262  Eigen::AngleAxisf rotation_diff_mat ((pose1.rotation ().inverse ().lazyProduct (pose2.rotation ()).eval()));
263 
264  float rotation_diff_angle = std::abs (rotation_diff_mat.angle ());
265 
266  return (position_diff < clustering_position_diff_threshold_ && rotation_diff_angle < clustering_rotation_diff_threshold_);
267 }
268 
269 
270 //////////////////////////////////////////////////////////////////////////////////////////////
271 template <typename PointSource, typename PointTarget> bool
274 {
275  return (a.votes > b.votes);
276 }
277 
278 
279 //////////////////////////////////////////////////////////////////////////////////////////////
280 template <typename PointSource, typename PointTarget> bool
282  const std::pair<size_t, unsigned int> &b)
283 {
284  return (a.second > b.second);
285 }
286 
287 //#define PCL_INSTANTIATE_PPFRegistration(PointSource,PointTarget) template class PCL_EXPORTS pcl::PPFRegistration<PointSource, PointTarget>;
288 
289 #endif // PCL_REGISTRATION_IMPL_PPF_REGISTRATION_H_
boost::shared_ptr< KdTreeFLANN< PointT, Dist > > Ptr
Definition: kdtree_flann.h:87
std::vector< PoseWithVotes, Eigen::aligned_allocator< PoseWithVotes > > PoseWithVotesList
void setInputTarget(const PointCloudTargetConstPtr &cloud) override
Provide a pointer to the input target (e.g., the point cloud that we want to align the input source t...
void transformPointCloud(const pcl::PointCloud< PointT > &cloud_in, pcl::PointCloud< PointT > &cloud_out, const Eigen::Transform< Scalar, 3, Eigen::Affine > &transform, bool copy_all_fields=true)
Apply an affine transform defined by an Eigen Transform.
Definition: transforms.hpp:215
const PointT & front() const
Definition: point_cloud.h:483
typename PointCloudTarget::ConstPtr PointCloudTargetConstPtr
Registration represents the base registration class for general purpose, ICP-like methods...
Definition: registration.h:60
Structure for storing a pose (represented as an Eigen::Affine3f) and an integer for counting votes...
Class that registers two point clouds based on their sets of PPFSignatures.
PCL_EXPORTS bool computePairFeatures(const Eigen::Vector4f &p1, const Eigen::Vector4f &n1, const Eigen::Vector4f &p2, const Eigen::Vector4f &n2, float &f1, float &f2, float &f3, float &f4)
Compute the 4-tuple representation containing the three angles and one distance between two points re...