Matlab SVD output in opencv

2019-06-24 15:05发布

问题:

in Matlab SVD function outputs three Matrices:

[U,S,V] = svd(X) 

and we can use the S Matrix to find to smallest possible number of component to reduce the dimension of X to retain enough variance. My question is how can I find the S Matrix (not the U Matrix) using Opencv , Is it possible to find S Matrix using build in OpenCV SVD? I mean OpenCV SVD function outputs three matrices like the Matlab one, But I don't know if they are the same or not. this is the SVD in OpenCV:

SVD::compute(InputArray src, OutputArray w, OutputArray u, OutputArray vt, int flags=0 ) 

and this is Matlab SVD:

[U,S,V] = svd(X).

Thank you.

回答1:

There is a simple difference between S in Matlab and w in OpenCV.

Take this example:

A = [2, 4;
     1, 3;
     0, 0;
     0, 0]

In Matlab, S would be:

S = [5.47, 0   ;
     0   , 0.37;
     0   , 0   ;
     0   , 0   ]

But openCV gives the following as w:

w = [5.47; 0.37]

So, OpenCV gives an array of singular values, if you really want to have the S matrix, you may create a new matrix and put w's elements in its diagonal.



回答2:

I'm pretty sure that the backend that actually computes the SVD decomposition is the same for MATLAB and OpenCV (I'm thinking in both cases it is done with LAPACK). So what you want to do is seems pretty easy.

You can convert w to S by creating a matrix of the same size of src with zeros everywhere and the values in w along the diagonal. It is just a simple change of data structure, the values will be the same.