Euclidean distance returning strange results

im writing a program to compare two images against each other based on color and them using euclidean distance algorithm, however when i run it and pass two images i get one distance and then when i pass the same images and the other i get a completely different set of results.

- is this normal or should the answers be the same?

The statement I use to calculate the Euclidean distance is:

distance = (int) Math.sqrt(   (rgb1.getR()-rgb2.getR())^2
                            + (rgb1.getG()-rgb2.getG())^2
                            + (rgb1.getB()-rgb2.getB())^2
                          );

      

+3


source to share


3 answers


Looking at the code you posted it looks like your RGB values. However, the operator is ^

not a power operator, but XOR (exclusive-OR) is a bitwise operation. Therefore, to calculate the squares correctly, use regular multiplication - for example, use a temporary variable int deltaR = rgb1.getR()-rgb2.getR();

, and then write in the formula deltaR*deltaR

instead of the operator ^

. Your RGB values ​​will probably be between 0 and 255, so there shouldn't be any overflow issues. Alternatively, you can use Math.pow(rgb1.getR()-rgb2.getR(),2)

etc. In the formula.



+7


source


To square numbers in Java, use Math.pow(x, 2)

, or even easier x * x

. The expression x ^ 2

has no square x

, instead XORs x

with 2

.

In your code:



int diffR = rgb1.getR() - rgb2.getR();
int diffG = rgb1.getG() - rgb2.getG();
int diffB = rgb1.getB() - rgb2.getB();

int distance = (int) Math.sqrt(diffR*diffR + diffG*diffG + diffB*diffB);

      

... Although I'm not entirely sure about your algorithm, this is a different problem.

+2


source


As people said, you can use Math.pow(x, 2)

for squaring. Just from personal experience, if you are going to call this function a lot, it would be better to write the multiplication yourself, i.e. Math.sqrt((deltaX * deltaX) + (deltaY * deltaY) + (deltaZ * deltaZ));

It may sound ugly, but if you profile both forms of code, you will see that the calls are Math.pow

much slower than simple multiplications. Obviously there is nothing to do with the challenge Math.sqrt

.

0


source







All Articles