# how to find correlation coefficient for two images?

I have two 16-Bit grey level images in cv::Mat format. I just have to find the correlation coefficient scores i.e) a score says how much the two images match each other.

Is there any functions in opencv or any other libraries to find it?

edit retag close merge delete

Sort by » oldest newest most voted

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 * im2_Std);

return correl;


}

more

Why do you have to convert the input images to float?

when computing "covar", we need to compute centered image, that is image minus im_mean, where im_mean is a floating point value.

Hi, you can use the template matching function of opencv with the method: TM_CCOEFFThis will give you the coeffcient you need. Just use the second image as a template. Here is an example: [http://docs.opencv.org/doc/tutorials/...]

more

The function is matchTemplate, tm_ccoeff ist just a parameter for this function.

Assuming both image1 and image2 are the same size:

float correlation(cv::Mat &image1, cv::Mat &image2)
{
cv::Mat corr;
cv::matchTemplate(image1, image2, corr, cv::TM_CCORR_NORMED);
return corr.at<float>(0,0);  // corr only has one pixel
}

more

Can I ask what value returns it on the return line?

Official site

GitHub

Wiki

Documentation