-
Notifications
You must be signed in to change notification settings - Fork 0
/
Correlation.cpp
33 lines (27 loc) · 936 Bytes
/
Correlation.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include "Correlation.h"
// Computes the correlation coefficient of two rows of image data "x" and "y" with a length of "length" bytes.
// The correlation coefficient is defined as the result of dividing the empiric covariance by the empiric variance.
float CorrelationCoefficient(unsigned char* x, unsigned char* y, uint64_t length) {
// calculate means of x and y
float xSum = 0.0f;
float ySum = 0.0f;
for (int i = 0; i < length; i++) {
xSum += x[i];
ySum += y[i];
}
float xMean = xSum / length;
float yMean = ySum / length;
float covariance = 0, varianceX = 0, varianceY = 0;
for (int i = 0; i < length; i++) {
float xDiff = x[i] - xMean;
float yDiff = y[i] - yMean;
covariance += xDiff * yDiff;
varianceX += xDiff * xDiff;
varianceY += yDiff * yDiff;
}
// prevent division by zero
if (varianceX * varianceY < FLT_EPSILON) {
return 0;
}
return covariance / std::sqrt(varianceX * varianceY);
}