我有这段代码在单击图像时获取RGB颜色:
public boolean onTouch(View v, MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
final Bitmap bitmap = ((BitmapDrawable) image.getDrawable())
.getBitmap();
int pixel = bitmap.getPixel(x, y);
redValue = Color.red(pixel);
blueValue = Color.blue(pixel);
greenValue = Color.green(pixel);
tv_selected_colour.setText(""+redValue+""+blueValue+""+greenValue);
return false;
}
});
我需要从RGB值中挑选出颜色名称(红色,绿色等)。这可能吗?
答案 0 :(得分:3)
几年前,(XKCD的)Randall Monroe做了一个large online survey of English-speakers,结果是list of over 900 colour names。您可以轻松地将此数据用作颜色命名功能的基础,该功能可将RGB三元组转换为最接近颜色的名称。这就是C中的简单实现,例如:
#include <stdio.h>
#define squared(X) ((X) * (X))
typedef struct {
char *name;
unsigned char r, g, b;
} color_name;
/* Source: http://xkcd.com/color/rgb.txt */
/* License: http://creativecommons.org/publicdomain/zero/1.0/ */
static const color_name xkcd_colors[] = {
{"cloudy blue",0xac,0xc2,0xd9}, {"dark pastel green",0x56,0xae,0x57},
{"dust",0xb2,0x99,0x6e}, {"electric lime",0xa8,0xff,0x04},
:
(et cetera)
:
{"blue",0x03,0x43,0xdf}, {"green",0x15,0xb0,0x1a},
{"purple",0x7e,0x1e,0x9c}
};
int main(int argc, char *argv[]) {
int red, green, blue, d2, mind2, i, result;
if (argc != 2 ||sscanf(argv[1],"%02x%02x%02x",&red,&green,&blue) != 3)
return !puts("Provide 6 hex chars as command line argument.");
mind2 = 256 * 256 * 3;
for (i=0; i<sizeof(xkcd_colors)/sizeof(color_name); i++) {
d2 = squared(red - xkcd_colors[i].r) + /* Calculate squared */
squared(green - xkcd_colors[i].g) + /* distance from each */
squared(blue - xkcd_colors[i].b); /* color in list. */
if (d2 < mind2) {
mind2 = d2; /* Find the minimum distance and */
result = i; /* store the index of this color */
}
}
printf("That color is called \"%s\"\n",xkcd_colors[result].name);
return 0;
}
注意:如果您不希望它返回“baby shit brown”(#ad900d)或“puke”等结果,您可能希望将功能基于不同的数据集(# a5a502),但原理是一样的。