# Tactiverge Academy — companion code for "Colour spaces and thresholding"
# Lesson: https://tactiverge.win/academy/computational-engineering/introduction-to-computer-vision/colour-and-thresholding/
# Licence: MIT (see https://tactiverge.win/open-engineering/). Examples appear in lesson order.

# ── Example 1 ────────────────────────────────────────
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))


# ── Example 2 ────────────────────────────────────────
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}")


# ── Example 3 ────────────────────────────────────────
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)}")


# ── Example 4 ────────────────────────────────────────
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))
