Question

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
                          );
Was it helpful?

Solution

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 variable int deltaR = rgb1.getR()-rgb2.getR(); and then in the formula write deltaR*deltaR instead of the ^ operator. Your RGB values will probably be in 0 to 255 range, so there shouldn't be overflow issues. Alternatively, you could use Math.pow(rgb1.getR()-rgb2.getR(),2) etc. in the formula.

OTHER TIPS

For squaring a number in Java, use Math.pow(x, 2) or even simpler, x * x. The expression x ^ 2 does not square x, instead it 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 quite sure of your algorithm, but that's a different issue.

As people have said, you can use Math.pow(x, 2) for squaring. Just from personal experience, if you're going to call this function a lot it might be better to write out the multiplication yourself, i.e. Math.sqrt((deltaX * deltaX) + (deltaY * deltaY) + (deltaZ * deltaZ)); It may seem uglier but if you profile both forms of the code you'll see that the calls to Math.pow are much slower than the simple multiplications. Obviously there's nothing to do about the Math.sqrt call though.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top