Sub topic 12
Gamma Encoding and Linear Light
Prerequisites and the working model
This chapter assumes you understand pixels, channels, arrays, and 8-bit values. You should also know that an RGB image stores three channel values, usually from 0 to 255.
A stored channel value is not always proportional to physical light. Displays and image formats often use gamma encoding, which is a nonlinear mapping between light intensity and a stored number. The mapping gives more stored precision to dark tones, where changes are easier to notice.
Linear light is a representation where a value of 0.5 means half the maximum light intensity. In a gamma-encoded image, 0.5 usually means something else.
Why encoding is needed
Human vision is more sensitive to relative changes in dark regions than in bright regions. Storing images directly as linear values would spend too many code values on bright differences that people barely notice. Gamma encoding redistributes the values.
For example, an 8-bit sRGB value of 128 looks like the middle of the numeric range, but it represents only about 21.6% of maximum light:
| Stored sRGB value | Normalised value | Approximate linear light |
|---|---|---|
| 128 | 0.502 | 0.216 |
| 188 | 0.737 | 0.503 |
| 255 | 1.000 | 1.000 |
sRGB is the common colour space for web images. Its transfer function is not a single perfect power curve. It has a small linear section near black and a power-law section elsewhere.
Converting sRGB values
Decode before operations that represent light, such as blending, resizing, blur, shading, and convolution. Encode the result when writing it back to an ordinary sRGB image.
import numpy as np
def srgb_to_linear(value):
c = np.asarray(value, dtype=np.float64) / 255.0
return np.where(
c <= 0.04045,
c / 12.92,
((c + 0.055) / 1.055) ** 2.4,
)
def linear_to_srgb(value):
x = np.asarray(value, dtype=np.float64)
encoded = np.where(
x <= 0.0031308,
12.92 * x,
1.055 * np.maximum(x, 0) ** (1 / 2.4) - 0.055,
)
return np.round(np.clip(encoded, 0, 1) * 255).astype(np.uint8)
linear = srgb_to_linear(128)
print(linear) # about 0.216
print(linear_to_srgb(linear)) # 128Common errors
Averaging encoded values does not correctly average light. Blending black (0) and white (255) directly in sRGB gives 128, which decodes to about 21.6% light. Blending them after decoding gives 50% light, which encodes to about 188.
Another error is applying the conversion twice. Keep track of whether an array is encoded or linear, and document that state beside the array or in the processing pipeline.
Exercise
Why should you decode sRGB values before blending black and white?
Show answer
sRGB values are nonlinear. Decoding converts them to values proportional to light, so the blend represents the correct physical brightness.