如题,使用库函数进行svd分解,形如 A = U * S * VT.

Eigen 库:

#include <iostream>
#include <Eigen/SVD>
#include <Eigen/Dense>  
  
//using Eigen::MatrixXf;  
using namespace Eigen;  
using namespace Eigen::internal;  
using namespace Eigen::Architecture;  

int main()
{
//-------------------------------svd测试    eigen
	Matrix3f A;
	A(0,0)=1,A(0,1)=0,A(0,2)=1;
	A(1,0)=0,A(1,1)=1,A(1,2)=1;
	A(2,0)=0,A(2,1)=0,A(2,2)=0;
	JacobiSVD<Eigen::MatrixXf> svd(A, ComputeThinU | ComputeThinV );
	Matrix3f V = svd.matrixV(), U = svd.matrixU();
	Matrix3f  S = U.inverse() * A * V.transpose().inverse(); // S = U^-1 * A * VT * -1
	std::cout<<"A :\n"<<A<<std::endl;
	std::cout<<"U :\n"<<U<<std::endl;
	std::cout<<"S :\n"<<S<<std::endl;
	std::cout<<"V :\n"<<V<<std::endl;
	std::cout<<"U * S * VT :\n"<<U * S * V.transpose()<<std::endl;
 	system("pause");
	//-------------------------------svd测试    eigen

	return 0;
}



OpenCV库:


#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include"opencv2/imgproc/imgproc.hpp"
#include <iostream>
 
using namespace std;
using namespace cv;

void print(CvMat& m){
	for (int row = 0; row < m.rows; row++){
		float* ptr = (float*)(m.data.ptr + row * m.step);//第row行数据的起始指针
		for (int col = 0; col < m.cols; col++)
			cout<<*(ptr+3*col)<<"     ";
		std::cout<<std::endl;
	}
}
int main ()
{
	float abt[3 * 3] = {
		1,0,1,
		0,1,1,
		0,0,0
	};
	float abt_d[3 * 3]={0}, abt_u[3 * 3]={0}, abt_v[3 * 3]={0};
	
	CvMat ABt   = cvMat(3, 3, CV_64F, abt);//CvMat 取对数组的引用而不是拷贝
	CvMat ABt_D = cvMat(3, 3, CV_64F, abt_d);
	CvMat ABt_U = cvMat(3, 3, CV_64F, abt_u);
	CvMat ABt_VT = cvMat(3, 3, CV_64F, abt_v);

	cvSVD(&ABt, &ABt_D, &ABt_U, &ABt_VT, CV_SVD_V_T);//最后一个参数用于控制返回 UT或U  VT或V
	std::cout<<"A : "<<std::endl;
	print(ABt);
	std::cout<<"U : "<<std::endl;
	print(ABt_U);
	std::cout<<"S : "<<std::endl;
	print(ABt_D);
	std::cout<<"V : "<<std::endl;
	print(ABt_VT);
	system("pause");
	return 0;
}





GitHub 加速计划 / opencv31 / opencv
238
21
下载
OpenCV: 开源计算机视觉库
最近提交(Master分支:4 个月前 )
74addff3 docs: fix spelling errors in code and comments 13 小时前
4cfd9689 Fix UB in cv::error when breakOnError set to true 16 小时前
Logo

AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。

更多推荐