Jump to content

Fastest way to compare colors?

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
5 replies to this topic

#1
farzher

farzher

    Newbie

  • Members
  • Pip
  • 8 posts
public boolean compareColors(Color a, Color b, int threshold) {		

		return (a.getRed() >= b.getRed() - threshold

			 || a.getRed() <= b.getRed() + threshold

			 

			 || a.getGreen() >= b.getGreen() - threshold

			 || a.getGreen() <= b.getGreen() + threshold

			 

			 || a.getBlue() >= b.getBlue() - threshold

			 || a.getBlue() <= b.getBlue() + threshold);

	}

It seems like this is a lot to check just to compare two colors, anyone have a better idea? This is java btw.

#2
farzher

farzher

    Newbie

  • Members
  • Pip
  • 8 posts
hey guys, wake up.

#3
Fawad

Fawad

    Newbie

  • Members
  • Pip
  • 5 posts
no idea mate:(

#4
Alexander

Alexander

    It's Science!

  • Moderators
  • 4,118 posts
It looks fine and simple to me. If you're wishing to optimize it I would definitely categorize it as a pointless micro-optimization due to what you're trying to attempt with the function.
Be sure to read the updated FAQ! || Health is achieved through the same 10,000 steps.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.

#5
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
That doesn't look like a lot, to me. I can think of other ways to compare colors that would be much more involved. Converting RGB to a different representation first, for example.
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

#6
Hoffmann Peter

Hoffmann Peter

    Newbie

  • Members
  • Pip
  • 6 posts
Beside that my java skills have never be tested in the water (aka I'm a java dry-swimmer), I would suggest:

public boolean compareColors(Color a, Color b, int threshold) {		
    return (
        abs(a.getRed() - b.getRed()) < threshold &&
        abs(a.getGreen() - b.getGreen()) < threshold && 
        abs(a.getBlue() - b.getBlue()) < threshold
    );
}

On the other side I think that your code has a logical flaw, the eye will rather see the difference between (R,G,B) and (R+9,G+9,B+9) [threshold = 10, result = true) than the difference between (R,G,B) and (R,G,B+11) [same threshold, result = false].
Thus, I suggest:


public boolean compareColors(Color a, Color b, int threshold) {		
    return (
        (a.getRed() - b.getRed())^2 + (a.getGreen() - b.getGreen())^2 + (a.getBlue() - b.getBlue())^2 < threshold^2
    );
}