38 #ifndef PCL_REGISTRATION_IMPL_IA_FPCS_H_
39 #define PCL_REGISTRATION_IMPL_IA_FPCS_H_
43 #include <pcl/common/utils.h>
44 #include <pcl/registration/ia_fpcs.h>
45 #include <pcl/registration/transformation_estimation_3point.h>
46 #include <pcl/sample_consensus/sac_model_plane.h>
51 template <
typename Po
intT>
57 const float max_dist_sqr = max_dist * max_dist;
58 const std::size_t s = cloud->
size();
63 float mean_dist = 0.f;
66 std::vector<float> dists_sqr(2);
69 #pragma omp parallel for default(none) shared(tree, cloud) \
70 firstprivate(ids, dists_sqr) reduction(+ : mean_dist, num) \
71 firstprivate(s, max_dist_sqr) num_threads(nr_threads)
72 for (
int i = 0; i < 1000; i++) {
74 if (dists_sqr[1] < max_dist_sqr) {
75 mean_dist += std::sqrt(dists_sqr[1]);
80 return (mean_dist / num);
84 template <
typename Po
intT>
91 const float max_dist_sqr = max_dist * max_dist;
92 const std::size_t s = indices.size();
97 float mean_dist = 0.f;
100 std::vector<float> dists_sqr(2);
103 #if OPENMP_LEGACY_CONST_DATA_SHARING_RULE
104 #pragma omp parallel for default(none) shared(tree, cloud, indices) \
105 firstprivate(ids, dists_sqr) reduction(+ : mean_dist, num) num_threads(nr_threads)
107 #pragma omp parallel for default(none) shared(tree, cloud, indices, s, max_dist_sqr) \
108 firstprivate(ids, dists_sqr) reduction(+ : mean_dist, num) num_threads(nr_threads)
110 for (
int i = 0; i < 1000; i++) {
111 tree.
nearestKSearch((*cloud)[indices[rand() % s]], 2, ids, dists_sqr);
112 if (dists_sqr[1] < max_dist_sqr) {
113 mean_dist += std::sqrt(dists_sqr[1]);
118 return (mean_dist / num);
122 template <
typename Po
intSource,
typename Po
intTarget,
typename NormalT,
typename Scalar>
127 , score_threshold_(std::numeric_limits<float>::max())
128 , fitness_score_(std::numeric_limits<float>::max())
130 reg_name_ =
"pcl::registration::FPCSInitialAlignment";
138 template <
typename Po
intSource,
typename Po
intTarget,
typename NormalT,
typename Scalar>
146 final_transformation_ = guess;
148 std::vector<MatchingCandidates> all_candidates(max_iterations_);
151 #pragma omp parallel default(none) shared(abort, all_candidates, timer) \
152 num_threads(nr_threads_)
155 const unsigned int seed =
156 static_cast<unsigned int>(std::time(
nullptr)) ^ omp_get_thread_num();
158 PCL_DEBUG(
"[%s::computeTransformation] Using seed=%u\n", reg_name_.c_str(), seed);
159 #pragma omp for schedule(dynamic)
161 for (
int i = 0; i < max_iterations_; i++) {
162 #pragma omp flush(abort)
166 all_candidates[i] = candidates;
171 if (selectBase(base_indices, ratio) == 0) {
174 if (bruteForceCorrespondences(base_indices[0], base_indices[1], pairs_a) ==
176 bruteForceCorrespondences(base_indices[2], base_indices[3], pairs_b) ==
180 std::vector<pcl::Indices> matches;
181 if (determineBaseMatches(base_indices, matches, pairs_a, pairs_b, ratio) ==
184 handleMatches(base_indices, matches, candidates);
185 if (!candidates.empty())
186 all_candidates[i] = candidates;
192 abort = (!candidates.empty() ? candidates[0].fitness_score < score_threshold_
196 #pragma omp flush(abort)
202 finalCompute(all_candidates);
211 template <
typename Po
intSource,
typename Po
intTarget,
typename NormalT,
typename Scalar>
216 const unsigned int seed = std::time(
nullptr);
218 PCL_DEBUG(
"[%s::initCompute] Using seed=%u\n", reg_name_.c_str(), seed);
225 if (!input_ || !target_) {
226 PCL_ERROR(
"[%s::initCompute] Source or target dataset not given!\n",
231 if (!target_indices_ || target_indices_->empty()) {
232 target_indices_.reset(
new pcl::Indices(target_->size()));
234 for (
auto& target_index : *target_indices_)
235 target_index = index++;
236 target_cloud_updated_ =
true;
241 if (nr_samples_ != 0) {
242 const int ss =
static_cast<int>(indices_->size());
243 const int sample_fraction_src = std::max(1,
static_cast<int>(ss / nr_samples_));
246 for (
int i = 0; i < ss; i++)
247 if (rand() % sample_fraction_src == 0)
248 source_indices_->push_back((*indices_)[i]);
251 source_indices_ = indices_;
254 if (source_normals_ && target_normals_ && source_normals_->size() == input_->size() &&
255 target_normals_->size() == target_->size())
259 if (target_cloud_updated_) {
260 tree_->setInputCloud(target_, target_indices_);
261 target_cloud_updated_ =
false;
265 constexpr
int min_iterations = 4;
266 constexpr
float diameter_fraction = 0.3f;
269 Eigen::Vector4f pt_min, pt_max;
271 diameter_ = (pt_max - pt_min).norm();
274 float max_base_diameter = diameter_ * approx_overlap_ * 2.f;
275 max_base_diameter_sqr_ = max_base_diameter * max_base_diameter;
278 if (normalize_delta_) {
279 float mean_dist = getMeanPointDensity<PointTarget>(
280 target_, *target_indices_, 0.05f * diameter_, nr_threads_);
286 if (max_iterations_ == 0) {
287 float first_est = std::log(small_error_) /
288 std::log(1.0 - std::pow(
static_cast<double>(approx_overlap_),
289 static_cast<double>(min_iterations)));
291 static_cast<int>(first_est / (diameter_fraction * approx_overlap_ * 2.f));
295 if (score_threshold_ == std::numeric_limits<float>::max())
296 score_threshold_ = 1.f - approx_overlap_;
298 if (max_iterations_ < 4)
301 if (max_runtime_ < 1)
302 max_runtime_ = std::numeric_limits<int>::max();
305 max_pair_diff_ = delta_ * 2.f;
306 max_edge_diff_ = delta_ * 4.f;
307 coincidation_limit_ = delta_ * 2.f;
308 max_mse_ = powf(delta_ * 2.f, 2.f);
309 max_inlier_dist_sqr_ = powf(delta_ * 2.f, 2.f);
312 fitness_score_ = std::numeric_limits<float>::max();
318 template <
typename Po
intSource,
typename Po
intTarget,
typename NormalT,
typename Scalar>
323 const float too_close_sqr = max_base_diameter_sqr_ * 0.01;
325 Eigen::VectorXf coefficients(4);
328 Eigen::Vector4f centre_pt;
329 float nearest_to_plane = std::numeric_limits<float>::max();
333 for (
int i = 0; i < ransac_iterations_; i++) {
335 if (selectBaseTriangle(base_indices) < 0)
338 pcl::Indices base_triple(base_indices.begin(), base_indices.end() - 1);
343 const PointTarget* pt1 = &((*target_)[base_indices[0]]);
344 const PointTarget* pt2 = &((*target_)[base_indices[1]]);
345 const PointTarget* pt3 = &((*target_)[base_indices[2]]);
347 for (
const auto& target_index : *target_indices_) {
348 const PointTarget* pt4 = &((*target_)[target_index]);
353 float d4 = (pt4->getVector3fMap() - centre_pt.head<3>()).squaredNorm();
357 if (d1 < too_close_sqr || d2 < too_close_sqr || d3 < too_close_sqr ||
358 d4 < too_close_sqr || d1 > max_base_diameter_sqr_ ||
359 d2 > max_base_diameter_sqr_ || d3 > max_base_diameter_sqr_)
364 if (dist_to_plane < nearest_to_plane) {
365 base_indices[3] = target_index;
366 nearest_to_plane = dist_to_plane;
371 if (nearest_to_plane != std::numeric_limits<float>::max()) {
374 setupBase(base_indices, ratio);
384 template <
typename Po
intSource,
typename Po
intTarget,
typename NormalT,
typename Scalar>
389 const auto nr_points = target_indices_->size();
393 base_indices[0] = (*target_indices_)[rand() % nr_points];
394 auto* index1 = base_indices.data();
397 for (
int i = 0; i < ransac_iterations_; i++) {
398 auto* index2 = &(*target_indices_)[rand() % nr_points];
399 auto* index3 = &(*target_indices_)[rand() % nr_points];
402 (*target_)[*index2].getVector3fMap() - (*target_)[*index1].getVector3fMap();
404 (*target_)[*index3].getVector3fMap() - (*target_)[*index1].getVector3fMap();
406 u.cross(v).squaredNorm();
409 if (t > best_t && u.squaredNorm() < max_base_diameter_sqr_ &&
410 v.squaredNorm() < max_base_diameter_sqr_) {
412 base_indices[1] = *index2;
413 base_indices[2] = *index3;
418 return (best_t == 0.f ? -1 : 0);
422 template <
typename Po
intSource,
typename Po
intTarget,
typename NormalT,
typename Scalar>
427 float best_t = std::numeric_limits<float>::max();
428 const pcl::Indices copy(base_indices.begin(), base_indices.end());
429 pcl::Indices temp(base_indices.begin(), base_indices.end());
432 for (
auto i = copy.begin(), i_e = copy.end(); i != i_e; ++i)
433 for (
auto j = copy.begin(), j_e = copy.end(); j != j_e; ++j) {
437 for (
auto k = copy.begin(), k_e = copy.end(); k != k_e; ++k) {
438 if (k == j || k == i)
441 auto l = copy.begin();
442 while (l == i || l == j || l == k)
453 float t = segmentToSegmentDist(temp, ratio_temp);
456 ratio[0] = ratio_temp[0];
457 ratio[1] = ratio_temp[1];
465 template <
typename Po
intSource,
typename Po
intTarget,
typename NormalT,
typename Scalar>
471 Eigen::Vector3f u = (*target_)[base_indices[1]].getVector3fMap() -
472 (*target_)[base_indices[0]].getVector3fMap();
473 Eigen::Vector3f v = (*target_)[base_indices[3]].getVector3fMap() -
474 (*target_)[base_indices[2]].getVector3fMap();
475 Eigen::Vector3f w = (*target_)[base_indices[0]].getVector3fMap() -
476 (*target_)[base_indices[2]].getVector3fMap();
484 float D = a * c - b * b;
485 float sN = 0.f, sD = D;
486 float tN = 0.f, tD = D;
489 if (D < small_error_) {
496 sN = (b * e - c * d);
497 tN = (a * e - b * d);
532 else if ((-d + b) > a)
542 ratio[0] = (std::abs(sN) < small_error_) ? 0.f : sN / sD;
543 ratio[1] = (std::abs(tN) < small_error_) ? 0.f : tN / tD;
545 Eigen::Vector3f x = w + (ratio[0] * u) - (ratio[1] * v);
550 template <
typename Po
intSource,
typename Po
intTarget,
typename NormalT,
typename Scalar>
555 const float max_norm_diff = 0.5f * max_norm_diff_ *
M_PI / 180.f;
559 float ref_norm_angle =
560 (use_normals_ ? ((*target_normals_)[idx1].getNormalVector3fMap() -
561 (*target_normals_)[idx2].getNormalVector3fMap())
566 auto it_out = source_indices_->begin(), it_out_e = source_indices_->end() - 1;
567 auto it_in_e = source_indices_->end();
568 for (; it_out != it_out_e; it_out++) {
569 auto it_in = it_out + 1;
570 const PointSource* pt1 = &(*input_)[*it_out];
571 for (; it_in != it_in_e; it_in++) {
572 const PointSource* pt2 = &(*input_)[*it_in];
576 if (std::abs(dist - ref_dist) < max_pair_diff_) {
579 const NormalT* pt1_n = &((*source_normals_)[*it_out]);
580 const NormalT* pt2_n = &((*source_normals_)[*it_in]);
583 (pt1_n->getNormalVector3fMap() - pt2_n->getNormalVector3fMap()).norm();
585 (pt1_n->getNormalVector3fMap() + pt2_n->getNormalVector3fMap()).norm();
587 float norm_diff = std::min<float>(std::abs(norm_angle_1 - ref_norm_angle),
588 std::abs(norm_angle_2 - ref_norm_angle));
589 if (norm_diff > max_norm_diff)
600 return (pairs.empty() ? -1 : 0);
604 template <
typename Po
intSource,
typename Po
intTarget,
typename NormalT,
typename Scalar>
608 std::vector<pcl::Indices>& matches,
611 const float (&ratio)[2])
627 cloud_e->resize(pairs_a.size() * 2);
628 auto it_pt = cloud_e->begin();
629 for (
const auto& pair : pairs_a) {
630 const PointSource* pt1 = &((*input_)[pair.index_match]);
631 const PointSource* pt2 = &((*input_)[pair.index_query]);
634 for (
int i = 0; i < 2; i++, it_pt++) {
635 it_pt->x = pt1->x + ratio[i] * (pt2->x - pt1->x);
636 it_pt->y = pt1->y + ratio[i] * (pt2->y - pt1->y);
637 it_pt->z = pt1->z + ratio[i] * (pt2->z - pt1->z);
643 tree_e->setInputCloud(cloud_e);
646 std::vector<float> dists_sqr;
649 for (
const auto& pair : pairs_b) {
650 const PointTarget* pt1 = &((*input_)[pair.index_match]);
651 const PointTarget* pt2 = &((*input_)[pair.index_query]);
654 for (
const float& r : ratio) {
656 pt_e.x = pt1->x + r * (pt2->x - pt1->x);
657 pt_e.y = pt1->y + r * (pt2->y - pt1->y);
658 pt_e.z = pt1->z + r * (pt2->z - pt1->z);
661 tree_e->radiusSearch(pt_e, coincidation_limit_, ids, dists_sqr);
662 for (
const auto&
id : ids) {
666 pairs_a[
static_cast<int>(std::floor((
id / 2.f)))].index_match;
668 pairs_a[
static_cast<int>(std::floor((
id / 2.f)))].index_query;
669 match_indices[2] = pair.index_match;
670 match_indices[3] = pair.index_query;
673 if (checkBaseMatch(match_indices, dist_base) < 0)
676 matches.push_back(match_indices);
682 return (!matches.empty() ? 0 : -1);
686 template <
typename Po
intSource,
typename Po
intTarget,
typename NormalT,
typename Scalar>
701 return (std::abs(d0 - dist_ref[0]) < max_edge_diff_ &&
702 std::abs(d1 - dist_ref[1]) < max_edge_diff_ &&
703 std::abs(d2 - dist_ref[2]) < max_edge_diff_ &&
704 std::abs(d3 - dist_ref[3]) < max_edge_diff_)
710 template <
typename Po
intSource,
typename Po
intTarget,
typename NormalT,
typename Scalar>
714 std::vector<pcl::Indices>& matches,
717 candidates.resize(1);
718 float fitness_score = std::numeric_limits<float>::max();
721 for (
auto& match : matches) {
722 Eigen::Matrix4f transformation_temp;
727 linkMatchWithBase(base_indices, match, correspondences_temp);
730 if (validateMatch(base_indices, match, correspondences_temp, transformation_temp) <
736 if (validateTransformation(transformation_temp, fitness_score) < 0)
740 candidates[0].fitness_score = fitness_score;
741 candidates[0].transformation = transformation_temp;
742 correspondences_temp.erase(correspondences_temp.end() - 1);
743 candidates[0].correspondences = correspondences_temp;
748 template <
typename Po
intSource,
typename Po
intTarget,
typename NormalT,
typename Scalar>
756 Eigen::Vector4f centre_base{0, 0, 0, 0}, centre_match{0, 0, 0, 0};
760 PointTarget centre_pt_base;
761 centre_pt_base.x = centre_base[0];
762 centre_pt_base.y = centre_base[1];
763 centre_pt_base.z = centre_base[2];
765 PointSource centre_pt_match;
766 centre_pt_match.x = centre_match[0];
767 centre_pt_match.y = centre_match[1];
768 centre_pt_match.z = centre_match[2];
773 auto it_match_orig = match_indices.begin();
774 for (
auto it_base = base_indices.cbegin(), it_base_e = base_indices.cend();
775 it_base != it_base_e;
776 it_base++, it_match_orig++) {
779 float best_diff_sqr = std::numeric_limits<float>::max();
782 for (
const auto& match_index : copy) {
786 float diff_sqr = std::abs(dist_sqr_1 - dist_sqr_2);
788 if (diff_sqr < best_diff_sqr) {
789 best_diff_sqr = diff_sqr;
790 best_index = match_index;
796 *it_match_orig = best_index;
801 template <
typename Po
intSource,
typename Po
intTarget,
typename NormalT,
typename Scalar>
807 Eigen::Matrix4f& transformation)
811 correspondences_temp.erase(correspondences_temp.end() - 1);
814 transformation_estimation_->estimateRigidTransformation(
815 *input_, *target_, correspondences_temp, transformation);
818 PointCloudSource match_transformed;
822 std::size_t nr_points = correspondences_temp.size();
824 for (std::size_t i = 0; i < nr_points; i++)
826 target_->points[base_indices[i]]);
829 return (mse < max_mse_ ? 0 : -1);
833 template <
typename Po
intSource,
typename Po
intTarget,
typename NormalT,
typename Scalar>
839 PointCloudSource source_transformed;
841 *input_, *source_indices_, source_transformed, transformation);
843 std::size_t nr_points = source_transformed.size();
844 std::size_t terminate_value =
845 fitness_score > 1 ? 0
846 :
static_cast<std::size_t
>((1.f - fitness_score) * nr_points);
848 float inlier_score_temp = 0;
850 std::vector<float> dists_sqr;
851 auto it = source_transformed.begin();
853 for (std::size_t i = 0; i < nr_points; it++, i++) {
855 tree_->nearestKSearch(*it, 1, ids, dists_sqr);
856 inlier_score_temp += (dists_sqr[0] < max_inlier_dist_sqr_ ? 1 : 0);
859 if (nr_points - i + inlier_score_temp < terminate_value)
864 inlier_score_temp /=
static_cast<float>(nr_points);
865 float fitness_score_temp = 1.f - inlier_score_temp;
867 if (fitness_score_temp > fitness_score)
870 fitness_score = fitness_score_temp;
875 template <
typename Po
intSource,
typename Po
intTarget,
typename NormalT,
typename Scalar>
878 finalCompute(
const std::vector<MatchingCandidates>& candidates)
881 int nr_candidates =
static_cast<int>(candidates.size());
883 float best_score = std::numeric_limits<float>::max();
884 for (
int i = 0; i < nr_candidates; i++) {
885 const float& fitness_score = candidates[i][0].fitness_score;
886 if (fitness_score < best_score) {
887 best_score = fitness_score;
893 if (!(best_index < 0)) {
894 fitness_score_ = candidates[best_index][0].fitness_score;
895 final_transformation_ = candidates[best_index][0].transformation;
896 *correspondences_ = candidates[best_index][0].correspondences;
899 converged_ = fitness_score_ < score_threshold_;
shared_ptr< const PointCloud< PointT > > ConstPtr
typename KdTreeReciprocal::Ptr KdTreeReciprocalPtr
std::string reg_name_
The registration method name.
typename PointCloudSource::Ptr PointCloudSourcePtr
int ransac_iterations_
The number of iterations RANSAC should run for.
TransformationEstimationPtr transformation_estimation_
A TransformationEstimation object, used to calculate the 4x4 rigid transformation.
int max_iterations_
The maximum number of iterations the internal optimization should run for.
void setIndices(const IndicesPtr &indices)
Provide a pointer to the vector of indices that represents the input data.
SampleConsensusModelPlane defines a model for 3D plane segmentation.
bool computeModelCoefficients(const Indices &samples, Eigen::VectorXf &model_coefficients) const override
Check whether the given index samples can form a valid plane model, compute the model coefficients fr...
double getTimeSeconds() const
Retrieve the time in seconds spent since the last call to reset().
virtual void finalCompute(const std::vector< MatchingCandidates > &candidates)
Final computation of best match out of vector of best matches.
void setupBase(pcl::Indices &base_indices, float(&ratio)[2])
Setup the base (four coplanar points) by ordering the points and computing intersection ratios and se...
int selectBaseTriangle(pcl::Indices &base_indices)
Select randomly a triplet of points with large point-to-point distances.
virtual int bruteForceCorrespondences(int idx1, int idx2, pcl::Correspondences &pairs)
Search for corresponding point pairs given the distance between two base points.
int selectBase(pcl::Indices &base_indices, float(&ratio)[2])
Select an approximately coplanar set of four points from the source cloud.
virtual int validateTransformation(Eigen::Matrix4f &transformation, float &fitness_score)
Validate the transformation by calculating the number of inliers after transforming the source cloud.
virtual int determineBaseMatches(const pcl::Indices &base_indices, std::vector< pcl::Indices > &matches, const pcl::Correspondences &pairs_a, const pcl::Correspondences &pairs_b, const float(&ratio)[2])
Determine base matches by combining the point pair candidate and search for coinciding intersection p...
virtual void linkMatchWithBase(const pcl::Indices &base_indices, pcl::Indices &match_indices, pcl::Correspondences &correspondences)
Sets the correspondences between the base B and the match M by using the distance of each point to th...
virtual void handleMatches(const pcl::Indices &base_indices, std::vector< pcl::Indices > &matches, MatchingCandidates &candidates)
Method to handle current candidate matches.
int checkBaseMatch(const pcl::Indices &match_indices, const float(&ds)[4])
Check if outer rectangle distance of matched points fit with the base rectangle.
float segmentToSegmentDist(const pcl::Indices &base_indices, float(&ratio)[2])
Calculate intersection ratios and segment to segment distances of base diagonals.
virtual int validateMatch(const pcl::Indices &base_indices, const pcl::Indices &match_indices, const pcl::Correspondences &correspondences, Eigen::Matrix4f &transformation)
Validate the matching by computing the transformation between the source and target based on the four...
FPCSInitialAlignment()
Constructor.
void computeTransformation(PointCloudSource &output, const Eigen::Matrix4f &guess) override
Rigid transformation computation method.
virtual bool initCompute()
Internal computation initialization.
search::KdTree is a wrapper class which inherits the pcl::KdTree class for performing search function...
int nearestKSearch(const PointT &point, int k, Indices &k_indices, std::vector< float > &k_sqr_distances) const override
Search for the k-nearest neighbors for the given query point.
bool setInputCloud(const PointCloudConstPtr &cloud, const IndicesConstPtr &indices=IndicesConstPtr()) override
Provide a pointer to the input dataset.
Define standard C methods to do distance calculations.
Define methods for measuring time spent in code blocks.
void getMinMax3D(const pcl::PointCloud< PointT > &cloud, PointT &min_pt, PointT &max_pt)
Get the minimum and maximum values on each of the 3 (x-y-z) dimensions in a given pointcloud.
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.
unsigned int compute3DCentroid(ConstCloudIterator< PointT > &cloud_iterator, Eigen::Matrix< Scalar, 4, 1 > ¢roid)
Compute the 3D (X-Y-Z) centroid of a set of points and return it as a 3D vector.
double pointToPlaneDistance(const Point &p, double a, double b, double c, double d)
Get the distance from a point to a plane (unsigned) defined by ax+by+cz+d=0.
std::vector< MatchingCandidate, Eigen::aligned_allocator< MatchingCandidate > > MatchingCandidates
void ignore(const T &...)
Utility function to eliminate unused variable warnings.
float squaredEuclideanDistance(const PointType1 &p1, const PointType2 &p2)
Calculate the squared euclidean distance between the two given points.
float getMeanPointDensity(const typename pcl::PointCloud< PointT >::ConstPtr &cloud, float max_dist, int nr_threads=1)
Compute the mean point density of a given point cloud.
std::vector< pcl::Correspondence, Eigen::aligned_allocator< pcl::Correspondence > > Correspondences
float euclideanDistance(const PointType1 &p1, const PointType2 &p2)
Calculate the euclidean distance between the two given points.
IndicesAllocator<> Indices
Type used for indices in PCL.
shared_ptr< Indices > IndicesPtr
Correspondence represents a match between two entities (e.g., points, descriptors,...
A point structure representing normal coordinates and the surface curvature estimate.