Sub topic 4
Channels: Several Numbers per Pixel
This chapter assumes basic Python, arrays, bytes, and common image formats such as JPEG and PNG. A channel is one stream of numbers that describes one property of every pixel. An image may have one channel, three channels, or more.
One pixel, several values
A grayscale image has one channel. Each pixel stores one intensity value, usually from 0 for black to 255 for white when the image uses 8-bit samples.
A colour image commonly uses three channels:
- Red
- Green
- Blue
Together, these channels form the RGB colour model. A pixel such as (255, 0, 0) is fully red, while (20, 80, 200) is a darker blue-purple colour.
The channel values are not separate pixels. They are different measurements belonging to the same pixel location.
| Image type | Channels per pixel | Typical meaning |
|---|---|---|
| Grayscale | 1 | Intensity |
| RGB | 3 | Red, green, and blue |
| RGBA | 4 | Red, green, blue, and transparency |
| Binary mask | 1 | Membership, often 0 or 1 |
Reading an image array
A colour image is often represented by a three-dimensional array. The shape may be (height, width, channels), abbreviated as HWC. For example, an array with shape (480, 640, 3) contains 480 rows, 640 columns, and three channel values at each location.
Some libraries use (channels, height, width), or CHW, instead. The numbers may be identical, but code that assumes the wrong order will interpret the image incorrectly.
import numpy as np
image = np.zeros((2, 3, 3), dtype=np.uint8)
image[0, 0] = (255, 0, 0) # red pixel
image[0, 1] = (0, 255, 0) # green pixel
print(image.shape) # (2, 3, 3)
print(image[0, 0]) # [255 0 0]
print(image[:, :, 0]) # the red channelThe expression image[:, :, 0] selects every row and column from channel zero. It produces a two-dimensional grayscale-like array containing only red intensity.
Alpha and masks
An alpha channel stores opacity rather than colour. In RGBA, alpha is usually 0 for fully transparent and 255 for fully opaque. Alpha does not automatically make a background disappear. A renderer must combine the pixel with a background using the alpha value.
A single-channel image can also be a mask. A mask marks regions for later processing, such as foreground pixels, defects, or segmentation results. Its values might be Boolean, 0 and 1, or 0 and 255.
Channel order and common errors
RGB and BGR contain the same three kinds of colour information, but their order differs. A BGR image displayed as RGB makes red objects appear blue and blue objects appear red. Always check both the array shape and the channel order before displaying or processing an image.
Exercise
An array has shape (720, 1280, 4). What does the final dimension usually represent, and what extra information does it contain?
Show answer
It usually represents four channels: red, green, blue, and alpha. The alpha channel stores opacity or transparency.