Visual Computing Library
Loading...
Searching...
No Matches
fitting.h
1/*****************************************************************************
2 * VCLib *
3 * Visual Computing Library *
4 * *
5 * Copyright(C) 2021-2025 *
6 * Visual Computing Lab *
7 * ISTI - Italian National Research Council *
8 * *
9 * All rights reserved. *
10 * *
11 * This program is free software; you can redistribute it and/or modify *
12 * it under the terms of the Mozilla Public License Version 2.0 as published *
13 * by the Mozilla Foundation; either version 2 of the License, or *
14 * (at your option) any later version. *
15 * *
16 * This program is distributed in the hope that it will be useful, *
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
19 * Mozilla Public License Version 2.0 *
20 * (https://www.mozilla.org/en-US/MPL/2.0/) for more details. *
21 ****************************************************************************/
22
23#ifndef VCL_ALGORITHMS_CORE_FITTING_H
24#define VCL_ALGORITHMS_CORE_FITTING_H
25
26#include "stat.h"
27
28#include <vclib/space/core/plane.h>
29
30#include <Eigen/Eigenvalues>
31
32namespace vcl {
33
38template<typename Scalar>
39Plane<Scalar> fitPlaneToPointCloud(const std::vector<Point3<Scalar>>& pointVec)
40{
41 Matrix33<Scalar> covMat = covarianceMatrixOfPointCloud(pointVec);
42 Point3<Scalar> b = polygonBarycenter(pointVec.begin(), pointVec.end());
43
44 Eigen::SelfAdjointEigenSolver<Eigen::Matrix<Scalar, 3, 3>> eig(covMat);
45
46 Eigen::Matrix<Scalar, 3, 1> eval = eig.eigenvalues();
47 Eigen::Matrix<Scalar, 3, 3> evec = eig.eigenvectors();
48
49 eval = eval.cwiseAbs();
50 int minInd;
51 eval.minCoeff(&minInd);
52 Point3<Scalar> d;
53 d[0] = evec(0, minInd);
54 d[1] = evec(1, minInd);
55 d[2] = evec(2, minInd);
56
57 return Plane<Scalar>(b, d);
58}
59
64template<Point3Concept PointType>
65Plane<typename PointType::ScalarType> fitPlaneToWeightedPointCloud(
66 const std::vector<PointType>& pointVec,
67 const std::vector<typename PointType::ScalarType>& weights)
68{
69 using Scalar = typename PointType::ScalarType;
70
71 Matrix33<Scalar> covMat =
72 weightedCovarianceMatrixOfPointCloud(pointVec, weights);
73 Point3<Scalar> b =
75
76 Eigen::SelfAdjointEigenSolver<Eigen::Matrix<Scalar, 3, 3>> eig(covMat);
77
78 Eigen::Matrix<Scalar, 3, 1> eval = eig.eigenvalues();
79 Eigen::Matrix<Scalar, 3, 3> evec = eig.eigenvectors();
80
81 eval = eval.cwiseAbs();
82 int minInd;
83 eval.minCoeff(&minInd);
84 Point3<Scalar> d;
85 d[0] = evec(0, minInd);
86 d[1] = evec(1, minInd);
87 d[2] = evec(2, minInd);
88
89 return Plane<Scalar>(b, d);
90}
91
92} // namespace vcl
93
94#endif // VCL_ALGORITHMS_CORE_FITTING_H
PointT weightedBarycenter(WIterator wBegin) const
Computes the weighted barycenter of the polygon.
Definition polygon.h:218