Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare Pixel Colour - Java

Tags:

java

pixel

colors

How can I find similar coloured pixels using colour objects? I know to see if two colors are equal you can use:

a.equals(b);

where a and b are colour objects, but what if I want to find similar shades of blue for example?

like image 975
dr85 Avatar asked Jul 11 '26 22:07

dr85


2 Answers

Comparing colours is not a trivial problem, there are a variety of different metrics. I can't find a library (easily) that does it but if you have a thorough search I'm sure there'll be something out there Have a look at this class. In the meantime do some reading!

like image 57
fredley Avatar answered Jul 13 '26 12:07

fredley


When it comes to programmatically tweaking color values you have lots of options. A very easy solution would be to simply offset the channel values of the color object randomly. Think of it as mutating colors - just take the color you'd like to mutate and generate a few more colors from it:

Color mutateColor(int range){
  int r = a.getRed() + (int)(Math.random() * 2 * range - range);
  r = Math.min(255, Math.max(0, r));

  int g = a.getGreen() + (int)(Math.random() * 2 * range - range);
  g = Math.min(255, Math.max(0, g));

  int b = a.getBlue() + (int)(Math.random() * 2 * range - range);
  b = Math.min(255, Math.max(0, b));

  return new Color(r, g, b);
}

This is the simplest example, a range is given and each channel is offset by that same range, resulting in something like this:

a few randomly colored boxes

This was done with a range value of 10. For added control you could add three arguments to the mutateColor function (offsets for each individual channel). You could also take one range but alter it based on the values already in the channel. For instance:

range = 0.25
red = 100
green = 10
blue = 0

redRange = 100 + rand(-25, 25)
greenRange = 10 + rand(-2.5, 2.5);
etc...

That's just one of many other possibilities.

If you were looking to compare two colors with a tolerance, I ported the code from fredley's link and it works nicely for getting the difference between two colors:

double colorDist(Color e1, Color e2){
  long rmean = ( (long)e1.getRed() + (long)e2.getRed() ) / 2;
  long r = (long)e1.getRed() - (long)e2.getRed();
  long g = (long)e1.getGreen() - (long)e2.getGreen();
  long b = (long)e1.getBlue() - (long)e2.getBlue();
  return Math.sqrt((((512+rmean)*r*r)>>8) + 4*g*g + (((767-rmean)*b*b)>>8));
}
like image 30
Zevan Avatar answered Jul 13 '26 12:07

Zevan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!