Skip to content

Instantly share code, notes, and snippets.

@behreajj
Created November 10, 2021 20:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save behreajj/2e160cbdc1c72b3411f8bbba27d777b6 to your computer and use it in GitHub Desktop.
Save behreajj/2e160cbdc1c72b3411f8bbba27d777b6 to your computer and use it in GitHub Desktop.
Perceptual Transforms, Cont.
static Vector4 LinearToXyz (in Color c)
{
// This could also be written as matrix-vector multiplication.
// Perceptual luminance is the y component.
return new Vector4 (
0.41241086f * c.r + 0.35758457f * c.g + 0.1804538f * c.b,
0.21264935f * c.r + 0.71516913f * c.g + 0.07218152f * c.b,
0.019331759f * c.r + 0.11919486f * c.g + 0.95039004f * c.b,
c.a);
}
static Vector4 XyzToCieLab (in Vector4 xyz)
{
Vector4 v = Vector4.Scale (xyz, new Vector4 (1.0f / 0.95047f, 1.0f, 1.0f / 1.08883f, 1.0f));
v.x = (v.x > 0.008856f) ? Mathf.Pow (v.x, 1.0f / 3.0f) : (7.787f * v.x + 16.0f / 116.0f);
v.y = (v.y > 0.008856f) ? Mathf.Pow (v.y, 1.0f / 3.0f) : (7.787f * v.y + 16.0f / 116.0f);
v.z = (v.z > 0.008856f) ? Mathf.Pow (v.z, 1.0f / 3.0f) : (7.787f * v.z + 16.0f / 116.0f);
float L = 116.0f * v.y - 16.0f;
float a = 500.0f * (v.x - v.y);
float b = 200.0f * (v.y - v.z);
return new Vector4 (a, L, b, xyz.w);
}
static Vector4 CieLabToXyz (in Vector4 lab)
{
float L = lab.y;
float a = lab.x;
float b = lab.z;
float vy = (L + 16.0f) / 116.0f;
float vx = a / 500.0f + vy;
float vz = vy - b / 200.0f;
float vye3 = vy * vy * vy;
float vxe3 = vx * vx * vx;
float vze3 = vz * vz * vz;
vy = (vye3 > 0.008856f) ? vye3 : ((vy - 16.0f / 116.0f) / 7.787f);
vx = (vxe3 > 0.008856f) ? vxe3 : ((vx - 16.0f / 116.0f) / 7.787f);
vz = (vze3 > 0.008856f) ? vze3 : ((vz - 16.0f / 116.0f) / 7.787f);
return new Vector4 (vx * 0.95047f, vy, vz * 1.08883f, lab.w);
}
static Color XyzToLinear (in Vector4 xyz)
{
// This could also be written as matrix-vector multiplication.
return new Color (
3.2408123f * xyz.x - 1.5373085f * xyz.y - 0.49858654f * xyz.z, //
-0.969243f * xyz.x + 1.8759663f * xyz.y + 0.041555032f * xyz.z,
0.0556384f * xyz.x - 0.20400746f * xyz.y + 1.057129f * xyz.z,
xyz.w);
}
static Color LinearToStandard (in Color c)
{
return new Color (
LinearToStandardChannel (c.r),
LinearToStandardChannel (c.g),
LinearToStandardChannel (c.b),
c.a);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment