Foxlair

关于shader中颜色的对比,rgb转lab颜色空间

· q8f13

shader中对比颜色的时候,不能直接使用rgb空间的值差来进行计算。因为这个空间并不能反映人眼对于颜色相近的定义。这个时候可以使用Lab*空间进行计算

But RGB is not “perceptually uniform”, so your Euclidean RGB distance metric suggested by Vadim will not match the human-perceived distance between colors. For a start, Lab* is intended to be a perceptually uniform colorspace, and the deltaE metric is commonly used. But there are more refined colorspaces and more refined deltaE formulas that get closer to matching human perception.

转换后计算两个颜色值的deltaE来决定其近似程度

cie1.png

附相关计算代码

 1float3 rgb2xyz( float3 c ) {
 2    float3 tmp;
 3    tmp.x = ( c.r > 0.04045 ) ? pow( ( c.r + 0.055 ) / 1.055, 2.4 ) : c.r / 12.92;
 4    tmp.y = ( c.g > 0.04045 ) ? pow( ( c.g + 0.055 ) / 1.055, 2.4 ) : c.g / 12.92,
 5    tmp.z = ( c.b > 0.04045 ) ? pow( ( c.b + 0.055 ) / 1.055, 2.4 ) : c.b / 12.92;
 6    const float3x3 mat = float3x3(
 7        0.4124, 0.3576, 0.1805,
 8        0.2126, 0.7152, 0.0722,
 9        0.0193, 0.1192, 0.9505 
10    );
11    return 100.0 * mul(tmp, mat);
12}
13
14float3 xyz2lab( float3 c ) {
15    float3 n = c / float3(95.047, 100, 108.883);
16    float3 v;
17    v.x = ( n.x > 0.008856 ) ? pow( n.x, 1.0 / 3.0 ) : ( 7.787 * n.x ) + ( 16.0 / 116.0 );
18    v.y = ( n.y > 0.008856 ) ? pow( n.y, 1.0 / 3.0 ) : ( 7.787 * n.y ) + ( 16.0 / 116.0 );
19    v.z = ( n.z > 0.008856 ) ? pow( n.z, 1.0 / 3.0 ) : ( 7.787 * n.z ) + ( 16.0 / 116.0 );
20    return float3(( 116.0 * v.y ) - 16.0, 500.0 * ( v.x - v.y ), 200.0 * ( v.y - v.z ));
21}
22
23float3 rgb2lab( float3 c ) {
24    float3 lab = xyz2lab( rgb2xyz( c ) );
25    return float3( lab.x / 100.0, 0.5 + 0.5 * ( lab.y / 127.0 ), 0.5 + 0.5 * ( lab.z / 127.0 ));
26}
27
28float getDeltaE(float3 a, float3 b)
29{
30    return sqrt((b.x - a.x) * (b.x - a.x) + (b.y - a.y) * (b.y - a.y) + (b.z - a.z) * (b.z - a.z));
31}

来源: How to compare two colors for similarity/difference How Is Color Measured? Calculating Delta E Conversion between RGB and LAB colorspace shader for Unity.

#unity   #shader   #game development