Pixels and Colour Spaces: RGB, BGR, Grey, HSV and Lab
A colour pixel is three numbers, but which three depends on the colour space. RGB says how much red, green and blue light to mix; it is what cameras and screens use, and it mixes up two things a vision system usually wants apart: what colour something is and how brightly it is lit. A red ball in the shade has a lower R value than the same ball in the sun, so a rule like "R > 150" finds it in one and loses it in the other. Other colour spaces separate brightness from colour (HSV, YCrCb, Lab) or make distances match what people perceive (Lab). This lesson converts between them, checks the formulas against OpenCV and scikit-image, and builds a colour segmenter that survives uneven light.
RGB and BGR
Both store the same three primaries; only the order of the last axis differs. scikit-image, Matplotlib, Pillow and PyTorch models use RGB, OpenCV's imread, imdecode and its drawing colours use BGR. Preparing image data shows the classic bug (a model fed BGR quietly gets worse). In this course every conversion names its direction: cv2.cvtColor(img, cv2.COLOR_RGB2HSV) for scikit-image images, COLOR_BGR2… for images decoded by OpenCV. OpenCV cannot tell which order an array is in; only the flag says.
Grey: a weighted sum, and two sets of weights
The eye is most sensitive to green and least to blue, so a grey value (luma) weights the channels unequally. OpenCV uses the ITU-R BT.601 weights from analogue television, scikit-image's rgb2gray the BT.709 weights of HDTV:
Both weight vectors sum to 1, so grey pixels stay the same; coloured pixels do not.
import numpy as np
import cv2
from skimage import data, color
cv2.setLogLevel(0)
rgb = data.astronaut()
g_cv = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY) # uint8, BT.601
g_np = np.rint(rgb @ np.array([0.299, 0.587, 0.114])).astype(np.uint8)
g_sk = color.rgb2gray(rgb) # float 0..1, BT.709
print("OpenCV vs 0.299 R + 0.587 G + 0.114 B: max diff", int(np.abs(g_cv.astype(int) - g_np).max()))
print("skimage rgb2gray:", g_sk.dtype, "range", round(float(g_sk.min()), 3), "to", round(float(g_sk.max()), 3))
d = np.abs(g_cv - g_sk * 255)
print(f"OpenCV vs skimage x 255: mean diff {d.mean():.2f}, max {d.max():.1f}")
for name, px in [("red", [255, 0, 0]), ("green", [0, 255, 0]), ("blue", [0, 0, 255])]:
p = np.uint8([[px]])
print(f"pure {name:5s}: OpenCV {int(cv2.cvtColor(p, cv2.COLOR_RGB2GRAY)[0, 0]):3d}, skimage {float(color.rgb2gray(p)[0, 0]) * 255:5.1f}")
wrong = cv2.cvtColor(rgb, cv2.COLOR_BGR2GRAY) # wrong flag for an RGB image
print(f"BGR2GRAY applied to RGB: mean abs error {np.abs(wrong.astype(int) - g_cv).mean():.2f}, max {np.abs(wrong.astype(int) - g_cv).max()}")OpenCV vs 0.299 R + 0.587 G + 0.114 B: max diff 1
skimage rgb2gray: float64 range 0.0 to 1.0
OpenCV vs skimage x 255: mean diff 2.76, max 15.5
pure red : OpenCV 76, skimage 54.2
pure green: OpenCV 150, skimage 182.4
pure blue : OpenCV 29, skimage 18.4
BGR2GRAY applied to RGB: mean abs error 8.86, max 35
The from-scratch formula matches OpenCV up to 1 level (OpenCV computes in fixed-point integers and rounds differently). The two libraries disagree by 2.76 levels on average and up to 15.5 on saturated colours: pure green is 150 in one and 182 in the other. Neither is wrong, but a model trained on one grey conversion and deployed with the other sees a small, systematic shift. The wrong flag (BGR2GRAY on an RGB image) swaps the red and blue weights and is off by up to 35 levels, enough to change a threshold decision.
HSV: hue, saturation, value
HSV describes a colour by its hue (the angle on a colour wheel: red, yellow, green, …), its saturation (how far from grey) and its value (the brightness of the strongest channel). With in , , and :
with when (greys have no hue). Scaling all three channels by the same factor (shade) changes but leaves and unchanged: that is the property that makes HSV useful for segmenting by colour.
Degrees go from 0 to 360, which does not fit in a byte, so for uint8 images OpenCV stores (0–179) and scales and to 0–255. (Float images keep degrees; COLOR_RGB2HSV_FULL maps the circle to 0–255 instead.) The from-scratch version, checked against OpenCV:
import numpy as np
import cv2
cv2.setLogLevel(0)
def rgb_to_hsv(rgb):
"""rgb: floats in 0..1, shape (..., 3). Returns H in degrees, S and V in 0..1."""
r, g, b = rgb[..., 0], rgb[..., 1], rgb[..., 2]
v = rgb.max(-1); d = v - rgb.min(-1)
s = np.where(v > 0, d / np.where(v > 0, v, 1), 0.0)
dd = np.where(d > 0, d, 1)
h = np.where(v == r, (g - b) / dd % 6, np.where(v == g, (b - r) / dd + 2, (r - g) / dd + 4)) * 60
return np.where(d > 0, h, 0.0), s, v
colours = {"red": [255, 0, 0], "orange": [255, 128, 0], "yellow": [255, 255, 0], "green": [0, 255, 0],
"cyan": [0, 255, 255], "blue": [0, 0, 255], "magenta": [255, 0, 255], "crimson": [220, 20, 60],
"dark red": [120, 0, 0], "grey": [128, 128, 128]}
arr = np.array(list(colours.values()), np.float64) / 255
h, s, v = rgb_to_hsv(arr)
cvh = cv2.cvtColor(np.uint8([list(colours.values())]), cv2.COLOR_RGB2HSV)[0]
print("colour scratch: H deg S V | OpenCV: H S V")
for i, name in enumerate(colours):
print(f"{name:9s} {h[i]:12.1f} {s[i]:5.2f} {v[i]:5.2f} | {cvh[i, 0]:8d} {cvh[i, 1]:3d} {cvh[i, 2]:3d}")
hues = np.array([2, 178]) # two reds, OpenCV units
print("naive mean of OpenCV hues 2 and 178:", hues.mean())
ang = np.deg2rad(hues * 2.0)
m = np.rad2deg(np.arctan2(np.sin(ang).mean(), np.cos(ang).mean())) % 360 / 2
print("circular mean:", round(float(m), 1))
def hue_dist(a, b):
d = np.abs(a - b) % 180
return np.minimum(d, 180 - d)
print("hue distance 2 vs 178:", int(hue_dist(2, 178)), "| 10 vs 60:", int(hue_dist(10, 60)))colour scratch: H deg S V | OpenCV: H S V
red 0.0 1.00 1.00 | 0 255 255
orange 30.1 1.00 1.00 | 15 255 255
yellow 60.0 1.00 1.00 | 30 255 255
green 120.0 1.00 1.00 | 60 255 255
cyan 180.0 1.00 1.00 | 90 255 255
blue 240.0 1.00 1.00 | 120 255 255
magenta 300.0 1.00 1.00 | 150 255 255
crimson 348.0 0.91 0.86 | 174 232 220
dark red 0.0 1.00 0.47 | 0 255 120
grey 0.0 0.00 0.50 | 0 0 128
naive mean of OpenCV hues 2 and 178: 90.0
circular mean: 180.0
hue distance 2 vs 178: 4 | 10 vs 60: 50
Dark red and red share hue 0 and saturation 1; only differs (0.47 against 1.00), as the formula promised. Crimson sits at 348 degrees, OpenCV hue 174, on the other side of the wrap-around from red. That wrap is the classic HSV bug: the mean of hues 2 and 178 is 90 (cyan!), while the circular mean (average the unit vectors, take the angle) gives 180, which is the same as 0: red. Distances between hues must also wrap: 2 and 178 are 4 apart. Grey has hue 0 by convention but saturation 0, which is why every hue rule needs a saturation floor: near-grey pixels have a random, noise-driven hue.
Lab: distances that match perception
Equal steps in RGB are not equal steps for the eye. CIELAB (Lab) was designed so that Euclidean distance approximates perceived difference: is lightness (0 black to 100 white), runs green (negative) to red (positive), blue to yellow. The simplest colour difference is Delta E 1976:
A of about 2 is a just-noticeable difference for most observers; later formulas (CIE94, CIEDE2000) correct its known errors in blues and saturated colours. The conversion goes through linear light and the CIE XYZ space, with a reference white (D65 for sRGB).
import numpy as np
import cv2
from skimage import color
cv2.setLogLevel(0)
pairs = {"two greens": ([0, 150, 0], [0, 170, 0]), "two blues": ([0, 0, 150], [0, 0, 170]),
"dark greys": ([20, 20, 20], [40, 40, 40]), "light greys": ([200, 200, 200], [220, 220, 220]),
"two yellows": ([200, 200, 0], [220, 220, 0])}
for name, (a, b) in pairs.items():
la = color.rgb2lab(np.uint8([[a]]))[0, 0]; lb = color.rgb2lab(np.uint8([[b]]))[0, 0]
rgb_d = float(np.linalg.norm(np.subtract(a, b, dtype=float)))
print(f"{name:11s} RGB distance {rgb_d:5.1f} | Lab {la.round(1).tolist()} -> {lb.round(1).tolist()} | Delta E 76 {float(color.deltaE_cie76(la, lb)):5.1f}")
red = np.uint8([[[255, 0, 0]]])
print("skimage Lab of red:", color.rgb2lab(red)[0, 0].round(1).tolist())
print("OpenCV Lab of red (uint8):", cv2.cvtColor(red, cv2.COLOR_RGB2LAB)[0, 0].tolist())
print("OpenCV Lab float32:", [round(float(v), 1) for v in cv2.cvtColor(red.astype(np.float32) / 255, cv2.COLOR_RGB2LAB)[0, 0]])
for name, px in [("red", [255, 0, 0]), ("skin-ish", [220, 170, 140]), ("blue", [0, 0, 255]), ("grey", [128, 128, 128])]:
print(f"YCrCb of {name:8s}:", cv2.cvtColor(np.uint8([[px]]), cv2.COLOR_RGB2YCrCb)[0, 0].tolist())two greens RGB distance 20.0 | Lab [53.8, -58.0, 56.0] -> [60.6, -63.6, 61.4] | Delta E 76 10.3
two blues RGB distance 20.0 | Lab [16.5, 53.3, -72.6] -> [19.6, 58.4, -79.6] | Delta E 76 9.2
dark greys RGB distance 34.6 | Lab [6.3, -0.0, 0.0] -> [16.1, -0.0, 0.0] | Delta E 76 9.8
light greys RGB distance 34.6 | Lab [80.6, -0.0, 0.0] -> [87.8, -0.0, 0.0] | Delta E 76 7.2
two yellows RGB distance 28.3 | Lab [78.2, -18.0, 78.7] -> [85.2, -19.3, 84.5] | Delta E 76 9.2
skimage Lab of red: [53.2, 80.1, 67.2]
OpenCV Lab of red (uint8): [136, 208, 195]
OpenCV Lab float32: [53.2, 80.1, 67.2]
YCrCb of red : [76, 255, 85]
YCrCb of skin-ish: [182, 155, 104]
YCrCb of blue : [29, 107, 255]
YCrCb of grey : [128, 128, 128]
The same RGB distance of 34.6 between two greys is in the dark and 7.2 in the light: the eye separates dark shades better than RGB suggests. For Lab, too, OpenCV packs uint8 images: , , (136, 208, 195 for red), while float input gives the real units, identical to scikit-image. Mixing the two scales is another silent bug.
YCrCb (the space of JPEG and video) is luma plus two colour-difference channels, and ; its is exactly the BT.601 grey (76 for red, as above), and greys sit at . Classic skin detectors threshold and ; they work poorly across skin tones and lighting, one of several reasons they were replaced by learned detectors (face detection).
Segmenting by colour
A colour threshold keeps the pixels whose colour lies in a box of the chosen space. To test RGB against HSV fairly, the next example draws a scene with a known answer: three red discs and one orange distractor on a green-grey background, lit by a light that fades from full strength on the left to a quarter on the right, plus sensor noise. The ground-truth mask is known, so each rule gets an IoU (intersection over union of predicted and true pixels).
import numpy as np
import cv2
cv2.setLogLevel(0)
rng = np.random.default_rng(0)
h, w = 120, 320
img = np.empty((h, w, 3)); img[:] = (100, 120, 100) # background, RGB
truth = np.zeros((h, w), np.uint8)
for x in [50, 150, 270]: # three red discs
cv2.circle(truth, (x, 60), 28, 1, -1)
img[truth > 0] = (200, 30, 40)
orange = np.zeros((h, w), np.uint8); cv2.circle(orange, (210, 60), 22, 1, -1)
img[orange > 0] = (220, 120, 30) # a distractor
light = np.linspace(1.0, 0.25, w)[None, :, None] # bright left, dim right
img = (img * light + rng.normal(0, 4, img.shape)).clip(0, 255).astype(np.uint8)
def iou(pred, true):
return (pred & true).sum() / (pred | true).sum()
t = truth > 0
rgb_rule = (img[..., 0] > 150) & (img[..., 1] < 80) & (img[..., 2] < 80)
hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)
H, S, V = hsv[..., 0], hsv[..., 1], hsv[..., 2]
hsv_rule = ((H <= 8) | (H >= 172)) & (S >= 120) & (V >= 40)
for name, pred in [("RGB box R>150, G<80, B<80", rgb_rule), ("HSV hue red, S>=120, V>=40", hsv_rule)]:
per_disc = [round(float(pred[:, x - 30:x + 30][t[:, x - 30:x + 30]].mean()), 2) for x in [50, 150, 270]]
print(f"{name:27s} IoU {iou(pred, t):.3f} | share of each disc found {per_disc} | orange pixels taken {int((pred & (orange > 0)).sum())}")
for x in [50, 150, 270]:
print(f"disc at x={x:3d}: light {float(light[0, x, 0]):.2f}, median RGB {np.median(img[t & (np.arange(w) // 60 == x // 60)[None, :]], axis=0).astype(int).tolist()}, "
f"median H S V {np.median(hsv[t & (np.arange(w) // 60 == x // 60)[None, :]], axis=0).astype(int).tolist()}")RGB box R>150, G<80, B<80 IoU 0.334 | share of each disc found [1.0, 0.0, 0.0] | orange pixels taken 0
HSV hue red, S>=120, V>=40 IoU 0.998 | share of each disc found [1.0, 1.0, 0.99] | orange pixels taken 0
disc at x= 50: light 0.88, median RGB [179, 27, 36], median H S V [178, 217, 179]
disc at x=150: light 0.65, median RGB [129, 19, 25], median H S V [178, 218, 129]
disc at x=270: light 0.37, median RGB [72, 10, 14], median H S V [176, 221, 72]
The RGB box finds all of the brightly lit disc and none of the other two (IoU 0.334): at 65 % light the disc's median red value is 129, below the 150 the rule was tuned on. The HSV rule finds 100 %, 100 % and 99 % of the three discs (IoU 0.998), because the hue stays at 176–178 and the saturation at about 220 while only drops, from 179 to 72, exactly as the formula promised. Neither rule takes the orange disc: its hue is outside the red interval, which is the other job of hue.
Now a real photo. scikit-image's coffee image shows a red cup and saucer on a wooden table. The from-scratch mask (NumPy comparisons on the HSV array) is checked against cv2.inRange, which takes a lower and an upper corner of the box and needs two calls for red:
import numpy as np
import cv2
from skimage import data
cv2.setLogLevel(0)
rgb = data.coffee() # (400, 600, 3) RGB
hsv = cv2.cvtColor(rgb, cv2.COLOR_RGB2HSV)
H, S, V = (hsv[..., i].astype(int) for i in range(3))
ours = ((H <= 8) | (H >= 170)) & (S >= 100) & (V >= 60)
lib = cv2.inRange(hsv, (0, 100, 60), (8, 255, 255)) | cv2.inRange(hsv, (170, 100, 60), (179, 255, 255))
print("from scratch == cv2.inRange:", np.array_equal(ours, lib > 0), "| share of red pixels:", round(float(ours.mean()), 3))
n, labels, stats, centroids = cv2.connectedComponentsWithStats(lib, connectivity=8)
big = 1 + int(np.argmax(stats[1:, cv2.CC_STAT_AREA]))
x, y, w, h, area = stats[big].tolist()
print(f"{n - 1} red regions; the largest: {area} pixels, box [x1, y1, x2, y2] = {[x, y, x + w, y + h]}")
print("hue upper limit -> share of red pixels (the wooden table is orange, hue 10 to 25):")
for upper in [4, 6, 8, 10, 12, 15]:
m = ((H <= upper) | (H >= 170)) & (S >= 100) & (V >= 60)
print(f" H <= {upper:2d}: {m.mean():.3f}")from scratch == cv2.inRange: True | share of red pixels: 0.26
793 red regions; the largest: 56385 pixels, box [x1, y1, x2, y2] = [73, 66, 491, 400]
hue upper limit -> share of red pixels (the wooden table is orange, hue 10 to 25):
H <= 4: 0.079
H <= 6: 0.213
H <= 8: 0.260
H <= 10: 0.380
H <= 12: 0.617
H <= 15: 0.755
Our NumPy comparisons and cv2.inRange agree pixel for pixel, and 26 % of the photo counts as red. Two lessons follow. First, the answer hangs on a hand-set boundary: the red cup and the orange-brown table are only a few hue units apart, and moving the upper limit from 4 to 15 changes the red share from 7.9 % to 75.5 % of the image (at 12 most of the table is already "red"). Second, even a reasonable mask is a set of pixels, not an object: at the limit 8 it falls apart into 793 separate regions, and the largest one, 56,385 pixels with the box [73, 66, 491, 400], runs down to the bottom edge of the image: it is most likely the cup merged with its saucer, not the cup alone. Morphology and connected components turn it into clean regions with boxes. When colour does not separate the object from its background, as with most real classes, you need a learned model: semantic segmentation.
Which space for what
| Space | Channels | Use it for |
|---|---|---|
| RGB / BGR | red, green, blue | storage, display, input to CNNs (pretrained models expect RGB) |
| grey | luma | edges, corners, thresholds, Haar and HOG features, anything that ignores colour |
| HSV / HSL | hue, saturation, brightness | colour thresholds that tolerate shading; hue histograms |
| Lab | lightness, green-red, blue-yellow | perceptual colour distance, colour transfer, white-balance checks |
| YCrCb / YUV | luma, two chroma channels | video and JPEG (chroma is stored at lower resolution), simple skin and chroma keys |
Pitfalls
- Wrong conversion flag.
COLOR_BGR2…on an RGB array (or the reverse) silently swaps red and blue. Know where each array came from. - Different grey formulas. OpenCV (BT.601) and scikit-image (BT.709) differ by up to 15.5 levels on saturated colours; keep one conversion from training to production.
- Hue wrap-around. Red needs two intervals, hue means and distances must be circular, and greys have meaningless hue: always add a saturation floor.
- Packed 8-bit ranges. OpenCV stores hue as degrees / 2 and Lab with offsets for
uint8images. Thresholds copied from another tool (which uses 0–360 and 0–100) are wrong by those factors. - Lighting colour. HSV handles brighter and darker light, not a change of light colour (sunlight versus tungsten shifts the hue). White balance or colour constancy (person re-identification uses the grey-world method) comes first.
Practice
- Convert RGB (0, 128, 255) to HSV in degrees by hand, then to OpenCV's 8-bit units.
Answer
In 0–1 units: , , . , , . , so . OpenCV: , , .
- You want all pixels whose hue is within 10 degrees of 355 degrees. Write the condition in OpenCV hue units.
Answer
355 degrees is OpenCV hue 177.5; 10 degrees is 5 units. The interval 172.5 to 182.5 wraps past 179, so use two intervals: (H >= 173) | (H <= 2) (rounded to integer hues), plus a saturation floor.
- Two colours are apart. Two others differ by 20 in each RGB channel. Which pair is more likely to look different to a person?
Answer
Most likely the second: around 2 is a just-noticeable difference, so 1.5 is hard to see, while the grey pairs in the lesson that differed by 20 per channel (34.6 in RGB distance) were 7 to 10 apart. RGB distance itself does not say how visible a difference is; convert to Lab to judge it.
Test yourself
Why does a hue threshold find a red object in the shade when an RGB threshold does not?
- HSV images are brighter
- Shading scales R, G and B by the same factor, which changes V but not H or S
- OpenCV corrects the lighting during the conversion
- Hue is measured in degrees
In OpenCV, an 8-bit image has a pixel with hue 178. Which colour family is it?
- Cyan
- Blue
- Red (just before the wrap-around to 0)
- Green
cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY) and skimage.color.rgb2gray(rgb) * 255 give different values for pure green (150 against about 182). Why?
- One of them has a bug
- They use different luma weights: BT.601 (0.587 for G) and BT.709 (0.7154 for G)
- skimage works in BGR
- OpenCV gamma-corrects the image
What does measure?
- The Euclidean distance between two colours in RGB
- The Euclidean distance in CIELAB, designed to approximate perceived colour difference
- The difference in hue only
- The brightness difference in decibels