开发者

Compare Pixel Colour - Java

How can I find similar coloured pixels using colour objects? I know to see if two colors are eq开发者_C百科ual 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?


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!


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:

Compare Pixel Colour - Java

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜