Search code examples
c++opencvcovariance

Calculate covariance in OpenCV


I have a cv::Mat like this:

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 I need is calcCovarMatrix.... BUT if I execute this 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 an incomprehensible 3x3 matrix...

new_covs=
[11220.02, 10838.03, 10987.83;
  10838.03, 10469.045, 10613.745;
  10987.83, 10613.745, 10760.445]

I hope you can help me with my problem!


Solution

  • According to the documentation you need the flag "CV_COVAR_SCALE" to obtain a scaled covariance.

    The mean is actually provided already scaled, so no need to scale it further.

    The right solution is then:

    cv::Mat a = (cv::Mat_<double>(3, 2) << 500.0, 350.2, 500.5, 355.8, 498.7, 352.0);
    cv::Mat mean, covs;
    cv::calcCovarMatrix(a, covs, mean, CV_COVAR_NORMAL | CV_COVAR_ROWS | CV_COVAR_SCALE);