我已经创建了一个包含名称和rgb值的巨大颜色列表(花了很长时间),现在我创建了一个算法,可以将相应的颜色获取到最接近的值。
它似乎工作得很好,但有时当有一个奇怪的值,它得到了错误的颜色。
示例输出
Log: InputRGB: R:7.1009636 | G:83.84344 | B:2.5013387
Log: ColorToCompare: Ball Blue (R13.0,G67.0,B80.0) CLOSE:0.4588677 | CurrentColor: Acid Green CLOSE: 0.41585693
Log: ColorToCompare: Bitter Lemon (R79.0,G88.0,B5.0) CLOSE:0.5143066 | CurrentColor: Ball Blue CLOSE: 0.4588677
Log: ColorToCompare: Citrine (R89.0,G82.0,B4.0) CLOSE:0.5610447 | CurrentColor: Bitter Lemon CLOSE: 0.5143066
Log: ColorToCompare: Smoky Black (R6.0,G5.0,B3.0) CLOSE:0.57945675 | CurrentColor: Citrine CLOSE: 0.5610447
Log: ColorName:Smoky Black
Log: End Color: R:6.0 G:5.0 B:3.0
Log: InputRGB: R:7.1009636 | G:83.84344 | B:2.5013387
我创建的用于计算此值的代码:
public String getClosetColor(float red, float green, float blue){
Functions.log("InputRGB: R:" + red + " | G:" + green + " | B:" + blue);
Color lastColor = null;
for(Color eachColor : this.colors)
{
if(lastColor == null){
lastColor = eachColor;
}
float lastColorCloseness = (getClose(red, lastColor.red) + getClose(green, lastColor.green) + getClose(blue, lastColor.blue)) / 3f;
float thisColorCloseness = (getClose(red, eachColor.red) + getClose(green, eachColor.green) + getClose(blue, eachColor.blue)) / 3f;
if(Float.isFinite(thisColorCloseness) && Float.isFinite(lastColorCloseness))
{
//If they are the same, choose a random one.
if(lastColorCloseness == thisColorCloseness){
if(MathUtils.random() > 0.5f){
lastColor = eachColor;
}
}
//If this one is greater then set it.
else if(thisColorCloseness > lastColorCloseness){
Functions.log(
"ColorToCompare: " + eachColor.nameOfColor + " (R" + eachColor.red + ",G" + eachColor.green + ",B" + eachColor.blue + ") CLOSE:" + thisColorCloseness +
" | CurrentColor: " + lastColor.nameOfColor + " CLOSE: " + lastColorCloseness
);
lastColor = eachColor;
}
}
}
Functions.log("ColorName:" + lastColor.nameOfColor);
Functions.log("End Color: R:" + lastColor.red + " G:" + lastColor.green + " B:" + lastColor.blue);
Functions.log("InputRGB: R:" + red + " | G:" + green + " | B:" + blue);
return "";
}
//Basically if one is higher than the other then devide by it.
private float getClose(float firstNumber, float secondNumber){
if(firstNumber < secondNumber){
return firstNumber / secondNumber;
}
else{
return secondNumber / firstNumber;
}
}
最佳答案
我不知道你是怎么想到距离函数的,但有点尴尬让我解释一下:
使用颜色的比率而不是差异,例如:
float lastColorCloseness = (getClose(red, lastColor.red) + getClose(green, lastColor.green) + getClose(blue, lastColor.blue)) / 3f;
这有一种奇怪的效果,即对距离相等的颜色不应用相同的颜色。例如比较
col1(100, 50, 200)
使用col2(50, 100, 150)
和col3(150, 100, 250)
。假设
col2
和col3
与col1
之间的距离等于:abs(100-50)+abs(50-100)+abs(200-150)=150
abs(100-150)+abs(50-100)+abs(200-250)=150
你的距离函数给出了不同的结果:
(50/100+50/100+150/250)/3=0.53
(50/100+50/100+200/250)/3=0.6
正如“大卫华莱士”所说,这并不是最夸张的结果。
改用欧几里德函数之类的距离函数。
关于java - 使RGB获得最接近的色彩算法更准确,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25620837/