Skip to content
Tactiverge

Colour spaces and thresholding

Separate an object from its background by brightness or by colour, and see why hue, saturation and value often work better than raw red, green and blue.

Lesson 2 of 6 · 35 min · Self-paced · Free

Why segmentation comes first

Suppose a robot must pick up a red block from a grey table. Before it can work out where the block is, it must decide which pixels belong to the block and which belong to the table. That job is called segmentation, and the simplest way to do it is thresholding: compare every pixel with a cut-off value and keep the ones on one side.

Thresholding is crude, but it is fast, easy to understand and surprisingly useful in controlled settings such as a factory line with fixed lighting. It is also the clearest way to see a lesson that runs through all of computer vision: a method that works perfectly on one image can fail on the next because the lighting changed.

Thresholding a greyscale image

Here is a small greyscale image of a bright object on a dark background. The function turns it into a binary mask: 1 where the pixel is brighter than the threshold, 0 elsewhere.

image = [
    [ 30,  35,  32,  40,  38,  33],
    [ 36, 180, 190,  41,  37,  35],
    [ 31, 185, 200, 195,  39,  34],
    [ 38, 176, 188, 192,  42,  36],
    [ 33,  37,  40,  36,  35,  31],
]

def threshold(img, t):
    return [[1 if v > t else 0 for v in row] for row in img]

mask = threshold(image, 100)
for row in mask:
    print(" ".join(str(v) for v in row))
print("Object pixels:", sum(sum(row) for row in mask))

Output:

0 0 0 0 0 0
0 1 1 0 0 0
0 1 1 1 0 0
0 1 1 1 0 0
0 0 0 0 0 0
Object pixels: 8

The mask is far simpler than the image: every pixel is now a yes or a no. The next lessons build on masks like this one to find where objects are and how big they are.

Choosing the threshold

Why 100? One good way to choose is to look at a histogram: a count of how many pixels fall into each range of brightness.

values = [30, 35, 32, 40, 38, 33, 36, 180, 190, 41, 37, 35,
          31, 185, 200, 195, 39, 34, 38, 176, 188, 192, 42, 36,
          33, 37, 40, 36, 35, 31]

bins = [0] * 8                 # eight bins, each 32 levels wide
for v in values:
    bins[v // 32] += 1
for i, count in enumerate(bins):
    print(f"{i * 32:3d}-{i * 32 + 31:3d} {'#' * count}")

Output:

  0- 31 ###
 32- 63 ###################
 64- 95
 96-127
128-159
160-191 #####
192-223 ###
224-255

The background forms one clump on the left and the object forms another on the right, with an empty gap between. Any threshold in the gap, from about 64 to 159, separates them perfectly, and 100 sits safely in the middle. Real images are messier: the clumps overlap, and there is no perfect threshold. Methods exist to pick a threshold automatically from the histogram (Otsu's method is a well-known one), but the idea is the same: find the valley between two peaks.

Why raw RGB struggles

Now consider colour. A red block on a table might give RGB values like (220, 40, 30) where it is lit, but only (90, 16, 12) on its shadowed side. A rule such as "red channel above 150" catches the lit side and misses the shadow completely, even though both are obviously the same red to a person. The trouble is that in RGB, colour and brightness are tangled together: when light dims, all three numbers fall at once.

HSV: separating colour from brightness

The HSV colour space describes each colour with three different numbers:

  • Hue (H): which colour it is, as an angle around a colour wheel from 0° to 360°. Red is near 0°, green near 120°, blue near 240°, and the wheel wraps back to red at 360°.
  • Saturation (S): how strong or pure the colour is, from 0 (grey) to 1 (vivid).
  • Value (V): how bright it is, from 0 (black) to 1 (brightest).

Python's standard library includes colorsys, which converts between RGB and HSV using values from 0 to 1:

import colorsys

def hsv(rgb):
    r, g, b = (v / 255 for v in rgb)
    h, s, v = colorsys.rgb_to_hsv(r, g, b)
    return round(h * 360), round(s, 2), round(v, 2)

red_in_light  = (220, 40, 30)
red_in_shadow = (90, 16, 12)
grey_card     = (120, 120, 120)

for name, px in [("red, lit", red_in_light),
                 ("red, shadow", red_in_shadow),
                 ("grey card", grey_card)]:
    print(f"{name:12s} RGB={px}  HSV={hsv(px)}")

Output:

red, lit     RGB=(220, 40, 30)  HSV=(3, 0.86, 0.86)
red, shadow  RGB=(90, 16, 12)  HSV=(3, 0.87, 0.35)
grey card    RGB=(120, 120, 120)  HSV=(0, 0.0, 0.47)

This is the key result. The lit and shadowed reds have the same hue (3°) and nearly the same saturation; only the value changed. The grey card's hue is meaningless (it prints 0), but its saturation of 0 tells you it has no colour at all.

Segmenting by colour

A colour rule in HSV can now ignore brightness, within limits:

import colorsys

def is_red(rgb):
    r, g, b = (v / 255 for v in rgb)
    h, s, v = colorsys.rgb_to_hsv(r, g, b)
    hue = h * 360
    red_hue = hue < 15 or hue > 345      # hue wraps around at 360°
    return red_hue and s > 0.5 and v > 0.2

pixels = [(220, 40, 30), (90, 16, 12), (120, 120, 120),
          (240, 200, 190), (200, 30, 60), (40, 8, 6)]
for px in pixels:
    print(px, is_red(px))

Output:

(220, 40, 30) True
(90, 16, 12) True
(120, 120, 120) False
(240, 200, 190) False
(200, 30, 60) True
(40, 8, 6) False

Each line of the rule has a reason. Red sits on both sides of 0°, so the hue test needs an or (the crimson (200, 30, 60) has a hue of about 349°). The saturation test rejects greys and pale pinks such as (240, 200, 190). The value test rejects pixels so dark that their hue is unreliable: (40, 8, 6) is technically reddish, but at that brightness a few units of sensor noise could swing its hue wildly. HSV does not make lighting problems disappear; it moves them into one number where you can deal with them.

Knowledge check

Check your understanding

  1. 1. A greyscale histogram has a peak around 40 and another around 190, with almost no pixels between 80 and 150. Which threshold is most sensible?
  2. 2. Why does a rule like "red channel above 150" often fail on shadowed parts of a red object?
  3. 3. In HSV, which number changes most when the same surface moves from bright light into shadow?
  4. 4. Why does the red detector test hue < 15 OR hue > 345?
  5. 5. What is the purpose of the saturation test (s > 0.5) in the red detector?

Go further

Colour spaces and thresholding — Computational Engineering — Tactiverge