understanding HSL to RGB color space conversion algorithm -
i've read hsl rgb algorithm in wikipedia. understand , can convert using it. came upon algorithm here, , math "explained" here.
the algorithm is:
//h, s , l input range = 0 ÷ 1.0 //r, g , b output range = 0 ÷ 255 if ( s == 0 ) { r = l * 255 g = l * 255 b = l * 255 } else { if ( l < 0.5 ) var_2 = l * ( 1 + s ) else var_2 = ( l + s ) - ( s * l ) var_1 = 2 * l - var_2 r = 255 * hue_2_rgb( var_1, var_2, h + ( 1 / 3 ) ) g = 255 * hue_2_rgb( var_1, var_2, h ) b = 255 * hue_2_rgb( var_1, var_2, h - ( 1 / 3 ) ) } hue_2_rgb( v1, v2, vh ) //function hue_2_rgb { if ( vh < 0 ) vh += 1 if( vh > 1 ) vh -= 1 if ( ( 6 * vh ) < 1 ) return ( v1 + ( v2 - v1 ) * 6 * vh ) if ( ( 2 * vh ) < 1 ) return ( v2 ) if ( ( 3 * vh ) < 2 ) return ( v1 + ( v2 - v1 ) * ( ( 2 / 3 ) - vh ) * 6) return ( v1 ) }
i've tried following math can't figure it. how work?
the first part if ( s == 0 )
case there no saturation means it’s shade of grey. set luminance, set rgb grey scale level , done.
if not case, need perform tricky part:
we shall use var_1
, var_2
temporary values, making code more readable.
so, if luminance smaller 0.5 (50%) var_2 = luminance x (1.0 + saturation. if luminance equal or larger 0.5 (50%) var_2 = luminance + saturation – luminance x saturation. that's else part of:
if ( l < 0.5 ) var_2 = l * ( 1 + s ) else var_2 = ( l + s ) - ( s * l )
then do:
var1 = 2 x luminance – var_2
which going useful later.
now need 3 temporary variables each color channel, far hue conserned. red, add 0.333 (h + (1/3)
in code), green nothing, , blue, subtract 0.333 (h + (1/3)
). temporaty value called vh
(value hue) in hue_2_rgb()
.
now each color channel treated separetely, 3 function calls. there 4 formulas can applied color channel. every color channel should "use" 1 formula.
which one? depends on value of hue (vh
).
by way, value of vh
must normalized, if it's negative add 1, or if it's greater 1, subtract 1 it, vh lies in [0, 1].
- if 6 x vh smaller 1, color channel = var_1 + (var_2 – var_1) x 6 x vh
- if 2 x vh smaller 1, color channel = var_2
- if 3 x vh smaller 2, color channel = var_1 + (var_2 – var_1) x (0.666 – vh) x 6
- else, color channel = var_1
for r = 255 * hue_2_rgb( var_1, var_2, h + ( 1 / 3 ) )
, color channel red, named r
in code.
Comments
Post a Comment