How to Convert RGB to CIELAB (Lab)
Converting RGB to CIELAB (Lab) is the process of taking a color defined by how a monitor emits light, and translating it into a color space defined by how the human eye perceives light.
Why Convert to Lab?
RGB is a device-dependent color space. The exact shade of rgb(255 0 0) can look slightly different depending on the monitor displaying it. Furthermore, RGB is not perceptually uniform. A 10% mathematical change in green looks drastically different to the human eye than a 10% change in blue.
Lab solves this. It is a device-independent, perceptually uniform color space. The L channel represents Lightness, while the a and b channels represent color-opponent dimensions (green-red and blue-yellow). Because it maps to human vision, Lab is the gold standard for calculating color difference (Delta E) and generating smooth, natural gradients.
The Conversion Pipeline
You cannot convert RGB directly to Lab using simple arithmetic. The conversion requires a complex pipeline of matrix transformations:
- Linearization: Standard CSS RGB values are gamma-corrected. This curve must be removed to convert the values into linear light.
- RGB to XYZ: The linear RGB values are multiplied against a transformation matrix to convert them into the CIE XYZ color space, which is the absolute reference space for all color math.
- XYZ to Lab: The XYZ values are compared against a reference white point (usually D50 for Lab) and passed through a non-linear cube-root function to map them onto the perceptual Lab axes.
Because of this complexity, it is highly recommended to use a dedicated color math library rather than writing the matrix transformations from scratch.