Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 54 ยท Pixels and Color

Color Spaces: BGR, RGB, Gray and HSV

Understand OpenCV's BGR channel order, convert with cvtColor, learn the grayscale formula and HSV hue, then rebuild gray and BGR-to-RGB with NumPy.

A color space is a way of describing a color with numbers. Your screen mixes red, green and blue light, so RGB is the natural choice. But OpenCV stores channels in the order blue, green, red (BGR), a historical quirk, and many tasks are easier in other spaces: grayscale for brightness-only work and HSV for picking colors by their hue.

This lesson covers the four spaces you will use most, how cv2.cvtColor converts between them, and how to reproduce the key conversions with plain NumPy so nothing is magic. It builds on Images Are NumPy Arrays.

The BGR pitfall

When OpenCV loads a photo, the last axis holds blue first. A pure red pixel is therefore (0, 0, 255), not (255, 0, 0).

Python
import cv2

img = cv2.imread("photo.jpg")
b, g, r = img[0, 0]            # note the order
print(b, g, r)

Other libraries (matplotlib, Pillow, most web tools) use RGB. If you show an OpenCV image with matplotlib without converting, reds and blues swap and skin looks blue. The fix is one call:

Python
rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

Four spaces to know

BGR OpenCV's default channel order.
RGB What matplotlib and Pillow expect.
Gray One brightness value per pixel.
HSV Hue, saturation and value.

Convert at the edges; stay in BGR inside OpenCV.

1 / 2

Converting with cvtColor

cv2.cvtColor(img, code) returns a new array. The code names the direction:

Python
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)   # (H, W)
hsv  = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)    # (H, W, 3)
rgb  = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)    # (H, W, 3)
back = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)  # (H, W, 3), all channels equal

A common mistake is using a code that does not match the image's real space (for example COLOR_RGB2GRAY on a BGR image). It still runs, with slightly wrong brightness weights, so the bug is easy to miss. Name your variables img_bgr, img_rgb and so on to keep track.

Grayscale

A gray image keeps one number per pixel: its brightness. Because the eye is most sensitive to green and least to blue, the standard conversion is a weighted sum, not a plain average:

gray = 0.299 * R + 0.587 * G + 0.114 * B

OpenCV's COLOR_BGR2GRAY uses these weights (computed in fixed-point integer math and rounded). Many algorithms, such as edge detection and thresholding, only need brightness, and a single channel is also three times less data.

Python Grayscale from BGR with NumPy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Pure green becomes much brighter than pure blue (about 150 versus 29), which matches how bright they look. A plain average would give both the same 85. We convert to float32 first because multiplying uint8 values by decimals would otherwise overflow or truncate; see Data Types, Ranges and Saturation.

Why work in grayscale?

Converting to gray throws away color but keeps the brightness structure, which is what many algorithms need: edges, corners, thresholds and template matching all look at intensity differences. Gray images have one third of the data, so they are processed faster and use less memory, and they make algorithms less sensitive to color changes caused by lighting. Use the weighted formula above (what cv2.cvtColor does) rather than the plain average (B + G + R) / 3, because the eye is most sensitive to green, and the average makes a green object look too dark compared with a blue one. Keep the original color image for display and for any step that really depends on color, such as segmenting by hue.

BGR to RGB is just reversing the last axis

You do not need cvtColor to swap channel order. The channels are the last axis, so reversing it does the job. NumPy slicing [..., ::-1] means "everything, with the last axis reversed".

Python Swap BGR and RGB by slicing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The reversed array is a view onto the same memory with negative strides, so it costs nothing, but it can behave oddly when passed to some OpenCV functions that need contiguous memory. If you hit an error, wrap it with np.ascontiguousarray(bgr[..., ::-1]). Views and Copies explains why.

HSV: picking colors by hue

HSV describes a color as Hue (which color on the color wheel), Saturation (how vivid versus washed-out) and Value (how bright). It is better than RGB for tasks like "find all the green things", because a green keeps roughly the same hue in sun and in shade, while its RGB numbers change a lot.

OpenCV's 8-bit HSV uses unusual ranges, so memorize them:

Channel Range in OpenCV (uint8) Why
H 0 to 179 Hue is 0 to 360 degrees, halved to fit a byte
S 0 to 255 0 is gray, 255 is fully vivid
V 0 to 255 0 is black, 255 is brightest

So red is near hue 0 (and also near 179, because the wheel wraps), green near 60 and blue near 120. This is OpenCV-specific; other libraries often use 0 to 360 or 0 to 1. The standard library's colorsys uses 0 to 1 for all three, and we can scale its output to OpenCV's convention to preview what cvtColor would give for single pixels.

Python Hue of familiar colors (OpenCV scale)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that white has saturation 0 (its hue is meaningless) and that dark green keeps the same hue as bright green while only the value drops. That is exactly why HSV is good for color filtering, which you will do with inRange in Arithmetic, Bitwise Ops and Masking. This is a stand-in: colorsys rounds slightly differently from OpenCV's integer code, so real cvtColor values can differ by one.

Rule of thumb: stay in BGR inside OpenCV, convert to RGB only when handing pictures to other libraries, convert to gray when color does not matter, and convert to HSV when you select by color.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the BGR value of a pure red pixel in OpenCV?

    Channels are stored blue, green, red, so red is the last number: (0, 0, 255).
  2. 2. Why does the grayscale formula weight green more than blue?

    The 0.299, 0.587, 0.114 weights reflect how bright each primary appears to people.
  3. 3. In OpenCV's 8-bit HSV, what is the range of the H (hue) channel?

    Hue is halved from 0-360 degrees so it fits a uint8 without overflow.
  4. 4. What does bgr[..., ::-1] do?

    The ellipsis keeps the first axes and ::-1 reverses the last one (channels).

Summary

  • OpenCV stores color images as BGR; convert to RGB for matplotlib and similar libraries.
  • cv2.cvtColor converts between spaces; match the conversion code to the real source space.
  • Gray is a weighted sum (0.299 R + 0.587 G + 0.114 B); HSV in 8 bits has H 0 to 179, S and V 0 to 255.
  • HSV separates color from brightness, which makes color selection much easier.

Next, learn to read and change individual pixels: Accessing and Modifying Pixels.