Eigen这个库,早在研究生阶段的时候,就用到烂了,因为三维的图形算法经常要涉及到求解稀疏矩阵。然而工作一年都没碰到Eigen,突然今天要用到求解稀疏矩阵最小二乘方程组,变得有点陌生了,惭愧,因此简单记录一下,以便日后重新复制粘贴修改使用。
#include "Eigen/Sparse"
typedef Eigen::SparseMatrix<double> SparseMatrixType;
#include <vector>
using namespace std;
vec CDepthRegression::Get_LightDirection()
{
vec light;
int fn = m_mesh->faces.size();
typedef Eigen::Triplet<double> T;
std::vector<T> tripletList;//稀疏矩阵的元素
for (int i = 0; i < fn;i++)
{
const TriMesh::Face &f = m_mesh->faces[i];
vec v0 = m_mesh->vertices[f[0]];
vec v1 = m_mesh->vertices[f[1]];
vec v2 = m_mesh->vertices[f[2]];
vec facenormal = (v2 - v1) CROSS(v0 - v2);
facenormal = normalize(facenormal);
for (int j = 0; j < 3;j++)
{
tripletList.push_back(T(i,j, facenormal[j]));
}
}
SparseMatrixType Ls(fn, 3);//矩阵的宽高
Ls.setFromTriplets(tripletList.begin(), tripletList.end());//从Triplet中构建稀疏矩阵
//最小二乘解超静定方程组
SparseMatrixType ls_transpose = Ls.transpose();
SparseMatrixType LsLs = ls_transpose* Ls;
Eigen::VectorXd RHSPos;//超静定方程组右边
RHSPos.resize(fn);
RHSPos.setZero();
for (int i = 0; i < fn;i++)
{
float I = m_mesh->face_color[i];
RHSPos[i] = I;
}
Eigen::SimplicialCholesky<SparseMatrixType>MatricesCholesky(LsLs);
Eigen::VectorXd xyzRHS = ls_transpose*RHSPos;
Eigen::Vector3d xyz = MatricesCholesky.solve(xyzRHS);
return vec(xyz[0],xyz[1], xyz[2]);
}