Sub topic 10
RGB versus BGR and other channel orders
This chapter assumes you can read a NumPy array shape such as (height, width, channels) and that you know a pixel in an RGB image holds three 8-bit samples. It also assumes you have met the interleaved memory layout from the previous chapter. Here we look at one specific problem: the same array can mean different colours depending on the order of its channels, and nothing in the array tells you which order it uses.
Why channel order is a convention, not data
A channel is just a position along the last axis of the array. Position 0 is not "red" by nature. Red is the meaning a library assigns to position 0. Two libraries that store identical numbers in different orders will show different colours when one reads the other's data.
The most common mismatch is between two orders:
- RGB: position 0 is red, 1 is green, 2 is blue. Most image libraries, GPU frameworks, and deep-learning models use it. Pillow, scikit-image, Matplotlib, and torchvision all assume RGB.
- BGR: position 0 is blue, 1 is green, 2 is red. OpenCV uses it by default for reading, writing, and drawing. Some camera and Windows bitmap APIs also use it.
The BGR convention in OpenCV is historical. Early camera and Windows bitmap formats stored pixels in that order, and the library kept it for compatibility.
A pixel with the stored values (255, 0, 0) is pure red in RGB and pure blue in BGR. The array has the same shape, dtype, and byte count in both cases, so no error is raised. The only symptom is wrong colours.
What the error looks like
Swapping red and blue gives a recognisable look. Skin tones turn blue-grey, skies turn orange, and grass stays green, because green sits in the middle in both orders. If green looks right and the other two look swapped, suspect RGB/BGR first.
The table shows what a swap does to a few colours. Each row is the colour you intended, stored in RGB, then displayed by a viewer that assumes BGR.
| Intended colour | Stored as RGB | Shown by a BGR viewer as |
|---|---|---|
| Red | (255, 0, 0) | Blue |
| Green | (0, 255, 0) | Green |
| Blue | (0, 0, 255) | Red |
| Yellow | (255, 255, 0) | Cyan |
| Orange | (255, 128, 0) | Light blue |
Grey and white images are unaffected, because their three samples are equal. A swap bug can therefore pass unnoticed on a grayscale test image and appear only on a colour photograph.
Converting between orders
Reversing the last axis converts RGB to BGR and BGR to RGB. The operation is its own inverse.
import numpy as np
rgb = np.zeros((1, 3, 3), dtype=np.uint8)
rgb[0, 0] = (255, 0, 0) # red
rgb[0, 1] = (0, 255, 0) # green
rgb[0, 2] = (0, 0, 255) # blue
bgr = rgb[..., ::-1] # reverse the channel axis
print(bgr[0, 0]) # [ 0 0 255] (red, written in BGR order)
print(np.array_equal(bgr[..., ::-1], rgb)) # True: reversing twice restores it
print(bgr.flags["C_CONTIGUOUS"]) # False
print(bgr.strides) # (9, 3, -1)The slice [..., ::-1] does not copy any data. It returns a view with a negative stride of -1 on the channel axis, so the array is no longer C-contiguous. This matters in practice. Some libraries require contiguous memory and fail or silently copy when they receive a reversed view. OpenCV functions are a common example. They can raise an error such as a layout complaint when given a negative-stride array. The fix is to make a real copy.
import numpy as np
rgb = np.arange(2 * 3 * 3, dtype=np.uint8).reshape(2, 3, 3)
bgr_view = rgb[..., ::-1]
bgr = np.ascontiguousarray(bgr_view) # copy with a normal layout
print(bgr_view.flags["C_CONTIGUOUS"]) # False
print(bgr.flags["C_CONTIGUOUS"]) # True
print(bgr.strides) # (9, 3, 1)A view also shares memory with the original. If you write into bgr_view, you change rgb too. Use .copy() or np.ascontiguousarray when you need an independent array.
If you use OpenCV, cv2.cvtColor(img, cv2.COLOR_BGR2RGB) does the same swap and returns a contiguous array. Pillow's Image.split() and Image.merge() can reorder bands by name.
Where the mismatch usually happens
Bugs appear at the boundary between two libraries. These are the typical cases:
- Read with OpenCV, display with Matplotlib.
cv2.imreadreturns BGR.plt.imshowassumes RGB, so the picture looks blue-tinted. - Read with Pillow, write with OpenCV. Pillow gives RGB.
cv2.imwriteexpects BGR, so the saved file has red and blue swapped. - Feed an OpenCV image to a trained model. Most pretrained vision models were trained on RGB data. A BGR input still runs, but accuracy drops, because the model sees colours it was not trained on. Nothing crashes. This is the most expensive version of the bug, since it shows up only as worse results.
- Drawing colours. In OpenCV,
(255, 0, 0)draws blue. Code copied from an RGB tool gives the wrong colour.
The safest habit is to convert once, at the point where data enters your own code, and to document the order in the name or comments of the variable. Names such as img_rgb and img_bgr cost nothing and prevent most mistakes.
Other channel orders
RGB and BGR are not the only orders, and a channel count of 4 adds more.
| Order | Channels | Where you meet it |
|---|---|---|
| RGB | 3 | Pillow, Matplotlib, most models |
| BGR | 3 | OpenCV, some Windows and camera APIs |
| RGBA | 4 | PNG, many web and graphics APIs |
| BGRA | 4 | OpenCV with alpha, Windows surfaces, some GPU swapchains |
| ARGB | 4 | Some Android and macOS pixel formats, 32-bit packed integers |
| Grayscale | 1 | Single-channel images |
With four channels, reversing the whole last axis is wrong. Reversing RGBA gives ABGR, not BGRA. To convert RGBA to BGRA you must keep alpha in place and swap only the first three channels. Use an explicit index list, which also makes the intent clear.
import numpy as np
rgba = np.zeros((1, 2, 4), dtype=np.uint8)
rgba[0, 0] = (255, 0, 0, 255) # opaque red
rgba[0, 1] = (0, 0, 255, 128) # half-transparent blue
bgra = rgba[..., [2, 1, 0, 3]] # fancy indexing: copies, keeps alpha last
print(bgra[0, 0]) # [ 0 0 255 255]
print(bgra[0, 1]) # [255 0 0 128]Indexing with a list is called fancy indexing. Unlike a slice, it returns a new contiguous array, so the negative-stride problem does not occur.
Packed formats add a second source of confusion. Order can be described by byte position in memory or by position inside a 32-bit integer. On a little-endian machine these two views are reversed. A format called "ARGB" in the integer sense is stored in memory as the bytes B, G, R, A. If a library's documentation names the order, check whether it means bytes in memory or bits in a word.
Planar layouts follow the same rule
In planar layouts the channels are separate planes, shaped (channels, height, width). Deep-learning frameworks commonly use this form. Channel order still applies, but you reorder along axis 0 instead of the last axis.
import numpy as np
chw = np.zeros((3, 2, 2), dtype=np.uint8)
chw[0] = 255 # first plane filled
swapped = chw[::-1] # reverse the channel axis (axis 0)
print(swapped[2].max()) # 255: the filled plane is now lastAlways check which axis holds the channels before you reorder. Reversing the wrong axis flips the image vertically or horizontally instead of swapping colours.
Detecting the order when nobody told you
An array carries no label for channel order, so you need a check. Three approaches work well:
- Read the documentation of the library that produced the array. This is the reliable answer.
- Use a known test image. Create or load a picture with a pure red region, then look at which index holds the large value at that location.
- Look at the result. Blue skin tones or orange skies point to a swap, but this is a clue, not proof.
A short check on a pixel you know to be red takes seconds:
import numpy as np
def dominant_channel_index(pixel):
return int(np.argmax(pixel))
red_pixel_from_unknown_source = np.array([10, 20, 240], dtype=np.uint8)
idx = dominant_channel_index(red_pixel_from_unknown_source)
print(idx) # 2 -> the red value is at index 2, so the order is BGRSummary of rules
- Channel order is a convention of the library, not a property stored in the array.
- A swapped order raises no error. It produces wrong colours or worse model accuracy.
- Reverse the last axis for 3-channel RGB and BGR. Use an index list when alpha is present.
- A reversed slice is a view with a negative stride. Copy it before passing it to code that needs contiguous memory.
- Convert once at the library boundary and name variables by order.
Exercise
You load a photo with OpenCV and call plt.imshow on the result. The grass looks normal but the sky is orange. Explain why, and give one line that fixes it. Then explain why bgra = rgba[..., ::-1] is the wrong way to convert an RGBA array to BGRA.
Show answer
OpenCV returns BGR, but Matplotlib assumes RGB, so red and blue are swapped. Green sits in the middle in both orders, so grass looks normal, while the blue sky is displayed through the red channel and looks orange. Fix it with img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) or img[..., ::-1] followed by np.ascontiguousarray. For RGBA, reversing the whole last axis gives ABGR, because alpha moves from the end to the start. Use rgba[..., [2, 1, 0, 3]] so alpha stays last.
Exercise
The array a = np.zeros((4, 4, 3), dtype=np.uint8) is converted with b = a[..., ::-1]. What are b.strides and b.flags["C_CONTIGUOUS"], and why might that cause a problem?
Show answer
The strides are (12, 3, -1) and C_CONTIGUOUS is False. The slice is a view with a negative step on the channel axis. Libraries that require contiguous memory, such as some OpenCV functions, may raise an error or copy silently. np.ascontiguousarray(b) produces a normal layout with strides (12, 3, 1).