hammingDistancePercentage static method
Calculates the normalized Hamming distance between two matrices.
The Hamming distance is the number of positions at which the corresponding elements in two matrices are different. This method computes a normalized similarity score based on the Hamming distance.
Parameters:
inputGrid
: The first Matrix to compare.templateGrid
: The second Matrix to compare against.
Returns: A double value between 0 and 1, where:
- 1.0 indicates perfect similarity (no differences)
- 0.0 indicates maximum dissimilarity (all elements are different)
Note: This method assumes that both matrices have the same dimensions. If the matrices have different sizes, the behavior is undefined and may result in errors or incorrect results.
Implementation
static double hammingDistancePercentage(
final Matrix inputGrid,
final Matrix templateGrid,
) {
int matchingPixels = 0;
int totalPixels = 0;
for (int y = 0; y < inputGrid.rows; y++) {
for (int x = 0; x < inputGrid.cols; x++) {
if (inputGrid._data[y][x] || templateGrid._data[y][x]) {
totalPixels++;
if (inputGrid._data[y][x] == templateGrid._data[y][x]) {
matchingPixels++;
}
}
}
}
if (totalPixels == 0) {
return 0.0;
} // If no true pixels, consider it a perfect match
return matchingPixels / totalPixels;
}