Point Cloud Library (PCL)  1.12.1-dev
ia_kfpcs.hpp
1 /*
2  * Software License Agreement (BSD License)
3  *
4  * Point Cloud Library (PCL) - www.pointclouds.org
5  * Copyright (c) 2014-, Open Perception, Inc.
6  *
7  * All rights reserved
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions are met
11  *
12  * * Redistributions of source code must retain the above copyright
13  * notice, this list of conditions and the following disclaimer.
14  * * Redistributions in binary form must reproduce the above
15  * copyright notice, this list of conditions and the following
16  * disclaimer in the documentation and/or other materials provided
17  * with the distribution.
18  * * Neither the name of the copyright holder(s) nor the names of its
19  * contributors may be used to endorse or promote products derived
20  * from this software without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
25  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
26  * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
27  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
28  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
29  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
30  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
32  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33  * POSSIBILITY OF SUCH DAMAGE.
34  *
35  */
36 
37 #ifndef PCL_REGISTRATION_IMPL_IA_KFPCS_H_
38 #define PCL_REGISTRATION_IMPL_IA_KFPCS_H_
39 
40 #include <limits>
41 
42 namespace pcl {
43 
44 namespace registration {
45 
46 template <typename PointSource, typename PointTarget, typename NormalT, typename Scalar>
49 : lower_trl_boundary_(-1.f)
50 , upper_trl_boundary_(-1.f)
51 , lambda_(0.5f)
52 , use_trl_score_(false)
53 , indices_validation_(new pcl::Indices)
54 {
55  reg_name_ = "pcl::registration::KFPCSInitialAlignment";
56 }
57 
58 template <typename PointSource, typename PointTarget, typename NormalT, typename Scalar>
59 bool
61 {
62  // due to sparse keypoint cloud, do not normalize delta with estimated point density
63  if (normalize_delta_) {
64  PCL_WARN("[%s::initCompute] Delta should be set according to keypoint precision! "
65  "Normalization according to point cloud density is ignored.\n",
66  reg_name_.c_str());
67  normalize_delta_ = false;
68  }
69 
70  // initialize as in fpcs
72  initCompute();
73 
74  // set the threshold values with respect to keypoint charactersitics
75  max_pair_diff_ = delta_ * 1.414f; // diff between 2 points of delta_ accuracy
76  coincidation_limit_ = delta_ * 2.828f; // diff between diff of 2 points
77  max_edge_diff_ =
78  delta_ *
79  3.f; // diff between 2 points + some inaccuracy due to quadruple orientation
80  max_mse_ =
81  powf(delta_ * 4.f, 2.f); // diff between 2 points + some registration inaccuracy
82  max_inlier_dist_sqr_ =
83  powf(delta_ * 8.f,
84  2.f); // set rel. high, because MSAC is used (residual based score function)
85 
86  // check use of translation costs and calculate upper boundary if not set by user
87  if (upper_trl_boundary_ < 0)
88  upper_trl_boundary_ = diameter_ * (1.f - approx_overlap_) * 0.5f;
89 
90  if (!(lower_trl_boundary_ < 0) && upper_trl_boundary_ > lower_trl_boundary_)
91  use_trl_score_ = true;
92  else
93  lambda_ = 0.f;
94 
95  // generate a subset of indices of size ransac_iterations_ on which to evaluate
96  // candidates on
97  std::size_t nr_indices = indices_->size();
98  if (nr_indices < std::size_t(ransac_iterations_))
99  indices_validation_ = indices_;
100  else
101  for (int i = 0; i < ransac_iterations_; i++)
102  indices_validation_->push_back((*indices_)[rand() % nr_indices]);
103 
104  return (true);
105 }
106 
107 template <typename PointSource, typename PointTarget, typename NormalT, typename Scalar>
108 void
110  const pcl::Indices& base_indices,
111  std::vector<pcl::Indices>& matches,
112  MatchingCandidates& candidates)
113 {
114  candidates.clear();
115 
116  // loop over all Candidate matches
117  for (auto& match : matches) {
118  Eigen::Matrix4f transformation_temp;
119  pcl::Correspondences correspondences_temp;
120  float fitness_score =
121  std::numeric_limits<float>::max(); // reset to std::numeric_limits<float>::max()
122  // to accept all candidates and not only best
123 
124  // determine corresondences between base and match according to their distance to
125  // centroid
126  linkMatchWithBase(base_indices, match, correspondences_temp);
127 
128  // check match based on residuals of the corresponding points after transformation
129  if (validateMatch(base_indices, match, correspondences_temp, transformation_temp) <
130  0)
131  continue;
132 
133  // check resulting transformation using a sub sample of the source point cloud
134  // all candidates are stored and later sorted according to their fitness score
135  validateTransformation(transformation_temp, fitness_score);
136 
137  // store all valid match as well as associated score and transformation
138  candidates.push_back(
139  MatchingCandidate(fitness_score, correspondences_temp, transformation_temp));
140  }
141 }
142 
143 template <typename PointSource, typename PointTarget, typename NormalT, typename Scalar>
144 int
146  validateTransformation(Eigen::Matrix4f& transformation, float& fitness_score)
147 {
148  // transform sub sampled source cloud
149  PointCloudSource source_transformed;
151  *input_, *indices_validation_, source_transformed, transformation);
152 
153  const std::size_t nr_points = source_transformed.size();
154  float score_a = 0.f, score_b = 0.f;
155 
156  // residual costs based on mse
157  pcl::Indices ids;
158  std::vector<float> dists_sqr;
159  for (PointCloudSourceIterator it = source_transformed.begin(),
160  it_e = source_transformed.end();
161  it != it_e;
162  ++it) {
163  // search for nearest point using kd tree search
164  tree_->nearestKSearch(*it, 1, ids, dists_sqr);
165  score_a += (dists_sqr[0] < max_inlier_dist_sqr_ ? dists_sqr[0]
166  : max_inlier_dist_sqr_); // MSAC
167  }
168 
169  score_a /= (max_inlier_dist_sqr_ * nr_points); // MSAC
170  // score_a = 1.f - (1.f - score_a) / (1.f - approx_overlap_); // make score relative
171  // to estimated overlap
172 
173  // translation score (solutions with small translation are down-voted)
174  float scale = 1.f;
175  if (use_trl_score_) {
176  float trl = transformation.rightCols<1>().head(3).norm();
177  float trl_ratio =
178  (trl - lower_trl_boundary_) / (upper_trl_boundary_ - lower_trl_boundary_);
179 
180  score_b =
181  (trl_ratio < 0.f ? 1.f
182  : (trl_ratio > 1.f ? 0.f
183  : 0.5f * sin(M_PI * trl_ratio + M_PI_2) +
184  0.5f)); // sinusoidal costs
185  scale += lambda_;
186  }
187 
188  // calculate the fitness and return unsuccessful if smaller than previous ones
189  float fitness_score_temp = (score_a + lambda_ * score_b) / scale;
190  if (fitness_score_temp > fitness_score)
191  return (-1);
192 
193  fitness_score = fitness_score_temp;
194  return (0);
195 }
196 
197 template <typename PointSource, typename PointTarget, typename NormalT, typename Scalar>
198 void
200  const std::vector<MatchingCandidates>& candidates)
201 {
202  // reorganize candidates into single vector
203  std::size_t total_size = 0;
204  for (const auto& candidate : candidates)
205  total_size += candidate.size();
206 
207  candidates_.clear();
208  candidates_.reserve(total_size);
209 
210  for (const auto& candidate : candidates)
211  for (const auto& match : candidate)
212  candidates_.push_back(match);
213 
214  // sort according to score value
215  std::sort(candidates_.begin(), candidates_.end(), by_score());
216 
217  // return here if no score was valid, i.e. all scores are
218  // std::numeric_limits<float>::max()
219  if (candidates_[0].fitness_score == std::numeric_limits<float>::max()) {
220  converged_ = false;
221  return;
222  }
223 
224  // save best candidate as output result
225  // note, all other candidates are accessible via getNBestCandidates () and
226  // getTBestCandidates ()
227  fitness_score_ = candidates_[0].fitness_score;
228  final_transformation_ = candidates_[0].transformation;
229  *correspondences_ = candidates_[0].correspondences;
230 
231  // here we define convergence if resulting score is above threshold
232  converged_ = fitness_score_ < score_threshold_;
233 }
234 
235 template <typename PointSource, typename PointTarget, typename NormalT, typename Scalar>
236 void
238  int n, float min_angle3d, float min_translation3d, MatchingCandidates& candidates)
239 {
240  candidates.clear();
241 
242  // loop over all candidates starting from the best one
243  for (MatchingCandidates::iterator it_candidate = candidates_.begin(),
244  it_e = candidates_.end();
245  it_candidate != it_e;
246  ++it_candidate) {
247  // stop if current candidate has no valid score
248  if (it_candidate->fitness_score == std::numeric_limits<float>::max())
249  return;
250 
251  // check if current candidate is a unique one compared to previous using the
252  // min_diff threshold
253  bool unique = true;
254  MatchingCandidates::iterator it = candidates.begin(), it_e2 = candidates.end();
255  while (unique && it != it_e2) {
256  Eigen::Matrix4f diff =
257  it_candidate->transformation.colPivHouseholderQr().solve(it->transformation);
258  const float angle3d = Eigen::AngleAxisf(diff.block<3, 3>(0, 0)).angle();
259  const float translation3d = diff.block<3, 1>(0, 3).norm();
260  unique = angle3d > min_angle3d && translation3d > min_translation3d;
261  ++it;
262  }
263 
264  // add candidate to best candidates
265  if (unique)
266  candidates.push_back(*it_candidate);
267 
268  // stop if n candidates are reached
269  if (candidates.size() == n)
270  return;
271  }
272 }
273 
274 template <typename PointSource, typename PointTarget, typename NormalT, typename Scalar>
275 void
277  float t, float min_angle3d, float min_translation3d, MatchingCandidates& candidates)
278 {
279  candidates.clear();
280 
281  // loop over all candidates starting from the best one
282  for (MatchingCandidates::iterator it_candidate = candidates_.begin(),
283  it_e = candidates_.end();
284  it_candidate != it_e;
285  ++it_candidate) {
286  // stop if current candidate has score below threshold
287  if (it_candidate->fitness_score > t)
288  return;
289 
290  // check if current candidate is a unique one compared to previous using the
291  // min_diff threshold
292  bool unique = true;
293  MatchingCandidates::iterator it = candidates.begin(), it_e2 = candidates.end();
294  while (unique && it != it_e2) {
295  Eigen::Matrix4f diff =
296  it_candidate->transformation.colPivHouseholderQr().solve(it->transformation);
297  const float angle3d = Eigen::AngleAxisf(diff.block<3, 3>(0, 0)).angle();
298  const float translation3d = diff.block<3, 1>(0, 3).norm();
299  unique = angle3d > min_angle3d && translation3d > min_translation3d;
300  ++it;
301  }
302 
303  // add candidate to best candidates
304  if (unique)
305  candidates.push_back(*it_candidate);
306  }
307 }
308 
309 } // namespace registration
310 } // namespace pcl
311 
312 #endif // PCL_REGISTRATION_IMPL_IA_KFPCS_H_
iterator end() noexcept
Definition: point_cloud.h:430
std::size_t size() const
Definition: point_cloud.h:443
iterator begin() noexcept
Definition: point_cloud.h:429
std::string reg_name_
The registration method name.
Definition: registration.h:560
virtual bool initCompute()
Internal computation initialization.
Definition: ia_fpcs.hpp:242
void getTBestCandidates(float t, float min_angle3d, float min_translation3d, MatchingCandidates &candidates)
Get all unique candidate matches with fitness scores above a threshold t.
Definition: ia_kfpcs.hpp:276
void finalCompute(const std::vector< MatchingCandidates > &candidates) override
Final computation of best match out of vector of matches.
Definition: ia_kfpcs.hpp:199
void handleMatches(const pcl::Indices &base_indices, std::vector< pcl::Indices > &matches, MatchingCandidates &candidates) override
Method to handle current candidate matches.
Definition: ia_kfpcs.hpp:109
void getNBestCandidates(int n, float min_angle3d, float min_translation3d, MatchingCandidates &candidates)
Get the N best unique candidate matches according to their fitness score.
Definition: ia_kfpcs.hpp:237
int validateTransformation(Eigen::Matrix4f &transformation, float &fitness_score) override
Validate the transformation by calculating the score value after transforming the input source cloud.
Definition: ia_kfpcs.hpp:146
bool initCompute() override
Internal computation initialization.
Definition: ia_kfpcs.hpp:60
void transformPointCloud(const pcl::PointCloud< PointT > &cloud_in, pcl::PointCloud< PointT > &cloud_out, const Eigen::Matrix< Scalar, 4, 4 > &transform, bool copy_all_fields)
Apply a rigid transform defined by a 4x4 matrix.
Definition: transforms.hpp:221
std::vector< MatchingCandidate, Eigen::aligned_allocator< MatchingCandidate > > MatchingCandidates
std::vector< pcl::Correspondence, Eigen::aligned_allocator< pcl::Correspondence > > Correspondences
IndicesAllocator<> Indices
Type used for indices in PCL.
Definition: types.h:133
#define M_PI_2
Definition: pcl_macros.h:202
#define M_PI
Definition: pcl_macros.h:201
Container for matching candidate consisting of.
Sorting of candidates based on fitness score value.