im writing a program to compare two images against each other based on color and im using the Euclidean distance algorithm however when i run it and pass in two images i get one distance and then when i pass in the same images but the other way round i get a completely different set of results.
is this normal or should the answers be the same?
The statement I’m using to compute the Euclidean distance is:
distance = (int) Math.sqrt( (rgb1.getR()-rgb2.getR())^2
+ (rgb1.getG()-rgb2.getG())^2
+ (rgb1.getB()-rgb2.getB())^2
);
Looking at the code you posted, it looks your RGB values are ints. However, the
^operator is not the power operator, but XOR (exclusive-OR) – a bitwise operation. So in order to calculate the squares correctly, use regular multiplication – e.g., use a temporary variableint deltaR = rgb1.getR()-rgb2.getR();and then in the formula writedeltaR*deltaRinstead of the^operator. Your RGB values will probably be in 0 to 255 range, so there shouldn’t be overflow issues. Alternatively, you could useMath.pow(rgb1.getR()-rgb2.getR(),2)etc. in the formula.