Sub topic 4
Channels: several numbers per pixel
This chapter assumes you can read basic Python and NumPy, and that you know a byte holds a value from 0 to 255. It builds on the idea that an image is a grid of sampled numbers. Here the question is how many numbers each grid cell holds.
From one number to several
A grayscale pixel needs one number: how bright the cell is. A colour pixel needs more, because colour cannot be described by brightness alone. Each of those numbers is a channel (also called a band or a component). A channel is one full grid of samples, one value per pixel, that measures a single property of the image.
So a pixel is a short vector, and an image has a channel count C:
| Image kind | Channels | Typical pixel |
|---|---|---|
| Grayscale | 1 | `(128,)` |
| Grayscale with transparency | 2 | `(128, 255)` |
| RGB colour | 3 | `(255, 0, 0)` |
| RGB with transparency (RGBA) | 4 | `(255, 0, 0, 255)` |
The channel count is a property of the data. It does not say what the channels mean. Three channels might be red, green, and blue, or they might be hue, saturation, and value. The meaning comes from the colour model and colour space, which later chapters cover.
The shape of a multichannel array
In NumPy, a colour image is usually a three-dimensional array with the shape (height, width, channels). The first index selects the row, the second selects the column, and the third selects the channel.
import numpy as np
img = np.zeros((2, 3, 3), dtype=np.uint8) # (height, width, channels)
img[0, 0] = (255, 0, 0) # red
img[0, 1] = (0, 255, 0) # green
img[0, 2] = (0, 0, 255) # blue
img[1, 0] = (255, 255, 255) # white
img[1, 1] = (128, 128, 128) # mid grey
# img[1, 2] stays (0, 0, 0): black
print(img.shape, img.dtype, img.nbytes) # (2, 3, 3) uint8 18The 18 comes from 2 × 3 × 3 × 1: two rows, three columns, three channels, one byte per sample. Each channel contributes a full height × width grid. Adding a channel therefore multiplies storage by (C + 1) / C. Going from RGB to RGBA adds one third.
Indexing shows the two views of the same data:
import numpy as np
img = np.zeros((2, 3, 3), dtype=np.uint8)
img[0, 0] = (255, 0, 0)
pixel = img[0, 0] # all channels of one pixel -> shape (3,)
red_plane = img[:, :, 0] # one channel for every pixel -> shape (2, 3)
print(pixel) # [255 0 0]
print(red_plane.shape) # (2, 3)A single channel taken on its own is itself a grayscale image. Showing the red channel of a photo as a grey picture is a common debugging step.
Grayscale arrays have two dimensions or three
Libraries disagree on how to store a one-channel image. Some return shape (H, W) and some return (H, W, 1). Both hold the same numbers. The difference matters in code:
- Operations that expect a channel axis, such as batching in a neural network, need
(H, W, 1). - Plotting functions such as
matplotlib.pyplot.imshowaccept(H, W)but reject(H, W, 1).
Use np.squeeze(img, axis=-1) to drop the axis and img[..., np.newaxis] to add it back. Always print img.shape after loading an image, because a "grayscale" file may still decode to three identical channels.
Interleaved and planar layouts
The shape tells you how to index the array. It does not tell you how the bytes sit in memory. Two layouts are common:
- Interleaved (also called packed): the channels of one pixel are stored next to each other:
R G B R G B .... - Planar: each channel is stored as a whole plane, one after another: all the
Rvalues, then all theGvalues, then all theBvalues.
A (H, W, C) NumPy array in default row-major order is interleaved. Strides show this. A stride is the number of bytes to step to reach the next element along an axis.
import numpy as np
img = np.zeros((2, 3, 3), dtype=np.uint8)
print(img.strides) # (9, 3, 1): bytes to step one row, one pixel, one channel
planar = np.ascontiguousarray(img.transpose(2, 0, 1)) # (channels, height, width)
print(planar.shape) # (3, 2, 3)The strides (9, 3, 1) mean that moving one channel costs 1 byte, one pixel costs 3 bytes, and one row costs 9 bytes. Neighbouring channels are neighbours in memory.
transpose(2, 0, 1) alone does not move any bytes. It only changes the shape and strides, producing a view. np.ascontiguousarray then copies the data so that the planar order is physically real. Deep learning frameworks such as PyTorch usually expect the (C, H, W) order, so this conversion is common when passing images to a model.
Interleaved suits per-pixel work such as colour conversion, since all of a pixel's values sit together. Planar suits per-channel work such as filtering one channel, and it is how some video formats store data.
Channel order
Channel count is not enough. You also need the order. Most libraries, including Pillow and matplotlib, use RGB. OpenCV's imread returns BGR, a historical choice. If you load with OpenCV and display with matplotlib, red and blue swap, and skin looks blue.
Reversing the last axis converts between the two:
import numpy as np
rgb = np.array([[[255, 0, 0]]], dtype=np.uint8) # one red pixel
bgr = rgb[..., ::-1] # reverse the channel axis
print(bgr) # [[[ 0 0 255]]]The slice [..., ::-1] is a view with a negative stride. Pass it through np.ascontiguousarray if a library needs a contiguous buffer.
Channels that are not colour
Channels can hold data other than colour:
- Alpha stores opacity, where 0 is transparent and 255 is opaque in 8-bit images.
- Depth from a depth camera is a single channel storing distance.
- Multispectral and satellite images can have a dozen or more channels, each for one wavelength band.
- Feature maps inside a neural network have hundreds of channels, none of which is a colour.
The same array-and-axis reasoning applies in every case.
Common errors
- Assuming three channels. A PNG may decode with 4 channels (RGBA) or 1. Check
shape[-1]before indexing channels. - Mixing orders.
(H, W, C)and(C, H, W)look alike whenCis small. A(3, 224, 224)array passed to code that expects(224, 224, 3)may run and produce nonsense. - Reading
nbytesas file size. It gives the raw in-memory size, not the compressed file size. - Forgetting the copy. A transposed or reversed array is a view. Writing to it changes the original.
Exercise
A camera produces an 8-bit RGBA image of 640 × 480 pixels. What are the array shape in (H, W, C) form and the raw size in bytes? What is the shape after converting it to a planar (C, H, W) layout?
Show answer
The shape is (480, 640, 4). The raw size is 480 × 640 × 4 × 1 = 1,228,800 bytes. The planar shape is (4, 480, 640), and the raw size is unchanged because only the order of the same samples changes.
Exercise
You load a photo with OpenCV and show it with matplotlib. The sky looks orange instead of blue. What is the cause, and which one line of NumPy fixes it?
Show answer
OpenCV returns channels in BGR order, while matplotlib expects RGB, so red and blue are swapped. Reverse the channel axis with img = img[..., ::-1] before displaying.