Ring code: two-cut locator, thicker dashes, first-token confirmation, scanner in vote page

This commit is contained in:
2026-11-16 19:40:56 +01:00
parent 86ec6adb6b
commit ffe4f7d00c
4 changed files with 20 additions and 17 deletions
+14 -13
View File
@@ -7,10 +7,10 @@ export const RING_SECTORS = [24, 28, 32, 36];
// code space units, centered on the origin. the solid dark center disc is what the phone looks for // code space units, centered on the origin. the solid dark center disc is what the phone looks for
export const CENTER = 0.62; export const CENTER = 0.62;
export const RADII = [0.9, 1.05, 1.2, 1.35]; export const RADII = [0.9, 1.05, 1.2, 1.35];
export const THICK = 0.105; export const THICK = 0.12;
export const DISC = 1.5; // light background disc export const DISC = 1.5; // light background disc
// animation bounds: dash length and opacity breathe inside these, the data never depends on them // animation bounds: dash length and opacity breathe inside these, the data never depends on them
const LEN = [0.56, 0.86]; // part of the sector covered by the dash const LEN = [0.62, 0.88]; // part of the sector covered by the dash
// wide gap between the two classes so the camera tells them apart easily // wide gap between the two classes so the camera tells them apart easily
const ALPHA_DARK = [0.93, 1], ALPHA_LIGHT = [0.08, 0.19]; const ALPHA_DARK = [0.93, 1], ALPHA_LIGHT = [0.08, 0.19];
const NSYM = 6; const NSYM = 6;
@@ -268,7 +268,7 @@ function solve(A, B) {
} }
// dark blobs of one pyramid level that look like a filled ellipse. s = level px size in image px // dark blobs of one pyramid level that look like a filled ellipse. s = level px size in image px
function blobs(g, w, h, s, out) { function blobs(g, w, h, s, ratio, out) {
// dark = clearly under the brightest thing nearby. a washed projector keeps black/white around 0.6, // dark = clearly under the brightest thing nearby. a washed projector keeps black/white around 0.6,
// and the disc always has its light surround within reach, whatever the room does around the screen // and the disc always has its light surround within reach, whatever the room does around the screen
const T = 8, tw = Math.ceil(w / T), th = Math.ceil(h / T), tmax = new Float32Array(tw * th); const T = 8, tw = Math.ceil(w / T), th = Math.ceil(h / T), tmax = new Float32Array(tw * th);
@@ -285,7 +285,7 @@ function blobs(g, w, h, s, out) {
} }
// nothing bright around: not a screen // nothing bright around: not a screen
if (m < 48) continue; if (m < 48) continue;
const thr = m * 0.8, y1 = Math.min(h, (ty + 1) * T), x1 = Math.min(w, (tx + 1) * T); const thr = m * ratio, y1 = Math.min(h, (ty + 1) * T), x1 = Math.min(w, (tx + 1) * T);
for (let y = ty * T; y < y1; y++) for (let x = tx * T; x < x1; x++) if (g[y * w + x] < thr) dark[y * w + x] = 1; for (let y = ty * T; y < y1; y++) for (let x = tx * T; x < x1; x++) if (g[y * w + x] < thr) dark[y * w + x] = 1;
} }
const stack = new Int32Array(w * h), lo = new Int32Array(h), hi = new Int32Array(h), stamp = new Int32Array(h).fill(-1); const stack = new Int32Array(w * h), lo = new Int32Array(h), hi = new Int32Array(h), stamp = new Int32Array(h).fill(-1);
@@ -367,7 +367,8 @@ export function locate(img, opts = {}) {
// each level sees discs of ~5..14 px radius, halving covers every size up to the whole frame // each level sees discs of ~5..14 px radius, halving covers every size up to the whole frame
const raw = []; const raw = [];
for (let s = f; w >= 24 && h >= 24; s *= 2) { for (let s = f; w >= 24 && h >= 24; s *= 2) {
blobs(g, w, h, s, raw); // two cuts: the low one keeps a blurred disc apart from the first ring, the high one still sees it on a very washed screen
for (const ratio of [0.72, 0.8]) blobs(g, w, h, s, ratio, raw);
const w2 = w >> 1, h2 = h >> 1, g2 = new Float32Array(w2 * h2); const w2 = w >> 1, h2 = h >> 1, g2 = new Float32Array(w2 * h2);
for (let y = 0; y < h2; y++) for (let x = 0; x < w2; x++) { for (let y = 0; y < h2; y++) for (let x = 0; x < w2; x++) {
const i = 2 * y * w + 2 * x; const i = 2 * y * w + 2 * x;
@@ -385,7 +386,8 @@ export function locate(img, opts = {}) {
} }
const out = []; const out = [];
for (const c of cands) { for (const c of cands) {
const fit = (!globalThis.NOFIT && discFit(img, c)) || c, rn = ringness(img, fit); const fit = discFit(img, c) || c, rn = ringness(img, fit);
if (opts.dbg && Math.hypot(c.cx - opts.dbg.cx, c.cy - opts.dbg.cy) < 0.4 * opts.dbg.r) opts.dbg.stage = rn ? "ok" : fit === c ? "nofit" : "ringness";
if (rn) out.push({ ...fit, ...rn }); if (rn) out.push({ ...fit, ...rn });
if (out.length >= (opts.max || 3)) break; if (out.length >= (opts.max || 3)) break;
} }
@@ -729,22 +731,21 @@ function tokenOf(bits, soft, strict = true) {
// tries the projective geometry (better under tilt) and the plain affine one (safer on soft frames) // tries the projective geometry (better under tilt) and the plain affine one (safer on soft frames)
export function decodeAt(img, cand, opts = {}) { export function decodeAt(img, cand, opts = {}) {
const span = cand.span || 200, unit = Math.sqrt(Math.abs(cand.A[0] * cand.A[3] - cand.A[1] * cand.A[2])); const span = cand.span || 200, unit = Math.sqrt(Math.abs(cand.A[0] * cand.A[3] - cand.A[1] * cand.A[2]));
let tone = img, tc = cand; let tone = img, x0 = 0, y0 = 0;
if (opts.sharpen !== false && unit < 70) { if (opts.sharpen !== false && unit < 70) {
// small code: work on a sharpened crop // small code (under ~210 px across): read tones from a sharpened crop
const half = Math.ceil(unit * (DISC + 0.25)) + 4; const half = Math.ceil(unit * (DISC + 0.25)) + 4;
const x0 = Math.max(0, Math.round(cand.cx) - half), y0 = Math.max(0, Math.round(cand.cy) - half); x0 = Math.max(0, Math.round(cand.cx) - half); y0 = Math.max(0, Math.round(cand.cy) - half);
const x1 = Math.min(img.w, Math.round(cand.cx) + half + 1), y1 = Math.min(img.h, Math.round(cand.cy) + half + 1); const x1 = Math.min(img.w, Math.round(cand.cx) + half + 1), y1 = Math.min(img.h, Math.round(cand.cy) + half + 1);
const w = x1 - x0, h = y1 - y0, g = new Float32Array(w * h); const w = x1 - x0, h = y1 - y0, g = new Float32Array(w * h);
for (let y = 0; y < h; y++) g.set(img.g.subarray((y0 + y) * img.w + x0, (y0 + y) * img.w + x1), y * w); for (let y = 0; y < h; y++) g.set(img.g.subarray((y0 + y) * img.w + x0, (y0 + y) * img.w + x1), y * w);
tone = sharpen({ g, w, h }, 6, 2); tone = sharpen({ g, w, h }, 6, 2);
tc = { ...cand, cx: cand.cx - x0, cy: cand.cy - y0 };
} }
const [a11, a12, a21, a22] = tc.A; const [a11, a12, a21, a22] = cand.A;
// geometry comes from the plain image, tones from the sharpened one // geometry comes from the plain image, tones from the sharpened one
const proj = opts.projective !== false && projective(img, cand); const proj = opts.projective !== false && projective(img, cand);
const maps = [proj && ((x, y) => { const [u, v] = proj(x, y); return bilinear(tone, u - (cand.cx - tc.cx), v - (cand.cy - tc.cy)); }), const maps = [proj && ((x, y) => { const [u, v] = proj(x, y); return bilinear(tone, u - x0, v - y0); }),
(x, y) => bilinear(tone, tc.cx + a11 * x + a12 * y, tc.cy + a21 * x + a22 * y)].filter(Boolean); (x, y) => bilinear(tone, cand.cx - x0 + a11 * x + a12 * y, cand.cy - y0 + a21 * x + a22 * y)].filter(Boolean);
let best = null; let best = null;
for (const S0 of maps) { for (const S0 of maps) {
const S = (opts.refine !== false && refine(S0, span * (tone === img ? 1 : 2))) || S0; const S = (opts.refine !== false && refine(S0, span * (tone === img ? 1 : 2))) || S0;
+1 -1
View File
@@ -150,6 +150,6 @@ window.debugOne = (trial) => {
} }
return { quad: q, cTrue, cEst, radial, cands: out.map((o) => ({ ...o, r: o.r && { token: o.r.token, score: o.r.score, bits: o.r.bits } })) }; return { quad: q, cTrue, cEst, radial, cands: out.map((o) => ({ ...o, r: o.r && { token: o.r.token, score: o.r.score, bits: o.r.bits } })) };
}; };
window.benchReady = true; for (const k of new URLSearchParams(location.search).keys()) globalThis[k] = true; window.benchReady = true;
</script></head> </script></head>
<body></body></html> <body></body></html>
+3 -1
View File
@@ -39,7 +39,9 @@ function diagnose(img, k, truth, t) {
const T = (x, y) => { const [u, v] = truth(x, y); return [(u + 0.5) * k - 0.5, (v + 0.5) * k - 0.5]; }; const T = (x, y) => { const [u, v] = truth(x, y); return [(u + 0.5) * k - 0.5, (v + 0.5) * k - 0.5]; };
const [cx, cy] = T(0, 0), [ex, ey] = T(CENTER, 0), rpx = Math.hypot(ex - cx, ey - cy); const [cx, cy] = T(0, 0), [ex, ey] = T(CENTER, 0), rpx = Math.hypot(ex - cx, ey - cy);
const out = { rpx: +rpx.toFixed(1) }; const out = { rpx: +rpx.toFixed(1) };
const cands = locate(img, { max: 60 }); const dbg = { cx, cy, r: rpx, stage: "noblob" };
const cands = locate(img, { max: 60, dbg });
out.loc = dbg.stage;
out.rank = cands.findIndex((c) => Math.hypot(c.cx - cx, c.cy - cy) < 0.3 * rpx); out.rank = cands.findIndex((c) => Math.hypot(c.cx - cx, c.cy - cy) < 0.3 * rpx);
out.ncand = cands.length; out.ncand = cands.length;
if (out.rank >= 0) { const r = decodeAt(img, cands[out.rank], {}); out.candOk = !!(r && r.token === t.token); out.candScore = r ? +(+r.score).toFixed(2) : null; } if (out.rank >= 0) { const r = decodeAt(img, cands[out.rank], {}); out.candOk = !!(r && r.token === t.token); out.candScore = r ? +(+r.score).toFixed(2) : null; }
+2 -2
View File
@@ -165,7 +165,7 @@ async def run_far(p, n, pipes, diag):
for d in sorted({r["d"] for r in res}): for d in sorted({r["d"] for r in res}):
sub = [r["diag"] for r in res if r["d"] == d] sub = [r["diag"] for r in res if r["d"] == d]
good = [x for x in sub if x["rank"] in range(4) and x.get("candOk")] good = [x for x in sub if x["rank"] in range(4) and x.get("candOk")]
st = collections.Counter(x["stage"] for x in sub if x not in good) st = collections.Counter(x["stage"] + ("/" + x["loc"] if x["stage"] == "locate" else "") for x in sub if x not in good)
print(f" d {d}: ok {len(good)}/{len(sub)} fails by stage {dict(st)}" print(f" d {d}: ok {len(good)}/{len(sub)} fails by stage {dict(st)}"
f" bit errs with true geometry {sum(x['bitErr'] for x in sub) / len(sub):.1f} (ideal thr {sum(x['idealErr'] for x in sub) / len(sub):.1f})" f" bit errs with true geometry {sum(x['bitErr'] for x in sub) / len(sub):.1f} (ideal thr {sum(x['idealErr'] for x in sub) / len(sub):.1f})"
f" worst-ring d' {sum(min(x['dprime']) for x in sub) / len(sub):.1f} sync span {sum(x['span'] for x in sub) / len(sub):.0f} levels") f" worst-ring d' {sum(min(x['dprime']) for x in sub) / len(sub):.1f} sync span {sum(x['span'] for x in sub) / len(sub):.0f} levels")
@@ -230,7 +230,7 @@ async def main():
if throttle > 1: if throttle > 1:
# rough low-end phone: chrome devtools cpu slowdown factor # rough low-end phone: chrome devtools cpu slowdown factor
await p.send("Emulation.setCPUThrottlingRate", {"rate": throttle}) await p.send("Emulation.setCPUThrottlingRate", {"rate": throttle})
await p.goto(f"http://127.0.0.1:{PORT}/static/ringlab/bench.html?" + os.environ.get("Q", "")) await p.goto(f"http://127.0.0.1:{PORT}/static/ringlab/bench.html")
for _ in range(50): for _ in range(50):
if await p.js("!!window.benchReady"): if await p.js("!!window.benchReady"):
break break