JS的两个值之间的色差/相似性%

问题描述:

我需要计算两个十六进制颜色值之间的差异,因此输出是一个百分比值。我第一个分离的是将十六进制值转换为十进制,因为第一个将具有比最后一个更高的权重。

I need to compute the difference between two hex color values so the output is a percentage value. The first thing I discarted was converting the hex value into decimal, as the first one will have much higher weight than the last.

第二个选项是计算每个RGB值,然后将它们全部添加。然而, 0,0,0 30,30,30 之间的差异远远低于 0,0,0 90,0,0

The second option is to compute the difference between each of the RGB values and then add them all. However, the difference between 0, 0, 0 and 30, 30, 30 is much lower than the one between 0, 0, 0 and 90, 0, 0.

此问题建议使用 YUV ,但我不知道如何使用它来建立差异。

This question recommends using YUV, but I can't figure out how to use it to establish the difference.

此外,

Also, this other question has a nice formula to compute the difference and output a RGB value, but it's not quite there.

这个其他问题有一个很好的公式来计算差异和输出一个RGB值,

只需计算欧氏距离

Just compute an Euclidean distance:

var c1 = [0, 0, 0],
    c2 = [30, 30, 30],
    c3 = [90, 0, 0],
    distance = function(v1, v2){
        var i,
            d = 0;

        for (i = 0; i < v1.length; i++) {
            d += (v1[i] - v2[i])*(v1[i] - v2[i]);
        }
        return Math.sqrt(d);
    };

console.log( distance(c1, c2), distance(c1, c3), distance(c2, c3) );
//will give you 51.96152422706632 90 73.48469228349535