Sub topic 10
RGB versus BGR and Other Channel Orders
This chapter assumes you know basic Python and arrays, including shapes, indexing, and bytes. You should also know that an image can have height, width, and several channel values per pixel.
What channel order means
A colour image commonly stores three samples per pixel. In an RGB image, those samples appear as red, green, and blue:
[R, G, B]For example, [255, 0, 0] means full red when the values use 8-bit RGB. The same three numbers interpreted as BGR mean blue, because the first position represents blue:
RGB: [255, 0, 0] -> red
BGR: [255, 0, 0] -> blueThe array shape often does not reveal the order. Both formats usually have shape (height, width, 3). The order is a convention defined by the library, file format, or device.
Interleaved and planar layouts
In an interleaved, or packed, layout, each pixel's channels are adjacent:
R0 G0 B0 R1 G1 B1 R2 G2 B2A height-width-channel array usually represents this arrangement. In a planar layout, all red samples come first, followed by all green samples and then all blue samples:
RRRR... GGGG... BBBB...The array shape for a planar image is often (channels, height, width). Shape alone still cannot prove the physical layout. Strides describe how many bytes the program moves when an index changes.
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)
bgr_view = rgb[..., ::-1]
print(bgr_view.shape) # (2, 3, 3)For rgb, moving one row advances 9 bytes, moving one pixel advances 3 bytes, and moving one channel advances 1 byte. The reversed view changes the interpretation order without necessarily copying the data. Some APIs require a contiguous array, so make a copy when needed.
Other channel orders
Common arrangements include:
| Order | Meaning | Typical context |
|---|---|---|
| RGB | Red, green, blue | Web images and many imaging libraries |
| BGR | Blue, green, red | Some computer-vision APIs |
| RGBA | RGB plus alpha | Images with transparency |
| BGRA | BGR plus alpha | Some camera and graphics APIs |
Alpha usually describes opacity: zero means transparent and the maximum value means opaque. It is not a colour channel, but it affects how the pixel is displayed.
When moving data between APIs, check the documentation and test with a deliberately coloured sample. A pixel containing pure red, pure green, and pure blue makes swaps easy to detect.
Exercise
An array has shape (480, 640, 3), and a library documents its input as BGR. Which array value represents pure red?
Show answer
In BGR order, pure red is [0, 0, 255].