java svd_SVD分解 opencv实现(示例代码)

本文展示了如何使用OpenCV库在C++中实现Singular Value Decomposition (SVD)。通过示例代码,解释了如何将二维浮点数矩阵分解为奇异值、左奇异向量和右奇异向量的转置矩阵,并验证了分解结果的正确性。
摘要由CSDN通过智能技术生成

头文件

#ifndef DEBUG_LRN_SVD_H

#define DEBUG_LRN_SVD_H

#include

#include

#include

#include

#include

using namespace std;

using namespace cv;

int test_SVD();

void print_matrix(const vector>& vec);

#endif //DEBUG_LRN_SVD_H

源文件

#include "svd.h"

void print_matrix(const vector>& vec){

if(vec.empty()){

return;

}

for ( auto row: vec){

if(row.empty()){

return;

}

for ( auto elem: row){

cout << elem << ", ";

}

cout << endl;

}

cout << endl;

}

int test_SVD()

{

std::vector<:vector>> vec{ { 0.68f, 0.597f },

{ -0.211f, 0.823f },

{ 0.566f, -0.605f } };

cout << "source matrix:" << endl;

print_matrix(vec);

// cout << "C++ implement SVD:" << endl;

// vector> matD, matU, matVt;

// if (svd(vec, matD, matU, matVt) != 0) {

// cout << "C++ implement singular value decomposition fail!" << endl;

// return -1;

// }

// cout << "singular values:" << endl;

// print_matrix(matD);

// cout << "left singular vectors:" << endl;

// print_matrix(matU);

// cout << "transposed matrix of right singular values:" << endl;

// print_matrix(matVt);

cout << "opencv singular value decomposition:" << endl;

const auto rows = (int)vec.size();

const auto cols = (int)vec[0].size();

cv::Mat mat(rows, cols, CV_32FC1);

for (int y = 0; y < rows; ++y) {

for (int x = 0; x < cols; ++x) {

mat.at(y, x) = vec.at(y).at(x);

}

}

cv::Mat matD, matU, matVt;

cv::SVD::compute(mat, matD, matU, matVt, 4);

cout << "singular values:" << endl;

cout << matD << endl;

cout << "left singular vectors:" << endl;

cout << matU << endl;

cout << "transposed matrix of right singular values:" << endl;

cout << matVt << endl;

cv::Mat matUt, matV;

cv::transpose(matU, matUt);

cv::transpose(matVt, matV);

cout << "verify if the result is correct:" << endl;

cv::Mat reconMatD = matUt * mat * matV;

cout << reconMatD << endl;

return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值