Sub topic 9
How Pixels Are Arranged in Memory
Assume you know basic Python, arrays, bytes, and common image files. This chapter uses NumPy terminology, but the ideas apply to most image libraries.
An image is usually represented as an array. For a colour image, the common shape is:
(height, width, channels)For example, an array with shape (1080, 1920, 3) contains 1,080 rows, 1,920 pixels per row, and three channel values per pixel.
Interleaved and planar layouts
In an interleaved layout, the channel values for each pixel are adjacent:
R G B R G B R G B
R G B R G B R G BAn array with shape (height, width, channels) normally represents this layout. It is convenient when an operation needs every channel of one pixel.
In a planar layout, all values for one channel are stored together:
R R R R ...
R R R R ...
G G G G ...
G G G G ...
B B B B ...
B B B B ...A planar array commonly has shape (channels, height, width). It can be efficient for operations that process one channel at a time.
| Layout | Typical shape | Useful when |
|---|---|---|
| Interleaved | `(height, width, channels)` | Reading or changing complete pixels |
| Planar | `(channels, height, width)` | Processing channels independently |
Shape, strides, and row padding
An array's stride is the number of bytes needed to move one step along an axis. For a contiguous uint8 RGB array with shape (2, 3, 3), the strides are (9, 3, 1):
- Move one row: 9 bytes.
- Move one pixel: 3 bytes.
- Move one channel: 1 byte.
import numpy as np
rgb = np.zeros((2, 3, 3), dtype=np.uint8)
print(rgb.shape) # (2, 3, 3)
print(rgb.strides) # (9, 3, 1)
planar = np.ascontiguousarray(rgb.transpose(2, 0, 1))
print(planar.shape) # (3, 2, 3)
print(planar.strides)A row may contain padding, also called a gap or pitch. Padding aligns rows for hardware or file-format requirements. Therefore, the distance between rows may be larger than width × channels × bytes_per_sample.
Channel order
RGB and BGR use the same three components but place them in a different order. If RGB data is passed to code expecting BGR, red and blue appear swapped.
bgr_view = rgb[..., ::-1]
bgr = np.ascontiguousarray(bgr_view)The first expression is a view with a reversed channel stride. The second creates a conventional contiguous copy, which some APIs require.
Exercise
An 8-bit image has shape (480, 640, 4). What does the last dimension represent, and how many bytes does one tightly packed row contain?
Show answer
The last dimension contains four one-byte channels, such as RGBA. One row contains 640 × 4 = 2,560 bytes, excluding any padding.