I had the same problem two days ago, and I have no idea why the problem occurs, but I've written a code that works for all the samples I tested in OpenCV and MATLAB.
void matlab_covar(Mat A,Mat B)
{
Mat covar,mean;
if(A.rows!=1) // check if A and B has one row don't reshape them
{
A=A.reshape(1,A.rows*A.cols).t(); //reshape A to be one row
B=B.reshape(1,A.rows*A.cols).t(); //rehsape B to be one row
}
vconcat(A,B,A); //vertical attaching
cv::calcCovarMatrix(A,covar, mean,CV_COVAR_COLS|CV_COVAR_NORMAL);
Mat Matlab_covar = covar/(A.cols-1); //scaling
cout<<Matlab_covar<<endl;
}
I tested some examples to show that this code works properly (but I'm not sure why it works)
example-1
in MATLAB
>> A = [1 2; 3 4];
>> B = [1 0; 5 8];
>> cov(A,B)
ans =
1.6667 4.3333
4.3333 13.6667
In Opencv
cv::Mat A = (cv::Mat_<double>(2,2) << 1,2,3,4);
cv::Mat B = (cv::Mat_<double>(2,2) << 1,0,5,8);
matlab_covar(A,B); //the function i write
output
[1.666666666666667, 4.333333333333333;
4.333333333333333, 13.66666666666667]
example-2
MATLAB
>> A = [3 3 3;2 2 2];
>> B = [1 2 3;3 2 1];
>> cov(A,B)
ans =
0.3000 0
0 0.8000
OpenCV
[0.3, 0;
0, 0.8]
Example-3
Matlab
>> a=rand(3,1)
a =
0.8147
0.9058
0.1270
>> b=rand(3,1)
b =
0.9134
0.6324
0.0975
>> cov(a,b)
ans =
0.1813 0.1587
0.1587 0.1718
OpenCV
cv::Mat A = (cv::Mat_<double>(3,1) << 0.8147,0.9058,0.1270);
cv::Mat B = (cv::Mat_<double>(3,1) << 0.9134,0.6324,0.0975);
matlab_covar(A,B);
[0.1812933233333333, 0.1586792416666666;
0.1586792416666666, 0.1717953033333333]
cv::calcCovarMatrix
, and after looking into the source code of the function, the mentioned flag is just removed. – dohnto