Sub topic 7
The alpha channel and transparency
This chapter assumes you know that an image is a height × width × channels array and that RGB images have three 8-bit channels. It adds a fourth channel that records how much of a pixel is covered by the image rather than what colour it is.
What alpha stores
The alpha channel is an extra sample per pixel that describes opacity. At the minimum value the pixel is fully transparent. At the maximum it is fully opaque. With 8-bit samples, 0 means transparent, 255 means opaque, and 128 means about 50% opaque. Dividing by 255 gives a fraction between 0.0 and 1.0.
Alpha does not describe colour. An RGBA pixel of (255, 0, 0, 128) is red that covers half of whatever lies behind it. Alpha has no visible effect until the pixel is combined with something else, such as a page background or another layer.
An RGBA image has shape (height, width, 4). Its raw size is 4/3 that of the same RGB image, using the formula from the raw size chapter.
Which formats carry alpha matters in practice:
| Format | Alpha support |
|---|---|
| JPEG | None. Transparent regions must be flattened onto a colour first. |
| PNG | Full 8-bit or 16-bit alpha, or a single transparent palette entry. |
| GIF | 1-bit only. A pixel is either fully transparent or fully opaque. |
| WebP | 8-bit alpha, in both lossy and lossless modes. |
| TIFF | Optional extra channel. |
Compositing with the over operator
To draw a foreground pixel over a background pixel, you blend them using the foreground's alpha. This is the "over" operator, and it is a weighted average. Take a foreground colour C_f with alpha a_f, and an opaque background colour C_b. The result is:
C_out = a_f * C_f + (1 - a_f) * C_b
The rule is applied per colour channel. If the background is also partly transparent, the result needs its own alpha, which is a_out = a_f + a_b * (1 - a_f).
The following code composites two pixels over white:
import numpy as np
# One row, two pixels: opaque red and half-transparent red (RGBA, uint8)
fg = np.array([[[255, 0, 0, 255], [255, 0, 0, 128]]], dtype=np.uint8)
bg = np.array([255, 255, 255], dtype=np.float64) # white background
alpha = fg[..., 3:4] / 255.0 # shape (1, 2, 1), values 0.0 to 1.0
rgb = fg[..., :3].astype(np.float64) # convert before arithmetic
out = alpha * rgb + (1.0 - alpha) * bg
print(out.round().astype(np.uint8))
# first pixel: [255 0 0]; second pixel: [255 127 127], a pale redTwo details in this code are easy to get wrong. The slice 3:4 keeps a trailing axis of length 1, so alpha broadcasts across the three colour channels. Converting to float before multiplying avoids uint8 overflow, because NumPy wraps uint8 values silently instead of raising an error.
Straight and premultiplied alpha
There are two common ways to store colour alongside alpha.
- Straight (unassociated) alpha stores the colour as if the pixel were fully opaque. PNG files use this convention, and most image libraries expose it when they load a file.
- Premultiplied (associated) alpha stores colour already multiplied by alpha. Many GPU pipelines and compositors use it internally.
The two representations are related by a multiplication and a division:
import numpy as np
straight = np.array([255.0, 0.0, 0.0, 128.0]) # red, about 50% opaque
a = straight[3] / 255.0
premul = np.array([*(straight[:3] * a), straight[3]])
print(premul.round()) # [128. 0. 0. 128.]
restored = np.array([*(premul[:3] / a), premul[3]])
print(restored.round()) # [255. 0. 0. 128.]With premultiplied alpha the over operator simplifies to C_out = C_f' + (1 - a_f) * C_b, where C_f' is the premultiplied foreground. It needs one multiplication per channel instead of two. It also behaves better when an image is resized or blurred, because averaging neighbouring premultiplied pixels gives correct results.
Converting back has a cost. Dividing by alpha fails when alpha is 0, and at 8 bits it loses precision for very transparent pixels. A pixel with alpha 1 can only store premultiplied colour values of 0 or 1, so recovering the original colour is imprecise.
Alpha and gamma
The over formula is a weighted average, so it assumes the values it mixes are proportional to light. sRGB values are gamma-encoded, so the formula is only an approximation when applied to them directly. The blend is physically correct only in linear light.
You can see the difference by mixing black and white at 50% alpha:
import numpy as np
def srgb_to_linear(v):
c = np.asarray(v, dtype=np.float64) / 255.0
return np.where(c <= 0.04045, c / 12.92, ((c + 0.055) / 1.055) ** 2.4)
def linear_to_srgb8(lin):
lin = np.asarray(lin, dtype=np.float64)
c = np.where(lin <= 0.0031308, lin * 12.92, 1.055 * lin ** (1 / 2.4) - 0.055)
return np.round(c * 255.0)
# 50% black over white, blended on the stored values
print(0.5 * 0 + 0.5 * 255) # 127.5, stored as about 128
# The same blend in linear light
lin = 0.5 * srgb_to_linear(0) + 0.5 * srgb_to_linear(255)
print(linear_to_srgb8(lin)) # about 188, a visibly lighter greyMost software blends on the stored values, as the first line does, and results are expected to match that behaviour. Design tools, web browsers, and image libraries typically do this. Blending in linear light is more accurate, and it matters most for soft shadows and anti-aliased edges. Choose one approach and keep it consistent across your pipeline.
Other uses and edge cases
Alpha is not only for transparent logos. A single-channel alpha is also called a matte or mask. Segmentation and matting systems often output one, and you can apply it as a cut-out of an object.
Several details are worth remembering:
- Flattening to JPEG. Choose a background colour and composite before saving. Skipping this step lets the library pick one for you, often black.
- Channel order. Libraries differ. OpenCV uses BGRA, while Pillow and most others use RGBA. The alpha channel normally stays last.
- Bit depth. A 16-bit PNG has 16-bit alpha. Divide by 65535 rather than 255.
- Colour under transparency. Pixels with alpha 0 still hold RGB values, and these may be used when an image is later resampled.
- Models and alpha. Most vision models expect three channels. Drop alpha deliberately, by compositing onto a known background, rather than letting a loader discard it.
Exercise
A straight-alpha pixel is (200, 100, 50, 51) in 8-bit RGBA. (a) What is its premultiplied form? (b) What RGB value results when it is composited over an opaque background of (100, 100, 100), blending on the stored values?
Show answer
Alpha as a fraction is 51 / 255 = 0.2. (a) Premultiplied: (200 × 0.2, 100 × 0.2, 50 × 0.2, 51) = (40, 20, 10, 51). (b) Using the over formula with a = 0.2: red = 0.2 × 200 + 0.8 × 100 = 120, green = 0.2 × 100 + 0.8 × 100 = 100, blue = 0.2 × 50 + 0.8 × 100 = 90. The result is (120, 100, 90).
Exercise
Why does saving an RGBA image as JPEG require a decision about a background colour?
Show answer
JPEG has no alpha channel, so transparency cannot be stored. The image must be composited onto a chosen background colour first, and the result saved as plain RGB. Otherwise the library picks a default, often black.