Showing posts with label HLSL. Show all posts
Showing posts with label HLSL. Show all posts

Saturday, 3 October 2015

RGB/HSV in HLSL 7

I got a very kind email from David Schaeffer yesterday with some bug fixes for the shader code I wrote for converting RGB to the HCY colour space.

My original implementation was

  float3 RGBtoHCY(in float3 RGB)
  {
    float3 HCV = RGBtoHCV(RGB);
    float Y = dot(RGB, HCYwts);
    if (HCV.y != 0)
    {
      float Z = dot(HUEtoRGB(HCV.x), HCYwts);
      if (Y > Z)
      {
        Y = 1 - Y;
        Z = 1 - Z;
      }
      HCV.y *= Z / Y;
    }
    return float3(HCV.x, HCV.y, Y);
  }

As he points out:
It seems to me that you have an error in your RGB to HCY code, though.  I was having some pixels always saturate to white, and after looking at Kuzma Shapran's original code I don't think the value of Y should actually be changed, only using the adjusted value of Y to calculate HCV.y.  Additionally I think the check for 0 in the original code was meant to prevent divide by 0 errors, so should be using Y instead of HCV.y.
I'll have to bow to David's superior knowledge on HCY usage as I've never actually used it in anger. So here's his improved version:

  float3 RGBtoHCY(in float3 RGB)
  {
    float3 HCV = RGBtoHCV(RGB);
    float Y = dot(RGB, HCYwts);
    float Z = dot(HUEtoRGB(HCV.x), HCYwts);
    if (Y < Z)
    {
      HCV.y *= Z / (Epsilon + Y);
    }
    else
    {
      HCV.y *= (1 - Z) / (Epsilon + 1 - Y);
    }
    return float3(HCV.x, HCV.y, Y);
  }

I've updated the snippets page accordingly.

Saturday, 6 September 2014

RGB/HSV in HLSL 6

It is often common to need to take a colour image and change some aspect of it: its hue, saturation, brightness or contrast.

You could simply convert the image to an appropriate colour space (e.g. HSV) perform the manipulations and then convert back to RGB. However, of the three components of the HSV colour space, it is least likely that you'll want to change the hue, which is trickiest component to convert. So can you change the saturation and value without performing the full round-trip conversions?

Remember that for RGB to HSV:

  float U = min(R, min(G, B));
  float V = max(R, max(G, B));
  float C = V - U;

  float S = C / (V + Epsilon);

The hue 'H' is given by the difference between two RGB channel values divided by 'V'.

So if we maintain the absolute differences between RGB channel values, we maintain the chroma 'C' (because the 'V' and 'U' values change by the same amount) but not necessarily the HSV saturation 'S' (because the denominator 'V' changes).

This implies we can easily change the chroma (or HSV saturation) by manipulating 'U' without any impact on the value 'V'. However, changing the value 'V' (or lightness) is not so easy without also changing the chroma (or HSV saturation).

Consider another formulation of HSV saturation (without the epsilon term):

  float S = C / V;
          = (V - U) / V;
          = 1 - (U / V);

It is dependent on the ratio of the minimum and maximum RGB channel values. So if we maintain this ratio, we do not affect the HSV saturation.

Anyway, let's start with what appears to be the easier modification first. Suppose we have an RGB triplet and we want to change its HSV saturation to 'S_wanted':

  float U = min(R, min(G, B));
  float V = max(R, max(G, B));

  float Q = S_wanted * V / (V - U + Epsilon);
  RGB = (V - RGB) * Q;

Above, 'Q' is equivalent to 'S_wanted / S' and 'Epsilon' is an appropriately tiny number, e.g. 1e-10.

Now the trickier modification. Suppose we have an RGB triplet and we want to change its HSV value to 'V_wanted' without changing its HSV saturation (or hue). We can multiply all channel values by
'V_wanted / V' and then apply the saturation modification algorithm above to restore the original saturation. But wait! The channel multiplication does not change the ratio of the minimum and maximum RGB channel values, so it therefore does not change the saturation after all. Only a simple multiplicative scaling is required:

  float V = max(R, max(G, B));
  RGB *= V_wanted / (V + Epsilon);

Please remember that we're talking about simplifying modifications in the HSV colour space here. HSL is another matter entirely. 

Wednesday, 23 April 2014

RGB/HSV in HLSL 5

It's been over three years since I started this thread on performing RGB/HSV conversions in HLSL. In those days, I was working with the XBox360 GPU, which has a component-wise 'max4' instruction that I took full advantage of. AMD's GCN architecture has 'min3'/'med3'/'max3' in hardware. However, the focus of GPU hardware designers seems to be shifting away from specialist SIMD pipelines. All this means that something like

  float V = max(R, max(G, B));

doesn't get optimised as well as you might hope.

But, given time, the Internet (or more specifically, Sam Hocevar and Emil Persson) comes up with the solution. And very elegant it is too.

HSV (and HSL) can be computed easily from HCV, where H is the hue [0..1], C is the chroma [0..1] and V is the value [0..1]. The core of a RGB-to-HCV conversion requires the RGB components to be sorted and the smallest and largest extracted:

  float U = min(R, min(G, B));
  float V = max(R, max(G, B));
  float C = V - U;

Any fool knows that three numbers can be sorted using, at most, three comparisons. So why are we doing (effectively) four comparisons? To make things worse, we then go on to compare the largest with the three components again to determine the hue offset.

So, here is the crux of Sam and Emil's optimization:

  float Epsilon = 1e-10;
  float4 P = (G < B) ? float4(B, G, -1.0, 2.0/3.0) : float4(G, B, 0.0, -1.0/3.0);
  float4 Q = (R < P.x) ? float4(P.xyw, R) : float4(R, P.yzx);
  float V = Q.x;
  float C = V - min(Q.w, Q.y);
  float H = abs((Q.w - Q.y) / (6 * C + Epsilon) + Q.z);

'Q.x' contains the largest RGB component, V, and either 'Q.w' or 'Q.y' contains the smallest, U. By shuffling components of P and Q, we get the hue offset and divisor "for free." Also note the cunning use of 'Epsilon' to remove the need to check for division-by-zero. More details here.

Once we have hue/chroma/value, we can compute the HSV saturation [0..1]:

  float S_hsv = C / (V + Epsilon);

Similarly, we can compute the HSL lightness [0..1] and saturation:

  float L = V - C * 0.5;
  float S_hsl = C / (1 - abs(L * 2 - 1) + Epsilon);

In terms of speed ... a notoriously difficult thing to estimate for GPU shaders ... this new RGB-to-HCV function is no slower than the old one and faster for many configurations.

However (and here I feel a tad smug), my original implementation of HSV-to-RGB is still faster than Sam's alternative. Though I'm sure that with a particularly aggressive optimizer on a more scalar configuration, there'd be hardly anything in it.

  float R = abs(H * 6 - 3) - 1;
  float G = 2 - abs(H * 6 - 2);
  float B = 2 - abs(H * 6 - 4);
  float3 RGB = ((saturate(float3(R,G,B)) - 1) * S + 1) * V;

I've placed the HLSL snippets on my main website; I hope no typos have crept in like last time.

For completeness, I've left in the HCY and HCL conversions.

Saturday, 11 January 2014

RGB/HCY and RGB/HCL Corrections

Florian Mosleh was kind enough to take the time to send me an email highlighting some typos that had crept into my implementations of RGB/HCY and RGB/HCL conversions.

I've incorporated the fixes into the HLSL snippets and added functions for RGB-to-HCL and HCL-to-RGB (although there seem to be inherent problems with the HCL colour space).

Monday, 20 August 2012

RGB/HCL in HLSL

The HCL colour space by M. Sarifuddin and Rokia Missaoui (not to be confused with CIELCH) is another colour space that tries to improve on HSL and HSV. It is a cylindrical space which means that, for an accurate implementation, trigonometric functions are necessary. One interesting feature is that it tries to adjust the hue metric to be more perceptually meaningful using piecewise linear interpolation.

Here's the optimised HLSL code to convert from linear RGB:

float HCLgamma = 3;
float HCLy0 = 100;
// HCLmaxL == exp(HCLgamma / HCLy0) - 0.5
float HCLmaxL = 0.530454533953517;

float3 RGBtoHCL(in float3 RGB)
{
  float3 HCL;
  float H = 0;
  float U, V;
#if NO_ASM
  U = -min(RGB.r, min(RGB.g, RGB.b));
  V = max(RGB.r, max(RGB.g, RGB.b));
#else
  float4 RGB4 = RGB.rgbr;
  asm { max4 U, -RGB4 };
  asm { max4 V, RGB4 };
#endif
  float Q = HCLgamma / HCLy0;
  HCL.y = V + U;
  if (HCL.y != 0)
  {
    H = atan2(RGB.g - RGB.b, RGB.r - RGB.g) / PI;
    Q *= -U / V;
  }
  Q = exp(Q);
  HCL.x = frac(H / 2 - min(frac(H), frac(-H)) / 6);
  HCL.y *= Q;
  HCL.z = lerp(U, V, Q) / (HCLmaxL * 2);
}


All components are scaled to fit into the expected [0,1] range.

The weird-looking statement with "frac()" terms is performing the piecewise adjustment of hue.

I'm very happy with this code as it is considerably faster than a simplistic transliteration of the reference code that Sarifuddin Madenda was good enough to send me.

However, the reverse transformation is far from perfect and needs more work to reduce the branching nature of the algorithm:

float HCLtoRGB(in float3 HCL)
{
  float3 RGB = 0;
  if (HCL.z != 0)
  {
    float H = HCL.x;
    float C = HCL.y;
    float L = HCL.z * HCLmaxL;
    float Q = exp((1 - C / (2 * L)) * (HCLgamma / HCLy0));
    float U = (2 * L - C) / (2 * Q - 1);
    float V = C / Q;
    float T = tan((H + min(frac(2 * H) / 4, frac(-2 * H) / 8)) * PI * 2);
    H *= 6;
    if (H <= 1)
    {
      RGB.r = 1;
      RGB.g = T / (1 + T);
    }
    else if (H <= 2)
    {
      RGB.r = (1 + T) / T;
      RGB.g = 1;
    }
    else if (H <= 3)
    {
      RGB.g = 1;
      RGB.b = 1 + T;
    }
    else if (H <= 4)
    {
      RGB.g = 1 / (1 + T);
      RGB.b = 1;
    }
    else if (H <= 5)
    {
      RGB.r = -1 / T;
      RGB.b = 1;
    }
    else
    {
      RGB.r = 1;
      RGB.b = -T;
    }
  }
  return RGB * V + U;
}


The multiple if-statements could be rationalised (binary search style) but I can't help thinking there's some simple trigonometric identity that can be utilised to eradicate them completely.

Monday, 6 August 2012

sRGB Approximations for HLSL

The sRGB color space is non-linear. Many transformations to and from the space require the RGB components to be mapped to a linear form.

The "official" transformation for each RGB component value in the range [0,1] is:

  if (C_srgb <= 0.04045)
      C_lin = C_srgb / 12.92;
  else
      C_lin = pow((C_srgb + 0.055) / 1.055, 2.4);

This is often approximated using the "gamma 2.2" formula:

  C_lin_1 = pow(C_srgb, 2.2);

This works fine, but is fairly inaccurate. The graph below uses the right-hand axis for the absolute difference:


For example, if the values are quantized to eight bits, for the sRGB component value 197/255, the linear output is 145/255 instead of 142/255. Can we do better?

In fact, if we simply change the "magic number" to 2.233333... we get better results:

  C_lin_2 = pow(C_srgb, 2.233333333);


However, the "pow" functionality is either prohibitively expensive or non-existent on many platforms. So, if we limit ourselves to simple arithmetic, a good approximation I found is the cubic:

  C_lin_3 = 0.012522878 * C_srgb +
            0.682171111 * C_srgb * C_srgb +
            0.305306011 * C_srgb * C_srgb * C_srgb;



This can be computed in HLSL using:

  float3 RGB = sRGB * (sRGB * (sRGB * 0.305306011 + 0.682171111) + 0.012522878);

The reverse transformation (from linear to sRGB) is more problematic:

Again, the "official" transformation is piecewise:

  if (C_lin <= 0.0031308)
    C_srgb = C_lin * 12.92;
  else
    C_srgb = 1.055 * pow(C_lin, 1.0 / 2.4) - 0.055;

This is usually poorly approximated with the inverse of the computation of "C_lin_1":

  C_srgb_1 = pow(C_lin, 0.4545454545);


In fact, the linear portion of the official graph is tiny, so an almost-perfect approximation is:

  C_srgb_2 = max(1.055 * pow(C_lin, 0.416666667) - 0.055, 0);


The clamp ("max(..., 0)") is free on many platforms, but the formula does use the "pow" functionality. If we assume we only have square-root operations at our disposal, a good approximation I found was:

  C_srgb_3 = 0.585122381 * sqrt(C_lin) +
             0.783140355 * sqrt(sqrt(C_lin)) -
             0.368262736 * sqrt(sqrt(sqrt(C_lin)));


This can be computed in HLSL using:

  float3 S1 = sqrt(RGB);
  float3 S2 = sqrt(S1);
  float3 S3 = sqrt(S2);
  float3 sRGB = 0.585122381 * S1 + 0.783140355 * S2 - 0.368262736 * S3;

An even better approximation (at the cost of an additional 'mad') is:


  float3 S1 = sqrt(RGB);
  float3 S2 = sqrt(S1);
  float3 S3 = sqrt(S2);
  float3 sRGB = 0.662002687 * S1 + 0.684122060 * S2 - 0.323583601 * S3 - 0.0225411470 * RGB;

Depending on your platform architecture, this may be faster using multiplication by a constant matrix for the final step.

Sunday, 5 August 2012

RGB/HCY in HLSL

The HCY colour space is a tractable hue/chroma/luminance scheme developed by Kuzma Shapran. It is ideal for pixel shaders, being only slightly more expensive that the HSV and HSL schemes. However, it tries to be more "meaningful" in terms of human perception.

The three components are:
  1. Hue (H) computed in the same manner as HSV and HSL;
  2. Chroma (C) computed as the scaled difference between the maximum unweighted RGB component and the minimum unweighted RGB component; and
  3. Luminance (Y) computed as the weighted sum of RGB components.
Note that the chroma is post-scaled so that the maximum weighted luminance for this hue is always one.

The HLSL conversions are as follows:
// The weights of RGB contributions to luminance.
// Should sum to unity.
float3 HCYwts = float3(0.299, 0.587, 0.114);

float3 HUEtoRGB(in float H)
{
  float R = abs(H * 6 - 3) - 1;
  float G = 2 - abs(H * 6 - 2);
  float B = 2 - abs(H * 6 - 4);
  return saturate(float3(R,G,B));
}

float RGBCVtoHUE(in float3 RGB, in float C, in float V)
{
    float3 Delta = (V - RGB) / C;
    Delta.rgb -= Delta.brg;
    Delta.rgb += float3(2,4,6);
    // NOTE 1
    Delta.brg = step(V, RGB) * Delta.brg;
    float H;
#if NO_ASM
    H = max(Delta.r, max(Delta.g, Delta.b));
#else
    float4 Delta4 = Delta.rgbr;
    asm { max4 H, Delta4 };
#endif
    return frac(H / 6);
}

float3 RGBtoHCY(in float3 RGB)
{
  float3 HCY = 0;
  float U, V;
#if NO_ASM
  U = -min(RGB.r, min(RGB.g, RGB.b));
  V = max(RGB.r, max(RGB.g, RGB.b));
#else
  float4 RGB4 = RGB.rgbr;
  asm { max4 U, -RGB4 };
  asm { max4 V, RGB4 };
#endif
  HCY.y = V + U;
  HCY.z = dot(RGB, HCYwts);
  if (HCY.y != 0)
  {
    HCY.x = RGBCVtoHUE(RGB, HCY.y, V);
    float Z = dot(HUEtoRGB(HCY.x), HCYwts);
    if (HCY.z > Z)
    {
      HCY.z = 1 - HCY.z;
      Z = 1 - Z;
    }
    HCY.y *= Z / HCY.z;
  }
  return HCY;
}

float3 HCYtoRGB(in float3 HCY)
{
  float RGB = HUEtoRGB(HCY.x);
  float Z = dot(RGB, HCYwts);
  if (HCY.z < Z)
  {
      HCY.y *= HCY.z / Z;
  }
  else if (Z < 1)
  {
      HCY.y *= (1 - HCY.z) / (1 - Z);
  }
  return (RGB - Z) * HCY.y + HCY.z;
}

I've folded the code into my web page on such conversions here.

Friday, 23 March 2012

RGB/HSV in HLSL 4

I've collated my implementations of RGB to HSV and HSL into a single webpage. See here.