Computer vision: Find coloured pixels with HSV

Picking out one colour, such as a red ball or a green leaf, is a classic first step in tracking objects.

What to build

A program that marks the pixels whose colour lies in an HSV range, counts them and finds their bounding box.

Requirements

  • A pixel matches when its saturation is at least Smin, its value at least Vmin, and its hue lies in the range from Hlow to Hhigh inclusive. If Hlow is greater than Hhigh, the range wraps around 0 degrees.
  • Print the mask, one line per row, with # for matching pixels and . for the rest.
  • Then print count N, then box rows R1-R2, columns C1-C2 for the smallest rectangle holding every match, or box none when nothing matches.

Input

Line 1: H and W. Then H lines of W pixels written as R,G,B. Last line: Hlow, Hhigh, Smin and Vmin.

Output

H mask lines, the count line and the box line.

Constraints

1 ≤ H, W ≤ 60.

Example

Input:

2 3
255,0,0 0,255,0 200,30,30
0,0,255 250,10,0 128,128,128
330 30 0.5 0.3

Output:

#.#
.#.
count 3
box rows 0-1, columns 0-2

Why it works

Hue picks the colour while saturation and value reject greys and dark pixels, whose hue is meaningless; the bounding box is the usual way to report where the coloured object is.

Examples

Example 1 · Input
2 3
255,0,0 0,255,0 200,30,30
0,0,255 250,10,0 128,128,128
330 30 0.5 0.3
Expected output
#.#
.#.
count 3
box rows 0-1, columns 0-2
Example 2 · Input
2 2
0,255,0 0,200,0
0,0,0 10,20,10
90 150 0.5 0.5
Expected output
##
..
count 2
box rows 0-0, columns 0-1

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Write a function that turns (R, G, B) into (H, S, V) as in the lesson, with H in degrees and S and V from 0 to 1.

Hint 2

For a wrapping range (low greater than high) a hue matches when it is ≥ low or ≤ high.

Solution

Show one correct solution (try it yourself first)
def to_hsv(r, g, b):
    hi, lo = max(r, g, b), min(r, g, b)
    d = hi - lo
    if d == 0:
        h = 0.0
    elif hi == r:
        h = 60 * (((g - b) / d) % 6)
    elif hi == g:
        h = 60 * ((b - r) / d + 2)
    else:
        h = 60 * ((r - g) / d + 4)
    return h, (0.0 if hi == 0 else d / hi), hi / 255


h, w = map(int, input().split())
img = [[tuple(map(int, p.split(","))) for p in input().split()] for _ in range(h)]
lo_h, hi_h, s_min, v_min = map(float, input().split())
found = []
for r in range(h):
    line = ""
    for c in range(w):
        hue, s, v = to_hsv(*img[r][c])
        in_range = lo_h <= hue <= hi_h if lo_h <= hi_h else (hue >= lo_h or hue <= hi_h)
        ok = in_range and s >= s_min and v >= v_min
        line += "#" if ok else "."
        if ok:
            found.append((r, c))
    print(line)
print("count", len(found))
if found:
    rs = [r for r, c in found]
    cs = [c for r, c in found]
    print(f"box rows {min(rs)}-{max(rs)}, columns {min(cs)}-{max(cs)}")
else:
    print("box none")

Lesson: Colour channels, colour spaces and greyscale →