dr85
dr85

Reputation: 743

Compare Pixel Colour - Java

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?

Upvotes: 2

Views: 4728

Answers (3)

Zevan
Zevan

Reputation: 10235

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));
}

Upvotes: 4

camickr
camickr

Reputation: 324197

what if I want to find similar shades of blue for example?

I have no idea what a technical definition for this might mean. However you might be able to use HSL Color to create your own definition.

Basically, I guess you could start by making sure the the Hue of each color is +/- a fixed number of degrees. Then you could narrow it down further by checking if the Saturation and/or Luminosity is within your desired range.

Upvotes: 1

fredley
fredley

Reputation: 33941

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!

Upvotes: 4

Related Questions