Sub topic 12
Gamma encoding and linear light
This chapter assumes you can read NumPy arrays, know that an 8-bit channel holds integers from 0 to 255, and have met the RGB model and sRGB as a name. It explains why stored pixel values are not proportional to light, and what that means when you process images.
Two meanings of "brightness"
A camera sensor counts photons. Twice as many photons produce twice the signal. That signal is linear light: the number is proportional to physical intensity.
Image files rarely store linear values. They store gamma-encoded values, which are a nonlinear function of linear light. The encoding is a power-law-like curve that spends more of the available codes on dark tones and fewer on bright ones.
Two facts explain why:
- Human vision is more sensitive to differences between dark tones than between bright tones. A step from 1% to 2% of maximum light is easy to see. A step from 91% to 92% is not.
- With only 256 codes per channel, a linear encoding would waste codes on bright tones and leave too few in the shadows. Visible banding would appear in dark gradients.
Gamma encoding is therefore a compression of the range based on perception. It lets 8 bits look smooth.
The sRGB transfer function
The sRGB standard defines the curve. Let c be the stored value scaled to the range 0 to 1, and L the linear light on the same scale. Decoding is:
- If
c <= 0.04045, thenL = c / 12.92 - Otherwise
L = ((c + 0.055) / 1.055) ** 2.4
The curve is close to a power of about 2.2, but it has a short linear segment near black so that the slope does not become zero there. Encoding is the inverse function.
import numpy as np
def srgb_to_linear(value_8bit):
c = np.asarray(value_8bit, 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(linear):
l = np.clip(np.asarray(linear, dtype=np.float64), 0.0, 1.0)
c = np.where(l <= 0.0031308, l * 12.92, 1.055 * l ** (1 / 2.4) - 0.055)
return np.round(c * 255.0).astype(np.uint8)
print(srgb_to_linear(128)) # about 0.216
print(srgb_to_linear(255)) # 1.0
print(linear_to_srgb(0.216)) # 128The key result is that a stored mid-grey of 128 carries only about 21.6% of the maximum light. The stored number is roughly halfway up the range, but the physical intensity is about a fifth of the maximum.
| Stored value | Fraction of stored range | Linear light |
|---|---|---|
| 0 | 0.00 | 0.000 |
| 64 | 0.25 | about 0.051 |
| 128 | 0.50 | about 0.216 |
| 192 | 0.75 | about 0.527 |
| 255 | 1.00 | 1.000 |
Why this matters for processing
Many operations assume that numbers add up like light: averaging, blurring, resizing, blending, and compositing. On linear values they behave physically. On gamma-encoded values they give subtly wrong results.
Consider averaging a black pixel (0) and a white pixel (255), as happens when you shrink a checkerboard.
import numpy as np
black, white = 0, 255
naive = (black + white) / 2
print(naive) # 127.5, stored value
lin = (srgb_to_linear(black) + srgb_to_linear(white)) / 2
print(lin) # 0.5 linear light
print(linear_to_srgb(lin)) # 188, the correct stored valueThe naive average, about 128, corresponds to only 21.6% of the light. The physically correct average of half the light is stored as about 188. A checkerboard resized in encoded space looks too dark. The same bias darkens blurs, makes coloured edges muddy, and shifts the result of alpha blending.
Run the snippet after defining the two functions from the previous example, since it reuses them.
Where linear light is the right working space
- Resizing, blurring, and other filtering.
- Blending, compositing, and lighting calculations in graphics and rendering.
- Physically based tasks such as measuring exposure or simulating a lens.
Where encoded values are fine
- Comparing pixel values for equality, or simple thresholds chosen by eye.
- Feeding images to neural networks trained on encoded values. Models learn from the data distribution they were given, so convert only if the training pipeline did.
- Most display-oriented editing, where the operation is defined on perceived tones.
Many libraries, including OpenCV's cv2.resize and Pillow's resampling, work directly on the stored values and do not convert to linear light. Check the documentation rather than assuming.
Precision and the linear trap
If you decode to linear light, do not keep the result in uint8. Linear values are crowded near black. The 8-bit codes 0 to 12 all decode to less than 0.004, so rounding them back to 8-bit linear integers would collapse many dark tones into a few levels. Use float32 or float64, or at least 16-bit integers, for linear data. Re-encode to 8-bit sRGB only at the end.
import numpy as np
codes = np.arange(0, 256, dtype=np.uint8)
lin = srgb_to_linear(codes)
# Round linear values into 8 bits: how many distinct levels remain?
lin8 = np.round(lin * 255).astype(np.uint8)
print(len(np.unique(lin8))) # far fewer than 256Common errors
- Treating 128 as "half brightness". It is half of the code range, but about a fifth of the light.
- Applying the curve twice. Decoding an image that is already linear, or encoding twice, produces washed-out or crushed results. Know the state of your data.
- Alpha and gamma confusion. Alpha is a linear fraction of coverage, not a gamma-encoded value. Apply the transfer function to colour channels only.
- Forgetting that the curve is not a plain power law.
c ** 2.2is a reasonable approximation, but the sRGB piecewise form differs near black. - Assuming all files are sRGB. Some images use other transfer curves, such as Adobe RGB (about 2.2), Display P3 (sRGB curve), or Rec. 709 video (a different curve). An embedded profile says which applies, as a later chapter covers.
Summary
- Stored pixel values are usually nonlinear in light. Decoding gives linear light, and encoding reverses it.
- The sRGB curve gives about 21.6% light for a stored 128.
- Filtering, resizing, and blending are physically correct in linear light, so decode, compute in floating point, then encode.
- Keep track of which state your array is in.
Exercise
A 2×1 sRGB image has pixel values 64 and 192 in one grey channel. Using the table in this chapter (64 gives about 0.051 linear light, 192 gives about 0.527), what is the physically correct average in linear light, and is it brighter or darker than the naive stored-value average of 128, which decodes to about 0.216?
Show answer
The linear average is (0.051 + 0.527) / 2 = 0.289. That is brighter than 0.216, which is the light carried by the naive stored average of 128. Averaging in encoded space therefore makes the result too dark. Encoding 0.289 back to sRGB gives a stored value of about 148.
Exercise
Why should you hold linear-light data in float32 rather than uint8 when you process an image?
Show answer
Linear values crowd near black. If you round them into 8-bit integers, many dark codes collapse into the same few levels, which causes banding and loses shadow detail. Floating point (or at least 16-bit integers) keeps the precision until you encode back to 8-bit sRGB.