从java中的十六进制代码获取颜色名称 [英] Get color name from hex code in java
问题描述
我使用java来查找图像中对象的颜色。
我已经从imgae获得一个像素,然后能够获得该像素的r,g,b值。
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.
现在,我想知道这个像素属于哪种颜色。所以我创建了一个映射,将十六进制代码映射到color_names。现在,我遍历地图,找出距离地图中所有条目的最短距离,以及距离到像素的距离最小的一个条目,我将该颜色分配给像素。
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;
}
现在的问题是,
你可以看到距离函数是: -
D = | r1-r2 | + | g1-g2 | + | b1-b2 |其中| x |表示abs(x)函数
我的黄色被映射为灰色。经过一些调试,我发现这一点。
我应该选择什么距离函数,或者如何改进我的映射?
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 ?
在java中有没有任何内置的东西?
感谢在adv
Does there exist any inbuilt thing for doing this in java? Thanks in adv
推荐答案
Color有一个构造函数需要rgb值,所以:
Color has a constructor that takes rgb values, So:
g.setColor( new Color(0x00, 0x00, 0xff) );
源是:类别颜色
这篇关于从java中的十六进制代码获取颜色名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!