Search Unity

Question Chroma Lum encoding and decoding

Discussion in 'Shaders' started by neoshaman, Jul 22, 2022.

  1. neoshaman

    neoshaman

    Joined:
    Feb 11, 2011
    Posts:
    6,493
    Hello

    I'm trying to do a chroma lum encoding to texture for a complex shader I'm doing. I have used unity formula for YCbCr but it doesn't seem to be reversible. Am I doing something wrong? Is there other way to get chroma lum encoding and decoding?

    Testing the reversibility in code:
    Code (CSharp):
    1. fixed4 frag (v2f i) : SV_Target
    2.             {
    3.                 // sample the texture
    4.                 fixed4 col = tex2D(_MainTex, i.uv);
    5.                 float3 c = col;
    6.                 c = RgbToYCbCr(c);
    7.                 c = YCbCrToRgb(c);
    8.  
    9.                 col = float4(c,1);
    10.                 return col;
    11.             }
    Left is code result, right is original texture colors:
    upload_2022-7-22_6-58-37.png

    Encoding and decoding formula lift from core shader render pipeline from unity:
    Code (CSharp):
    1. //
    2. // RGB / Full-range YCbCr conversions (ITU-R BT.601)
    3. //
    4. float3 RgbToYCbCr(float3 c){
    5.     float Y  =  0.299 * c.r + 0.587 * c.g + 0.114 * c.b;
    6.     float Cb = -0.169 * c.r - 0.331 * c.g + 0.500 * c.b;
    7.     float Cr =  0.500 * c.r - 0.419 * c.g - 0.081 * c.b;
    8.     return float3(Y, Cb, Cr);
    9. }
    10.  
    11. float3 YCbCrToRgb(float3 c){
    12.     float R = c.x + 0.000 * c.y + 1.403 * c.z;
    13.     float G = c.x - 0.344 * c.y - 0.714 * c.z;
    14.     float B = c.x - 1.773 * c.y + 0.000 * c.z;
    15.     return float3(R, G, B);
    16. }
     
  2. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,343
    YCbCr isn't reversible normally, not without some loss, but that's much worse than usual. It looks like the Cb is offset by 0.5, but I don't know if that's the fault of the encode or decode.

    Depending on what you're doing, YCoCg might be a better choice as it is reversible (at least some versions are).
     
    neoshaman likes this.
  3. joshuacwilde

    joshuacwilde

    Joined:
    Feb 4, 2018
    Posts:
    727
    YCoCg has some good examples on shadertoy I have referenced in the past.
     
    neoshaman likes this.
  4. neoshaman

    neoshaman

    Joined:
    Feb 11, 2011
    Posts:
    6,493
    Works great! Thanks!