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