From 867f6c46b926b4450ef08bb4932c9bd2210b569d Mon Sep 17 00:00:00 2001 From: Showdown76py Date: Sun, 16 Aug 2026 23:18:47 +0100 Subject: [PATCH] Ring decoder: vanishing line search when the fit misses (screens at 30-45 deg), sync score ignores a one-sided glare; glare bench --- .gitignore | 1 + README.md | 2 +- static/js/ringcode.js | 92 +++++++++++++++++++++++++++++++++++++---- static/ringlab/synth.js | 11 +++++ tools/ringbench.py | 48 +++++++++++++++++++-- 5 files changed, 142 insertions(+), 12 deletions(-) diff --git a/.gitignore b/.gitignore index cf4faf1..2ee9e12 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,4 @@ __pycache__/ .claude/ docs/video/ tools/bench_out/ +static/ringlab/tmp/ diff --git a/README.md b/README.md index dd535b7..c33ccc3 100644 --- a/README.md +++ b/README.md @@ -79,7 +79,7 @@ Par défaut, le projecteur affiche un code circulaire : un disque sombre avec le - Les anneaux ne s'ouvrent pas avec l'appareil photo natif : un petit QR fixe, dans un coin de l'écran, mène à la page de vote. - Signature de 32 bits : un jeton ne vaut que pendant environ 3 s et le serveur doit le recevoir en ligne. Même à 1 000 essais par seconde, la probabilité de deviner un jeton valide pendant sa durée de vie est d'environ 7 × 10⁻⁷, et il en faut 5 distincts pour s'inscrire. - De loin : le téléphone cherche le disque sur une copie réduite de l'image, puis lit un recadrage à la résolution du capteur. Le disque est repéré par rapport au blanc qui l'entoure, pas par un seuil global, ce qui tient avec un projecteur délavé dans une salle sombre. Repère pratique : rester à moins de 10 fois le diamètre du code (un code de 1 m se lit jusqu'à 10 m environ). -- Banc d'essai : `uv run python tools/ringbench.py` (Chrome sans interface, perspective, flou, contraste délavé, décor encombré, images sans code, code lointain sur projecteur délavé, séquences de 6 s). `CPU=6` simule un téléphone lent, `V1=1` rejoue l'ancien décodeur comme référence, `SUITE=far,seq` limite les séries. +- Banc d'essai : `uv run python tools/ringbench.py` (Chrome sans interface, perspective, flou, contraste délavé, décor encombré, images sans code, code lointain sur projecteur délavé, séquences de 6 s). `CPU=6` simule un téléphone lent, `V1=1` rejoue l'ancien décodeur comme référence, `SUITE=far,seq` limite les séries, `SUITE=glare` ajoute un reflet sur l'écran vu de biais. ## Sécurité : ce qui est garanti, ce qui ne l'est pas diff --git a/static/js/ringcode.js b/static/js/ringcode.js index e9625f7..05250a0 100644 --- a/static/js/ringcode.js +++ b/static/js/ringcode.js @@ -273,6 +273,23 @@ function corr(vals, bits) { return dv && db ? num / Math.sqrt(dv * db) : 0; } +// same as corr after removing the first angular harmonic from both sides: a reflection or a lamp lights one side +// of the ring brighter, and that slow swell alone pulls a clean sync ring under the threshold +const flatten = (v) => { + const n = v.length; + let a = 0, b = 0, c = 0; + for (let j = 0; j < n; j++) { const t = (2 * Math.PI * j) / n; a += v[j]; b += v[j] * Math.cos(t); c += v[j] * Math.sin(t); } + a /= n; b *= 2 / n; c *= 2 / n; + return v.map((x, j) => { const t = (2 * Math.PI * j) / n; return x - a - b * Math.cos(t) - c * Math.sin(t); }); +}; +const SYNC_FLAT = flatten(SYNC_BITS); +function corrFlat(vals) { + const f = flatten(vals); + let num = 0, dv = 0, db = 0; + for (let i = 0; i < f.length; i++) { num += f[i] * -SYNC_FLAT[i]; dv += f[i] * f[i]; db += SYNC_FLAT[i] * SYNC_FLAT[i]; } + return dv && db ? num / Math.sqrt(dv * db) : 0; +} + // otsu split of one ring: threshold + how well it separates (between-class / total variance) function split(vals) { const s = [...vals].sort((a, b) => a - b), n = s.length; @@ -682,6 +699,14 @@ function projective(img, cand) { if (!l || Math.abs(l[2]) < 1e-9) return null; l = l.map((v) => v / l[2]); lastProjective.l = l; lastProjective.stage = 'line'; + const map = mapFromLine(Q1, l, mx, my, sc); + lastProjective.stage = map ? 'ok' : 'ellipse'; + lastProjective.map = map; + return map; +} + +// code space -> image from the disc conic Q1 and a vanishing line l (normalized coordinates), or null +function mapFromLine(Q1, l, mx, my, sc) { // rectify: P maps the vanishing line to infinity const P = [[1, 0, 0], [0, 1, 0], l]; const Pi = inv3(P); @@ -696,20 +721,28 @@ function projective(img, cand) { // (x-c0)^T (M/kk) (x-c0) = 1 is the disc: scale so it becomes radius CENTER let a = M[0][0] / kk, b = M[0][1] / kk, c = M[1][1] / kk; if (a < 0) { a = -a; b = -b; c = -c; } - lastProjective.ellipse = [a, b, c]; lastProjective.stage = 'ellipse'; if (!(a > 0 && a * c - b * b > 0)) return null; - lastProjective.stage = 'ok'; const p = Math.sqrt(a), q = b / p, s = Math.sqrt(c - q * q); // affine from code space (radius CENTER) into the rectified plane: x = c0 + B t, B = (A^-1) / CENTER const B = [[1 / p / CENTER, -q / (p * s) / CENTER], [0, 1 / s / CENTER]]; - const map = (x, y) => { + return (x, y) => { const u = c0[0] + B[0][0] * x + B[0][1] * y, v = c0[1] + B[1][1] * y; const w = Pi[2][0] * u + Pi[2][1] * v + Pi[2][2]; + // points beyond the vanishing line fold back: report them off image + if (w <= 0) return [NaN, NaN]; const X = (Pi[0][0] * u + Pi[0][1] * v + Pi[0][2]) / w, Y = (Pi[1][0] * u + Pi[1][1] * v + Pi[1][2]) / w; return [X * sc + mx, Y * sc + my]; }; - lastProjective.map = map; - return map; +} + +// disc conic in normalized coordinates, for the tilt search +function discConic(img, cand) { + const disc = discEdge(img, cand, 160); + if (disc.length < 40) return null; + const mx = disc.reduce((s, p) => s + p[0], 0) / disc.length, my = disc.reduce((s, p) => s + p[1], 0) / disc.length; + const sc = Math.sqrt(disc.reduce((s, p) => s + (p[0] - mx) ** 2 + (p[1] - my) ** 2, 0) / disc.length) || 1; + const Q1 = fitConic(disc.map((p) => [(p[0] - mx) / sc, (p[1] - my) / sc])); + return Q1 && { Q1, mx, my, sc }; } // unsharp mask on a small crop: undoes part of the camera blur and flattens slow brightness changes @@ -800,6 +833,51 @@ export function decodeAt(img, cand, opts = {}) { if (r && r.token) return r; if (r && (!best || r.score > best.score)) best = r; } + // looks like a code but the geometry is off: a screen seen at 30-45 deg bends the outer rings more than the + // conic fit can follow. search the vanishing line directly, scored on the sync ring and the outer ring + if (opts.tilt !== false && best && best.score > 0.55 && best.theta != null) { + const D = discConic(img, cand); + if (D) { + const at = (map) => (x, y) => { const [u, v] = map(x, y); return bilinear(tone, u - x0, v - y0); }; + const n0 = RING_SECTORS[0], s0 = (2 * Math.PI) / n0, nk = RING_SECTORS[3], sk = (2 * Math.PI) / nk; + const quick = (S) => { + let top = null; + for (let dt = -12; dt <= 12; dt += 2) { + const th = best.theta + (dt * Math.PI) / 180, vals = []; + for (let j = 0; j < n0; j++) vals.push(sector(S, RADII[0], sectorAngle(th, j, n0), s0)); + if (vals.some(Number.isNaN)) return null; + const sc = Math.max(corr(vals, SYNC_BITS), corrFlat(vals)); + if (!top || sc > top.sc) top = { sc, th }; + } + const outer = []; + for (let j = 0; j < nk; j++) outer.push(sector(S, RADII[3], sectorAngle(top.th, j, nk), sk)); + if (outer.some(Number.isNaN)) return null; + return top.sc + split(outer).quality; + }; + const tries = []; + for (const m of [0.015, 0.03, 0.045, 0.06, 0.08, 0.1]) for (let i = 0; i < 16; i++) { + const a = (i / 16) * 2 * Math.PI, map = mapFromLine(D.Q1, [m * Math.cos(a), m * Math.sin(a), 1], D.mx, D.my, D.sc); + if (!map) continue; + const S = at(map), q = quick(S); + if (q != null) tries.push({ q, S, l: [m * Math.cos(a), m * Math.sin(a)] }); + } + tries.sort((p, q) => q.q - p.q); + for (const t of tries.slice(0, 3)) { + // polish around the pick on a finer grid before the full read + let pick = t; + for (const dx of [-0.008, 0, 0.008]) for (const dy of [-0.008, 0, 0.008]) { + if (!dx && !dy) continue; + const map = mapFromLine(D.Q1, [t.l[0] + dx, t.l[1] + dy, 1], D.mx, D.my, D.sc); + if (!map) continue; + const S = at(map), q = quick(S); + if (q != null && q > pick.q) pick = { q, S, l: [t.l[0] + dx, t.l[1] + dy] }; + } + const r = readRings(pick.S, { ...opts, span }); + if (r && r.token) return { ...r, tilt: pick.l }; + if (r && r.score > best.score) best = r; + } + } + } return best; } @@ -809,7 +887,7 @@ function readRings(S, opts) { const syncAt = (theta, scale) => { const vals = []; for (let j = 0; j < n0; j++) vals.push(sector(S, RADII[0] * scale, sectorAngle(theta, j, n0), step0)); - return vals.some(Number.isNaN) ? null : { score: corr(vals, SYNC_BITS), theta, scale, vals }; + return vals.some(Number.isNaN) ? null : { score: Math.max(corr(vals, SYNC_BITS), corrFlat(vals)), theta, scale, vals }; }; // coarse pass over the full turn (no rotational symmetry), then a fine pass around the best hits. // ~5x fewer samples than a dense search, which matters on low-end phones @@ -914,4 +992,4 @@ export function makeReader(opts = {}) { } // internals for the lab bench -export const _lab = { readRings, sector, bilinear, split, corr, sectorAngle, classify, tokenOf }; +export const _lab = { readRings, sector, bilinear, split, corr, sectorAngle, classify, tokenOf, discConic, mapFromLine, refine }; diff --git a/static/ringlab/synth.js b/static/ringlab/synth.js index 774cdb2..d458552 100644 --- a/static/ringlab/synth.js +++ b/static/ringlab/synth.js @@ -76,6 +76,7 @@ function page(pw, ph, d, t, rnd) { } // one sensor frame. t: W H frac tilt axis dist wash cast oblur pblur motion noise band gain dx dy theta bits anim fade +// glare: [dx, dy, radius, strength 0..1, tint] around the code centre, in code diameters // returns { canvas, truth } where truth maps code space to pixel index coordinates of the frame export function frame(room, t, rnd) { const { W, H } = t, ss = 2; @@ -117,6 +118,16 @@ export function frame(room, t, rnd) { sctx.imageSmoothingQuality = "high"; sctx.drawImage(B, x0, y0, x1 - x0, y1 - y0); } + if (t.glare) { + // reflection of a window or lamp on the screen: a tinted bright veil over part of the code + const [gx, gy, gr, gs, tint] = t.glare, [ccx, ccy] = applyH(fwd, P.cx, P.cy); + const x = ccx + gx * d, y = ccy + gy * d, g = sctx.createRadialGradient(x, y, 0, x, y, gr * d); + const [tr, tg, tb] = tint || [255, 235, 245]; + g.addColorStop(0, `rgba(${tr},${tg},${tb},${gs})`); g.addColorStop(0.5, `rgba(${tr},${tg},${tb},${gs * 0.6})`); g.addColorStop(1, `rgba(${tr},${tg},${tb},0)`); + sctx.globalCompositeOperation = "screen"; + sctx.fillStyle = g; sctx.fillRect(0, 0, W, H); + sctx.globalCompositeOperation = "source-over"; + } const out = document.createElement("canvas"); out.width = W; out.height = H; const octx = out.getContext("2d", { willReadFrequently: true }); // optical blur is angular (scales with sensor resolution), pixel softness is not diff --git a/tools/ringbench.py b/tools/ringbench.py index 7f33c37..2e370c2 100644 --- a/tools/ringbench.py +++ b/tools/ringbench.py @@ -1,6 +1,6 @@ """ring code bench: renders codes with perspective, blur, washed contrast and clutter in headless chrome, runs the real decoder and prints read rates. usage: uv run python tools/ringbench.py [trials per cell] -env: SUITE=legacy,far,seq,neg (default all) PIPES=legacy,cap960,scan DIAG=legacy|native FAR_D=80,100 NEG=300 +env: SUITE=legacy,far,glare,seq,neg (default all but glare) PIPES=legacy,cap960,scan DIAG=legacy|native FAR_D=80,100 NEG=300 IV=700 FADE_K=0.3 (sequence code interval and wipe share) CPU=6 (slow phone) V1=1 (decoder and dash design from before the far-reading work, the baseline)""" import asyncio import base64 @@ -22,7 +22,7 @@ sys.path.insert(0, str(ROOT / "tools")) from cdp import Browser # noqa: E402 from rotatyvote import ringcode # noqa: E402 -PORT = 8200 +PORT = int(os.environ.get("BENCH_PORT", "8200")) V1 = bool(os.environ.get("V1")) rng = random.Random(11) @@ -55,7 +55,7 @@ def code(r): # washed projector: (black level, white level) of the screen as the camera sees it -WASH = {0.45: (80, 195), 0.3: (105, 181)} +WASH = {1.0: (0, 255), 0.45: (80, 195), 0.3: (105, 181)} SENSORS = {1280: (1280, 720), 1920: (1920, 1080)} @@ -84,6 +84,44 @@ def far_trials(n): return out +def glare_trials(n): + """a reflection on the screen lights part of the code, often with a laptop lid or screen seen at an angle""" + r = random.Random(53) + out = [] + for d, tilt, strength, contrast in itertools.product([150, 250, 350], [0, 30, 45], [0.35, 0.6], [1.0, 0.45]): + for _ in range(n): + t = camera(r, d, contrast, r.choice([0.7, 1.5]), 1920) + a, k = r.uniform(0, 6.283), r.uniform(0.1, 0.6) + tint = r.choice([(255, 235, 245), (255, 250, 230), (230, 240, 255)]) + t.update(code(r), tilt=tilt, glare=[k * math.cos(a), k * math.sin(a), r.uniform(0.5, 1.1), strength, tint], + glareS=strength, jpeg=r.choice([0, 0.6])) + out.append(t) + return out + + +async def run_glare(p, n, pipes): + diag = os.environ.get("DIAG") + res = await chunks(p, "runFar", "trials", glare_trials(n), {"pipes": pipes, "keep": 3, "diag": diag}, 10) + print(f"\n== reflection on the screen, single frames ({len(res)} frames), 1920 sensor ==") + table(res, ("d", "tilt", "glareS", "contrast"), pipes) + for pn in pipes: + wrong = sum(1 for r in res if r[pn]["token"] and not r[pn]["ok"]) + print(f" {pn}: read {100 * sum(r[pn]['ok'] for r in res) / len(res):.0f} %, false tokens {wrong}") + if diag: + # where failing frames break when the true geometry is substituted stage by stage + for key in ("tilt", "glareS"): + for v in sorted({r[key] for r in res}): + sub = [r for r in res if r[key] == v and not r[pipes[0]]["ok"]] + st = collections.Counter(r["diag"]["stage"] for r in sub) + print(f" {key} {v}: {len(sub)} failures by stage {dict(st)} oracle sync {sum((r['diag']['oracleScore'] or 0) for r in sub) / max(1, len(sub)):.2f}" + f" byte errs with true geometry {sum(r['diag']['byteErr'] for r in sub) / max(1, len(sub)):.1f}") + out = ROOT / "tools" / "bench_out" + out.mkdir(exist_ok=True) + for i, r in enumerate(res[:3]): + if r.get("png"): + (out / f"glare_{i}.jpg").write_bytes(base64.b64decode(r["png"].split(",")[1])) + + def neg_trials(n): """nothing to read: no code on the screen, bare dark discs, discs with pie-like arcs around""" r = random.Random(31) @@ -227,7 +265,7 @@ async def main(): break except httpx.HTTPError: await asyncio.sleep(0.1) - b = Browser(9336) + b = Browser(int(os.environ.get("CDP_PORT", "9336"))) await b.start() p = await b.page(960, 720) throttle = float(os.environ.get("CPU", "1")) @@ -243,6 +281,8 @@ async def main(): await run_legacy(p, n) if "far" in suites: await run_far(p, n, pipes, os.environ.get("DIAG")) + if "glare" in suites: + await run_glare(p, n, pipes) if "seq" in suites: await run_seq(p, max(1, n // 2), pipes) if "neg" in suites: