# Calculate covariance in Opencv

Dear forum followers I have a issue which I don't know how solve it.

I have a Mat like:

500.0   350.2
500.5   355.8
498.7   352.0
............

And I need calculate the covariance. The result would be something like:

0.8633    1.2167
1.2167    8.1733

Of course, the function which I need is calcCovarMatrix.... BUT if I execute these code:

cv::Mat a = (cv::Mat_<double>(3, 2) << 500.0, 350.2, 500.5, 355.8, 498.7, 352.0);
cv::Mat mu, new_covs;
cv::calcCovarMatrix(a, new_covs, mu, CV_COVAR_NORMAL | CV_COVAR_COLS);
The result is a incomprehensible 3x3 matrix...
new_covs=
[11220.02, 10838.03, 10987.83;
10838.03, 10469.045, 10613.745;
10987.83, 10613.745, 10760.445]

Another question:

If I have a set of clusters could I get the weight of these clusters like Expectation Maximization does it. How?: (http://docs.opencv.org/modules/ml/doc...)

I hope you can help my with my problem!! Thank you in advanced!

edit retag close merge delete

Sort by ยป oldest newest most voted

for the covariance:

Mat_<float> samples = (Mat_<float>(3, 2) << 500.0, 350.2,
500.5, 355.8,
498.7, 352.0);

Mat cov, mu;
cv::calcCovarMatrix(samples, cov, mu, CV_COVAR_NORMAL | CV_COVAR_ROWS);

cov = cov / (samples.rows - 1);

cout << "cov: " << endl;
cout << cov << endl;

cout << "mu: " << endl;
cout << mu << endl;

result:

cov:
[0.8633207194507122, 1.216659545898438;
1.216659545898438, 8.173264974107346]
mu:
[499.7333374023438, 352.6666666666666]
more

Exactly!!! We need to divide between number of rows -1!!

You are a genius!!!

( 2015-02-20 07:54:35 -0600 )edit

Official site

GitHub

Wiki

Documentation