java 获取颜色代码,从java中的十六进制代码获取颜色名称

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 data = new HashMap();

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

解决方案

Color has a constructor that takes rgb values, So:

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

Source is : Class Color

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值