Sub topic 9
How pixels are arranged in memory
An image array is a block of bytes, and the shape and strides tell your code how to read it. This chapter covers the layouts you will meet in practice, how to compute where a given sample sits, and the errors that come from misreading a layout. It assumes you can read NumPy shapes, know that a uint8 takes one byte, and have seen an image as a height by width by channels array.
One-dimensional memory, multi-dimensional meaning
Memory is a flat sequence of bytes. A 2-D or 3-D image is a convention for interpreting that sequence. Three decisions fix the convention:
- Row order. Most libraries use row-major order, also called C order. The samples of row 0 come first, then row 1, and so on. Within a row, pixels run left to right.
- Channel arrangement. Samples of one pixel can sit together (interleaved) or each channel can have its own block (planar).
- Row spacing. The distance between the start of one row and the start of the next is the stride. It can be larger than the row's pixel data.
Strides are the general answer. For any element, the byte offset from the start of the buffer is the sum of each index multiplied by its stride.
Interleaved layout
In an interleaved layout, also called packed or chunky, the channels of one pixel are adjacent: R, G, B, R, G, B, and so on. NumPy, Pillow, OpenCV, and most image file decoders produce an array of shape (height, width, channels). A height-width-channel array is HWC for short.
Planar layout
In a planar layout, all red samples come first, then all green, then all blue. The array shape is (channels, height, width), or CHW. Many deep learning frameworks, such as PyTorch, expect CHW tensors. Some video formats also store planes separately, for example one luma plane and two chroma planes.
| Property | Interleaved (HWC) | Planar (CHW) |
|---|---|---|
| Neighbours in memory | Channels of one pixel | Pixels of one channel |
| Typical shape | `(H, W, C)` | `(C, H, W)` |
| Good for | Decoding, display, per-pixel colour work | Per-channel filters, convolution libraries, plane-based video |
| Contiguous run when reading one pixel | Yes | No, C separate locations |
| Contiguous run when reading one channel | No, strided | Yes |
Neither layout is faster in general. The faster one is the one that matches how your code walks the data.
Reading shape and strides
NumPy exposes strides in bytes. For a contiguous uint8 array of shape (2, 3, 3), one row is 3 pixels × 3 channels × 1 byte = 9 bytes, one pixel is 3 bytes, and one channel is 1 byte.
import numpy as np
img = np.zeros((2, 3, 3), dtype=np.uint8)
print(img.shape, img.strides) # (2, 3, 3) (9, 3, 1)
row, col, ch = 1, 2, 0
offset = row * img.strides[0] + col * img.strides[1] + ch * img.strides[2]
print(offset) # 14: the red sample of the last pixel
planar = img.transpose(2, 0, 1)
print(planar.shape, planar.strides) # (3, 2, 3) (1, 9, 3)
print(planar.flags["C_CONTIGUOUS"]) # FalseThe transposed array has shape CHW, but its strides (1, 9, 3) show that the bytes did not move. Stepping one channel moves one byte, which is still the interleaved layout. transpose returns a view: a new description of the same bytes. No pixel was copied.
Views, copies, and contiguity
A view is cheap, but some code requires a particular physical layout. To get a real planar buffer, force a copy:
import numpy as np
img = np.arange(18, dtype=np.uint8).reshape(2, 3, 3)
planar_view = img.transpose(2, 0, 1)
planar = np.ascontiguousarray(planar_view)
print(planar.strides) # (6, 3, 1)
print(np.shares_memory(img, planar_view)) # True
print(np.shares_memory(img, planar)) # False
bgr_view = img[..., ::-1]
print(bgr_view.strides) # (9, 3, -1)
print(bgr_view.flags["C_CONTIGUOUS"]) # False
bgr = np.ascontiguousarray(bgr_view)
print(bgr.strides) # (9, 3, 1)Reversing the channel axis gives a stride of -1. The array reads each pixel's bytes backwards without moving anything. That is the RGB to BGR conversion from the previous chapter, done at zero copy cost. It is also why a library that takes a raw pointer may reject or misread such an array. Many C-based functions, such as some OpenCV calls, require contiguous memory. If you pass a negative-stride view, you may get an error or a wrong result. Call np.ascontiguousarray first.
Row padding
The stride of the row axis is not always width × channels × bytes. Hardware and libraries often align each row to a 4-, 16-, or 64-byte boundary, so rows get padding bytes at the end. Bitmap (BMP) files pad every row to a multiple of 4 bytes. Video frames and GPU textures often do the same.
import numpy as np
height, width, channels = 3, 5, 3
row_stride = 16 # 15 bytes of pixel data + 1 byte of padding
buf = bytearray(range(height * row_stride))
img = np.ndarray((height, width, channels), dtype=np.uint8,
buffer=buf, strides=(row_stride, channels, 1))
print(img.strides) # (16, 3, 1)
print(img.flags["C_CONTIGUOUS"]) # False
print(img.nbytes, len(buf)) # 45 48
print(img[1, 2, 0], buf[1 * 16 + 2 * 3 + 0]) # 22 22The array is correct only because the strides say so. If you ignored the padding and reshaped the raw buffer as (3, 5, 3), every row after the first would shift by one more byte. The picture would show a diagonal skew.
Common errors
- Wrong layout assumption. Passing an HWC array to code that expects CHW does not raise an error if the sizes happen to fit. The result is nonsense channels. Check
shapeagainst the documented layout. - Reshape instead of transpose.
img.reshape(3, H, W)reinterprets the bytes. It does not move the channel axis. Usetranspose(and copy if needed). - Hidden views. Modifying a view changes the original.
img[..., ::-1]shares memory withimg. Writing to the result also writes to the source. - Raw size versus buffer size. Row padding means
len(buf)can exceedheight × width × channels × bytes. Compare both when debugging. - Slow strided access. Looping over channels of an HWC array in the inner loop touches memory with a stride. Where speed matters, make the inner loop walk the axis with the smallest stride.
Exercise
A contiguous uint8 RGB image has shape (480, 640, 3). (a) What are its strides in bytes? (b) At what byte offset is the green sample of the pixel in row 10, column 20? (c) After np.ascontiguousarray(img.transpose(2, 0, 1)), what are the strides?
Show answer
(a) One row is 640 × 3 = 1920 bytes, one pixel is 3 bytes, one channel is 1 byte, so the strides are (1920, 3, 1). (b) Green is channel 1, so the offset is 10 × 1920 + 20 × 3 + 1 × 1 = 19200 + 60 + 1 = 19261. (c) The new shape is (3, 480, 640). One plane is 480 × 640 = 307200 bytes, one row is 640 bytes, and one sample is 1 byte, so the strides are (307200, 640, 1).
Exercise
A decoder gives you a buffer of 4800 bytes for an image with width 30, height 40, and 3 channels of 8 bits each. The raw pixel data needs 30 × 40 × 3 = 3600 bytes. What is the likely row stride, and what shape and strides would you pass to np.ndarray?
Show answer
The buffer holds 4800 / 40 = 120 bytes per row, while the pixel data needs only 30 × 3 = 90 bytes per row. So the row stride is 120 bytes, with 30 bytes of padding per row. Use shape (40, 30, 3) and strides (120, 3, 1).