I'm trying to port some Matlab code to OpenCV, part of it includes getting the covariance matrix
An example of an octave:
octave:1> A=[-1, 1, 2; -2, 3, 1; 4, 0, 3;]
A =
-1 1 2
-2 3 1
4 0 3
octave:2> cov(A)
ans =
10.3333 -4.1667 3.0000
-4.1667 2.3333 -1.5000
3.0000 -1.5000 1.0000
OpenCV Version:
Mat_<double> A(3,3); A << -1, 1, 2, -2, 3, 1 , 4, 0, 3;
Mat Sw, mea;
calcCovarMatrix( A, Sw, mea, cv::COVAR_NORMAL|cv::COVAR_ROWS );
cerr << Sw << endl;
[20.66666666666666, -8.333333333333334, 6;
-8.333333333333334, 4.666666666666667, -3;
6, -3, 2]
As you can see, similarly, but factor 2 in the OpenCV version. Any obvious mistake here?
switching the ROWS / COLS flag matches the transposition of the input:
calcCovarMatrix( A, Sw, mea, cv::COVAR_NORMAL|cv::COVAR_COLS );
[4.666666666666666, 5.666666666666666, -2.666666666666667;
5.666666666666666, 12.66666666666667, -9.666666666666666;
-2.666666666666667, -9.666666666666666, 8.666666666666666]
calcCovarMatrix( A.t(), Sw, mea, cv::COVAR_NORMAL|cv::COVAR_COLS );
[20.66666666666666, -8.333333333333334, 6;
-8.333333333333334, 4.666666666666667, -3;
6, -3, 2]