# Ink width of the subtitle line per cue and case, and a contact sheet. Background colour is known (0x1f2a44); text ink = any pixel that differs.
# Usage: python3 measure.py <workdir> <case> [<case> ...]
import sys, os
from PIL import Image
import numpy as np
W = sys.argv[1]; cases = sys.argv[2:]
BG = np.array([0x1f, 0x2a, 0x44])
def ink(path):
    a = np.array(Image.open(path).convert("RGB")).astype(int)
    m = (np.abs(a - BG).sum(axis=2) > 60)
    ys, xs = np.where(m)
    if len(xs) == 0: return 0, 0
    return int(xs.max() - xs.min() + 1), int(m.sum())
print("case | cue | ink width px | ink pixels")
for c in cases:
    for i in range(1, 9):
        w, n = ink(os.path.join(W, "frames", c, "cue%d.png" % i))
        print("%s | %d | %d | %d" % (c, i, w, n))
# contact sheet: rows = cases, columns = cues 1-6; crop the subtitle band (bottom 120 px), scaled by 0.5
tiles = []
for c in cases:
    row = [Image.open(os.path.join(W, "frames", c, "cue%d.png" % i)).convert("RGB").crop((240, 600, 1040, 720)) for i in range(1, 9)]
    tiles.append(row)
sheet = Image.new("RGB", (2 * 800, 4 * 120 * len(cases)), (0, 0, 0))
for r, row in enumerate(tiles):
    for k, t in enumerate(row):
        sheet.paste(t, ((k % 2) * 800, (r * 4 + k // 2) * 120))
sheet.save(os.path.join(W, "sheet-%s.png" % "-".join(x.split("-")[0] for x in cases)))
