Sub topic 7
The alpha channel and transparency
Prerequisites
Assume you know that an image is an array of pixels, that RGB uses three colour channels, and that an 8-bit channel stores values from 0 to 255. You should also be comfortable with basic arithmetic and Python.
What the alpha channel stores
An alpha channel is an extra value associated with each pixel. It usually describes opacity:
| Alpha value | Meaning |
|---|---|
| 0 | Fully transparent |
| 128 | About half opaque |
| 255 | Fully opaque |
An RGBA pixel therefore contains red, green, blue, and alpha values. Alpha is not a colour. It is metadata about how the colour should combine with another image or background.
With 8-bit channels, RGB uses 3 bytes per pixel. RGBA uses 4 bytes per pixel, so adding alpha increases the raw pixel storage by one third.
def composite(foreground, background, alpha):
"""Composite an RGB foreground over an RGB background."""
a = alpha / 255
return tuple(round(a * fg + (1 - a) * bg)
for fg, bg in zip(foreground, background))
red = (255, 0, 0)
white = (255, 255, 255)
print(composite(red, white, 255)) # (255, 0, 0)
print(composite(red, white, 128)) # (255, 127, 127)
print(composite(red, white, 0)) # (255, 255, 255)The compositing equation for each channel is:
output = alpha × foreground + (1 − alpha) × background
Here, alpha must be scaled to the range 0 to 1. The result depends on the background. A half-transparent red pixel appears pink over white but dark red over black.
Straight and premultiplied alpha
In straight, or unassociated, alpha, RGB stores the colour as if it were fully opaque, and alpha is stored separately. A half-transparent red pixel is (255, 0, 0, 128).
In premultiplied alpha, RGB has already been multiplied by alpha. The same pixel is approximately (128, 0, 0, 128). This representation makes many blending operations safer and avoids bright fringes around transparent edges, but programs must know which representation they are receiving.
| Representation | Stored RGB for half-transparent red | Common concern |
|---|---|---|
| Straight alpha | `(255, 0, 0)` | Incorrect filtering can create halos |
| Premultiplied alpha | `(128, 0, 0)` | Treating it as straight makes colours too dark |
File formats and common errors
PNG commonly stores RGBA and preserves alpha losslessly. JPEG normally stores RGB and does not preserve transparency. A transparent PNG placed over a background may look correct until it is resized, filtered, or converted.
Check these details when debugging:
- Is the image RGB or RGBA?
- Is alpha straight or premultiplied?
- Is alpha represented by 0–1, 0–255, or another range?
- Does the display software composite against a checkerboard, black, or white background?
Exercise
A foreground channel is 200, the background channel is 20, and alpha is 0.25. What output channel should compositing produce?
Show answer
65, because 0.25 × 200 + 0.75 × 20 = 65.