Sub topic 4
BGR, RGB, and grayscale
This chapter assumes you can load an image with cv2.imread, that you know an OpenCV image is a NumPy array with shape (height, width, channels), and that you are comfortable with NumPy slicing. Here you will learn why channel order causes silent bugs, how to convert between color spaces with cv2.cvtColor, and how the grayscale conversion works.
Why channel order matters
A color image stores three numbers per pixel, one per channel. A channel is one color component, such as the amount of red. The libraries you will combine with OpenCV disagree about the order of those numbers:
| Library or format | Channel order |
|---|---|
| OpenCV (`cv2.imread`, `cv2.imshow`, `cv2.imwrite`) | Blue, green, red (BGR) |
| Matplotlib, Pillow, most deep learning frameworks | Red, green, blue (RGB) |
The data type, uint8, and the shape, (height, width, 3), are identical in both cases. Because nothing in the array says which order it uses, a wrong order raises no error. The picture just looks wrong: skin turns blue, skies turn orange, and a model fed the wrong order gives worse predictions without any warning.
OpenCV is consistent with itself. imread, imshow, and imwrite all assume BGR, so the colors are right as long as you stay inside OpenCV. The problem starts when an array crosses a boundary into another library.
Converting with cv2.cvtColor
cv2.cvtColor(src, code) returns a new array in the requested color space. The code names the source and the destination, such as cv2.COLOR_BGR2RGB.
import cv2
img = cv2.imread("photo.jpg")
if img is None:
raise FileNotFoundError("Could not read photo.jpg")
rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
print("bgr :", img.shape, img.dtype)
print("rgb :", rgb.shape, rgb.dtype)
print("gray:", gray.shape, gray.dtype)
b, g, r = img[0, 0]
print("same pixel in RGB:", rgb[0, 0], "equals", (r, g, b))The output for a 640x480 photo would be:
bgr : (480, 640, 3) uint8
rgb : (480, 640, 3) uint8
gray: (480, 640) uint8
same pixel in RGB: [ 12 40 200] equals (12, 40, 200)Three details are worth noting:
cvtColornever modifies its input.imgis still BGR afterward. Keeping the two variables named differently (imgandrgb) tells you which order each array has.- The grayscale result has no channel axis. Its shape is
(height, width), not(height, width, 1). - The conversion copies the data, so
rgbis independent ofimg.
The usual symptom: wrong colors in Matplotlib
Matplotlib expects RGB. If you pass it a BGR array, red and blue swap. The fix is one conversion at the boundary.
import cv2
import matplotlib.pyplot as plt
img = cv2.imread("photo.jpg")
if img is None:
raise FileNotFoundError("Could not read photo.jpg")
fig, axes = plt.subplots(1, 3, figsize=(12, 4))
axes[0].imshow(img) # wrong: BGR data interpreted as RGB
axes[0].set_title("BGR passed directly")
axes[1].imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) # correct
axes[1].set_title("Converted to RGB")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
axes[2].imshow(gray, cmap="gray") # a 2D array needs a colormap
axes[2].set_title("Grayscale")
for ax in axes:
ax.axis("off")
plt.show()The third panel shows a second gotcha. When Matplotlib receives a 2D array, it maps values to colors with a colormap. The default colormap is not gray, so without cmap="gray" your grayscale image appears in green and yellow tones. That is false color, not a bug in the data.
How the grayscale conversion works
Converting to grayscale reduces three numbers per pixel to one brightness value. COLOR_BGR2GRAY does not take a plain average. It uses a weighted sum that matches how human vision responds to color, where green contributes most and blue least:
gray = 0.299 * R + 0.587 * G + 0.114 * B
You can check this against NumPy.
import cv2
import numpy as np
img = cv2.imread("photo.jpg")
if img is None:
raise FileNotFoundError("Could not read photo.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
b = img[:, :, 0].astype(np.float64)
g = img[:, :, 1].astype(np.float64)
r = img[:, :, 2].astype(np.float64)
manual = 0.299 * r + 0.587 * g + 0.114 * b
max_diff = np.abs(manual - gray.astype(np.float64)).max()
print("largest difference:", max_diff)
print("within rounding:", max_diff <= 1.0)
mean_gray = img.mean(axis=2)
print("plain average differs by up to:", np.abs(mean_gray - gray).max())The largest difference between your formula and OpenCV is at most 1, because OpenCV rounds to whole uint8 values. The plain average can differ from the weighted result by a large amount. A pure green pixel (0, 255, 0) becomes about 150 with the weighted formula and 85 with the average.
The cast to float64 matters. With uint8 arrays, img[:, :, 0] * 0.299 is fine, but adding or multiplying integer arrays can wrap around at 255. Convert before you do arithmetic on pixel values.
Reading directly as grayscale
If you only need grayscale, you can ask imread to convert while loading:
import cv2
gray = cv2.imread("photo.jpg", cv2.IMREAD_GRAYSCALE)
if gray is None:
raise FileNotFoundError("Could not read photo.jpg")
print(gray.shape) # (height, width)This skips the intermediate color array and uses less memory. The result can differ slightly from cvtColor on a loaded image, because the decoder may do the conversion internally. Choose one approach and use it consistently if you compare results across runs.
Going back from grayscale
Grayscale discards color, and no function can bring it back. What you can do is change the layout. cv2.COLOR_GRAY2BGR copies the single channel into all three, which gives a (height, width, 3) array that still looks gray. You need this whenever you want to draw colored annotations on a grayscale image, because drawing with a color tuple like (0, 0, 255) on a 2D array only uses the first value as brightness.
import cv2
gray = cv2.imread("photo.jpg", cv2.IMREAD_GRAYSCALE)
if gray is None:
raise FileNotFoundError("Could not read photo.jpg")
canvas = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)
cv2.rectangle(canvas, (50, 50), (250, 200), (0, 0, 255), 2) # red in BGR
print(canvas.shape) # (height, width, 3)
cv2.imwrite("gray_with_red_box.png", canvas)Common errors and edge cases
- Converting twice. Calling
cv2.cvtColor(gray, cv2.COLOR_BGR2GRAY)on an array that is already 2D raises acv2.errorabout the number of channels, because the code expects three. Checkimg.ndimorimg.shapeif you are unsure what you hold. - Converting a
None. Ifimreadfailed and you skipped the check,cvtColorraises a confusing error about an empty source. Check forNoneright after loading. - Images with transparency.
cv2.imread("logo.png")drops the alpha channel by default. Withcv2.IMREAD_UNCHANGEDyou get four channels in BGRA order, andcv2.COLOR_BGRA2BGRremoves the alpha channel again. Passing a 4-channel array toCOLOR_BGR2GRAYfails; useCOLOR_BGRA2GRAY. - Float images.
cvtColoracceptsuint8,uint16, andfloat32. Forfloat32, OpenCV assumes values in the range 0 to 1 and does not rescale them. If you normalized an image by dividing by 255, convert the color order after that without multiplying by 255 again. - Channel flipping with slicing.
img[:, :, ::-1]also reverses the channels and is a valid NumPy idiom, but it returns a view with a negative stride. Some OpenCV functions, including drawing functions, reject such an array with a layout error. Wrap it withnp.ascontiguousarray(img[:, :, ::-1]), or usecvtColor, which always returns a standard array.
Decision guide
| Situation | Choice |
|---|---|
| Showing an OpenCV array with Matplotlib | `COLOR_BGR2RGB` before `imshow` |
| Passing an array to a model that expects RGB | `COLOR_BGR2RGB` once, at the input |
| Saving an array from Pillow or Matplotlib with OpenCV | `COLOR_RGB2BGR` before `cv2.imwrite` |
| Algorithms that need brightness only | `COLOR_BGR2GRAY`, or `IMREAD_GRAYSCALE` at load time |
| Drawing colored shapes on a gray image | `COLOR_GRAY2BGR` first, then draw |
Exercise
You load photo.jpg with cv2.imread, then run gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) and rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB). What are the shapes of img, gray, and rgb for a 480-row, 640-column image, and is img changed by either call?
Show answer
img is (480, 640, 3), rgb is (480, 640, 3), and gray is (480, 640) with no channel axis. Neither call changes img, because cvtColor returns a new array.
Exercise
A colleague loads an image with OpenCV, draws a pure red rectangle using the color (255, 0, 0), and shows the result with Matplotlib's imshow without any conversion. What color do they see, and why? Which single change makes the rectangle red in the Matplotlib window?
Show answer
They see a red rectangle only by accident of two mistakes canceling. In OpenCV (255, 0, 0) is blue, so the rectangle is blue in the array. Matplotlib reads the channels as RGB, so it displays that first channel value as red, but the rest of the photo is displayed with red and blue swapped. Correct code draws red as (0, 0, 255) in BGR and then converts the whole array with cv2.cvtColor(img, cv2.COLOR_BGR2RGB) before calling imshow, so both the photo and the rectangle have the right colors.
Exercise
Why does cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) give a different result from img.mean(axis=2) for a pure green pixel (0, 255, 0), and roughly what value does each give?
Show answer
OpenCV uses the weighted sum 0.299 R + 0.587 G + 0.114 B, which weights green most heavily, so the pixel becomes about 150. The plain mean gives 255 / 3 = 85.