Ask Your Question

Revision history [back]

I know that this thread is old but here is an answer for those who continuously browse the internet in search of answers.

The following code works with Opencv 3.0 and it should work with opencv 2.4 with few changes.

double correlation(cv::Mat &image_1, cv::Mat &image_2)   {

// convert data-type to "float"
cv::Mat im_float_1;
image_1.convertTo(im_float_1, CV_32F);
cv::Mat im_float_2;
image_2.convertTo(im_float_2, CV_32F);

int n_pixels = im_float_1.rows * im_float_1.cols;

// Compute mean and standard deviation of both images
cv::Scalar im1_Mean, im1_Std, im2_Mean, im2_Std;
meanStdDev(im_float_1, im1_Mean, im1_Std);
meanStdDev(im_float_2, im2_Mean, im2_Std);

// Compute covariance and correlation coefficient
double covar = (im_float_1 - im1_Mean).dot(im_float_2 - im2_Mean) / n_pixels;
double correl = covar / (im1_Std[0] * im2_Std[0]);

return correl;

}