RGB to HSV to RGB Color Space conversion

From Shader Forge Wiki
Jump to: navigation, search


Color Space Conversion

There are many times when working in a color space other than RGB can be useful. For instance, if you want to provide random hue variations to some artwork. You can convert to HSV color space and back using the functions below, which are based off the ones found here link rgb-to-hsv

input: float3 RGB RGB to HSV:

   float4 k = float4(0.0, -1.0/3.0, 2.0/3.0, -1.0);
   float4 p = RGB.g < RGB.b ? float4(RGB.b, RGB.g, k.w, k.z) : float4(RGB.gb, k.xy);
   float4 q = RGB.r < p.x   ? float4(p.x, p.y, p.w, RGB.r) : float4(RGB.r, p.yzx);
   float d = q.x - min(q.w, q.y);
   float e = 1.0e-10;
   return float3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x);

and convert back using the following code:

input: float3 HSV HSV to RGB:

   float4 k = float4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);
   float3 p = abs(frac(HSV.xxx + k.xyz) * 6.0 - k.www);
   return HSV.z * lerp(k.xxx, clamp(p - k.xxx, 0.0, 1.0), HSV.y);

and an example of it's use: HSVtoRGBtoHSV.png

--Jason Booth (talk) 00:45, 24 March 2014 (UTC)