0

I am using java to find out color of an object in the image. I have obtained a pixel from imgae and then able to get the r,g,b values for that pixel.

Now, I want to know this pixel belongs to which color. So I have created a map which maps hex code to color_names. Now, i traverse map and find out shortest distance from all entries in map and the one entry for which distance is minimum to the pixel I assign that color to pixel.

Here is some of my code :-

private static String getColorName(int[] rgb) {
    Map<String, String> data = new HashMap<String, String>();
    data.put("00ff00", "GREEN");
    data.put("ff0000", "RED");
    data.put("0000ff", "BLUE");

    data.put("00ffff", "CYAN");
    data.put("ffff00", "YELLOW");
    data.put("ff00ff", "PINK");

    data.put("c8c8c8", "LIGHT GREY");
    //data.put("808080", "GREY");
    data.put("ffc800", "ORANGE");
    data.put("4F3E86", "PURPLE");

    data.put("000000", "BLACK");
    data.put("ffffff", "WHITE");

    String hex = "0123456789abcdef";

    int minD = 256*256*256;
    String res = "";

    for (String key : data.keySet()) {
        int r = hex.indexOf(key.charAt(0))*16 + hex.indexOf(key.charAt(1));
        int g = hex.indexOf(key.charAt(2))*16 + hex.indexOf(key.charAt(3));
        int b = hex.indexOf(key.charAt(4))*16 + hex.indexOf(key.charAt(5));

        int distance = (Math.abs(rgb[0] - r)) + 
                (Math.abs(rgb[1] - g)) + 
                (Math.abs(rgb[2] - b));

        if (distance < minD) {
            res = data.get(key);
            minD = distance;
        }
    }
    return res;
}

The problem is now,

As you can see Distance function is:- D = |r1-r2| + |g1-g2| + |b1-b2| where |x| indicates abs(x) function My yellow color getting mapped to grey color. After some debugging, i found this. What distance function should i choose or how can i improve my mapping ?

Does there exist any inbuilt thing for doing this in java? Thanks in adv

Sachin Jain
  • 21,353
  • 33
  • 103
  • 168

1 Answers1

0

Color has a constructor that takes rgb values, So:

g.setColor( new Color(0x00, 0x00, 0xff) );

Source is : Class Color

Mani
  • 1,841
  • 15
  • 29
  • `g` probably represents a [`Graphics`](http://docs.oracle.com/javase/7/docs/api/java/awt/Graphics.html) instance - which would mean this answer misses the point of your question, which is about how to determine that sub-set of colors, whether represented as ints or hex. – Andrew Thompson Jun 21 '12 at 06:17