【发布时间】:2018-04-22 07:18:16
【问题描述】:
我正在尝试构建一个十六进制颜色比较器,该比较器比较数组中的值并删除相似的值,以保留像素最多的颜色。
下面是 输入 的示例,数组的长度可以从 1 变为更多:
[…]
0: Array [ "ffffff", 12992 ]
1: Array [ "da542f", 3117 ] #similar
2: Array [ "da5630", 60 ] #similar
length: 3
(index: Array [hexColor, NumberOfPixel])
输出看起来像这样:
[…]
0: Array [ "ffffff", 12992 ]
1: Array [ "da542f", 3117 ]
length: 2
我想出的,因为下面的例子是超级硬编码的并且会产生错误我想避免在彼此内部有多个 if/else,hexColorCalc() 函数来自这个 post :
// ordered by highest pixel
colors_lst = [
["333333", 6421],
["da542f", 3117],
["da5630", 60]
]
console.log(colors_lst);
function hexColorDelta(array) {
function hexColorCalc(hex1, hex2) {
// get red/green/blue int values of hex1
var r1 = parseInt(hex1.substring(0, 2), 16);
var g1 = parseInt(hex1.substring(2, 4), 16);
var b1 = parseInt(hex1.substring(4, 6), 16);
// get red/green/blue int values of hex2
var r2 = parseInt(hex2.substring(0, 2), 16);
var g2 = parseInt(hex2.substring(2, 4), 16);
var b2 = parseInt(hex2.substring(4, 6), 16);
// calculate differences between reds, greens and blues
var r = 255 - Math.abs(r1 - r2);
var g = 255 - Math.abs(g1 - g2);
var b = 255 - Math.abs(b1 - b2);
// limit differences between 0 and 1
r /= 255;
g /= 255;
b /= 255;
// 0 means opposit colors, 1 means same colors
return (r + g + b) / 3;
}
// Do nothing since nothing to compare
if (array.length == 1) {
console.log('length of array : 1');
return array
}
// Just compare both values and erase the one with least pixel
if (array.length == 2) {
console.log('length of array : 2');
var hex1 = array[0][0];
var hex2 = array[1][0];
if (hexColorCalc(hex1, hex2) > 0.9) {
colors_lst = array.pop(); // Get ride of last item in array
return colors_lst;
}
}
// Problems
if (array.length == 3) {
var hex1 = array[0][0];
var hex2 = array[1][0];
var hex3 = array[2][0];
// if True, other if/else below won't be working
if (hexColorCalc(hex1, hex2) > 0.9) {
array.splice(2, 1);
}
if (hexColorCalc(hex1, hex3) > 0.9) {
array.splice(3, 1);
}
if (hexColorCalc(hex2, hex3) > 0.9) {
array.splice(2, 1);
}
return array
}
}
console.log(hexColorDelta(colors_lst));
我注释掉了代码是如何工作的,我在理解这个问题的正确算法时遇到了一些麻烦。如何避免硬编码并返回没有相似之处的正确列表?
【问题讨论】:
-
您如何准确定义“相似性”?
da542f和da5630非常接近,但并不完全相同。门槛在哪里? -
仍然存在一些问题,因为根据比较和删除颜色的顺序,您将获得不同数量的颜色。我建议在互联网上搜索 JavaScript color quantization 并可能使用任何可用的实现 github.com/leeoniya/RgbQuant.js
标签: javascript algorithm