Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab SVD output in opencv

Tags:

opencv

matlab

svd

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.

like image 947
Saeed.Torabzadeh Avatar asked Dec 16 '22 20:12

Saeed.Torabzadeh


2 Answers

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.

like image 108
Kamyar Infinity Avatar answered Dec 27 '22 09:12

Kamyar Infinity


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.

like image 27
carlosdc Avatar answered Dec 27 '22 10:12

carlosdc