Ring code v2: logo disc locator, projective rectification, animated dashes, lab pages, bench tool

This commit is contained in:
2026-08-16 18:15:22 +01:00
parent d507190b11
commit a6b4b44478
8 changed files with 736 additions and 138 deletions
+1
View File
@@ -6,3 +6,4 @@ __pycache__/
.pytest_cache/ .pytest_cache/
.claude/ .claude/
docs/video/ docs/video/
tools/bench_out/
+363 -82
View File
@@ -1,15 +1,17 @@
// ring code: static qr in the middle + rotating rings of dashes carrying the time token. // ring code: dark logo disc in the middle + rotating rings of dashes carrying the time token.
// layout, bit order and reed-solomon params must match rotatyvote/ringcode.py // layout, bit order and reed-solomon params must match rotatyvote/ringcode.py
// pure functions, no dom: runs in the browser and under node for the cross tests // pure functions, no dom: runs in the browser and under node for the cross tests
export const SYNC = "010001100101001000111111"; export const SYNC = "010001100101001000111111";
export const RING_SECTORS = [24, 28, 32, 36]; export const RING_SECTORS = [24, 28, 32, 36];
// radii in units of the center qr side, qr centered on the origin // code space units, centered on the origin. the solid dark center disc is what the phone looks for
// tight rings leave more of the diameter to the center qr, which is the detection bottleneck 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.105;
export const DASH = 0.74; // part of a sector covered by the dash export const DISC = 1.5; // light background disc
export const DISC = 1.5; // background disc radius // 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 ALPHA_DARK = [0.86, 1], ALPHA_LIGHT = [0.17, 0.33];
const NSYM = 6; const NSYM = 6;
// gf(256), poly 0x11d, generator 2 // gf(256), poly 0x11d, generator 2
@@ -142,76 +144,62 @@ const sectorAngle = (theta, j, n) => theta + ((j + 0.5) * 2 * Math.PI) / n;
// ---- drawing (projector + bench) ---- // ---- drawing (projector + bench) ----
export function render(ctx, cx, cy, side, theta, bits, modules, colors = {}) { const INK = "#1c2036";
const ink = colors.ink || "#1c2036", gray = colors.gray || "#a7acbd";
ctx.fillStyle = colors.disc || "#eef0f6"; function logo(ctx, cx, cy, r, t) {
ctx.beginPath(); ctx.arc(cx, cy, DISC * side, 0, 2 * Math.PI); ctx.fill(); // the rotaty mark in light tones on the dark disc
if (modules) { const n = 6, rr = r * 0.52, step = (2 * Math.PI) / n;
const n = modules.length, q = 2, s = side / n;
ctx.fillStyle = "#fff";
ctx.fillRect(cx - side / 2 - q * s, cy - side / 2 - q * s, side + 2 * q * s, side + 2 * q * s);
ctx.fillStyle = "#000";
for (let y = 0; y < n; y++) for (let x = 0; x < n; x++) {
if (modules[y][x] === "1") ctx.fillRect(cx - side / 2 + x * s, cy - side / 2 + y * s, s + 0.5, s + 0.5);
}
}
const rings = ringsOf(bits);
ctx.lineCap = "round"; ctx.lineCap = "round";
ctx.lineWidth = THICK * side; ctx.lineWidth = r * 0.17;
rings.forEach((ring, k) => { for (let j = 0; j < n; j++) {
const n = ring.length, r = RADII[k] * side, step = (2 * Math.PI) / n; const a = -Math.PI / 2 + j * step + t * 0.35;
// round caps stick out by half the stroke, take that off the arc ctx.strokeStyle = j === 0 ? "#ffcc00" : "#ffffff";
const cap = (THICK * side) / 2 / r; ctx.beginPath(); ctx.arc(cx, cy, rr, a + step * 0.2, a + step * 0.8); ctx.stroke();
const half = Math.max(0.01, (step * DASH) / 2 - cap); }
}
// deterministic per-dash phase so every dash breathes on its own rhythm
const phase = (k, j) => ((Math.sin(k * 12.9898 + j * 78.233) * 43758.5453) % 1 + 1) % 1;
export function render(ctx, cx, cy, unit, theta, bits, t = 0) {
ctx.fillStyle = "#eef0f6";
ctx.beginPath(); ctx.arc(cx, cy, DISC * unit, 0, 2 * Math.PI); ctx.fill();
ctx.fillStyle = INK;
ctx.beginPath(); ctx.arc(cx, cy, CENTER * unit, 0, 2 * Math.PI); ctx.fill();
logo(ctx, cx, cy, CENTER * unit, t);
ctx.lineCap = "round";
ctx.lineWidth = THICK * unit;
ringsOf(bits).forEach((ring, k) => {
const n = ring.length, r = RADII[k] * unit, step = (2 * Math.PI) / n;
const cap = (THICK * unit) / 2 / r;
for (let j = 0; j < n; j++) { for (let j = 0; j < n; j++) {
const ph = phase(k, j) * 2 * Math.PI, w = 0.5 + 0.5 * Math.sin(t * 1.3 + ph), w2 = 0.5 + 0.5 * Math.sin(t * 0.9 + ph * 1.7);
const len = LEN[0] + (LEN[1] - LEN[0]) * w;
const dark = ring[j] === "1";
const [a0, a1] = dark ? ALPHA_DARK : ALPHA_LIGHT;
const half = Math.max(0.01, (step * len) / 2 - cap);
const a = sectorAngle(theta, j, n) - Math.PI / 2; const a = sectorAngle(theta, j, n) - Math.PI / 2;
ctx.strokeStyle = ring[j] === "1" ? ink : gray; ctx.globalAlpha = a0 + (a1 - a0) * w2;
ctx.strokeStyle = INK;
ctx.beginPath(); ctx.arc(cx, cy, r, a - half, a + half); ctx.stroke(); ctx.beginPath(); ctx.arc(cx, cy, r, a - half, a + half); ctx.stroke();
} }
}); });
ctx.globalAlpha = 1;
} }
// ---- decoding (phone) ---- // ---- decoding (phone) ----
// homography mapping the unit qr square (-.5..+.5) onto the 4 detected corners (tl, tr, br, bl)
export function homography(c) {
const src = [[-0.5, -0.5], [0.5, -0.5], [0.5, 0.5], [-0.5, 0.5]];
const A = [], B = [];
for (let i = 0; i < 4; i++) {
const [x, y] = src[i], { x: u, y: v } = c[i];
A.push([x, y, 1, 0, 0, 0, -u * x, -u * y]); B.push(u);
A.push([0, 0, 0, x, y, 1, -v * x, -v * y]); B.push(v);
}
// gaussian elimination 8x8
for (let i = 0; i < 8; i++) {
let p = i;
for (let r = i + 1; r < 8; r++) if (Math.abs(A[r][i]) > Math.abs(A[p][i])) p = r;
[A[i], A[p]] = [A[p], A[i]]; [B[i], B[p]] = [B[p], B[i]];
if (Math.abs(A[i][i]) < 1e-12) return null;
for (let r = 0; r < 8; r++) if (r !== i) {
const f = A[r][i] / A[i][i];
for (let k = i; k < 8; k++) A[r][k] -= f * A[i][k];
B[r] -= f * B[i];
}
}
const h = B.map((b, i) => b / A[i][i]);
return (x, y) => { const w = h[6] * x + h[7] * y + 1; return [(h[0] * x + h[1] * y + h[2]) / w, (h[3] * x + h[4] * y + h[5]) / w]; };
}
export function grayOf(imageData) { export function grayOf(imageData) {
const { data, width, height } = imageData, g = new Float32Array(width * height); const { data, width, height } = imageData, g = new Float32Array(width * height);
for (let i = 0, j = 0; i < g.length; i++, j += 4) g[i] = 0.299 * data[j] + 0.587 * data[j + 1] + 0.114 * data[j + 2]; for (let i = 0, j = 0; i < g.length; i++, j += 4) g[i] = 0.299 * data[j] + 0.587 * data[j + 1] + 0.114 * data[j + 2];
return { g, w: width, h: height }; return { g, w: width, h: height };
} }
function sampler(img, H) { function bilinear(img, u, v) {
const { g, w, h } = img; const { g, w, h } = img;
return (x, y) => { if (!(u >= 0 && v >= 0 && u < w - 1 && v < h - 1)) return NaN;
const [u, v] = H(x, y); const x0 = u | 0, y0 = v | 0, fx = u - x0, fy = v - y0, i = y0 * w + x0;
if (!(u >= 0 && v >= 0 && u < w - 1 && v < h - 1)) return NaN; return (g[i] * (1 - fx) + g[i + 1] * fx) * (1 - fy) + (g[i + w] * (1 - fx) + g[i + w + 1] * fx) * fy;
const x0 = u | 0, y0 = v | 0, fx = u - x0, fy = v - y0, i = y0 * w + x0;
return (g[i] * (1 - fx) + g[i + 1] * fx) * (1 - fy) + (g[i + w] * (1 - fx) + g[i + w + 1] * fx) * fy;
};
} }
// mean brightness of one dash: a few points across its middle // mean brightness of one dash: a few points across its middle
@@ -269,11 +257,82 @@ function solve(A, B) {
return B.map((b, i) => b / A[i][i]); return B.map((b, i) => b / A[i][i]);
} }
// the qr corners are a few px off and that error grows with the radius. the rings themselves are the function otsu(vals) {
// better reference: find their dark bands along rays, fit one ellipse family, undo center/scale/shear const hist = new Float64Array(256);
for (const v of vals) hist[Math.max(0, Math.min(255, v | 0))]++;
let total = 0, sum = 0;
for (let i = 0; i < 256; i++) { total += hist[i]; sum += i * hist[i]; }
let wb = 0, sb = 0, best = 0, thr = 128;
for (let i = 0; i < 256; i++) {
wb += hist[i];
if (!wb || wb === total) continue;
sb += i * hist[i];
const mb = sb / wb, mf = (sum - sb) / (total - wb), v = wb * (total - wb) * (mb - mf) ** 2;
if (v > best) { best = v; thr = i; }
}
return thr;
}
// candidate center discs: solid dark elliptic blobs. returns [{ cx, cy, A }] in image pixels,
// A maps code space (center disc radius CENTER) onto the ellipse, rotation left free
export function locate(img, opts = {}) {
const f = Math.max(1, Math.ceil(Math.max(img.w, img.h) / (opts.maxDim || 480)));
const w = Math.floor(img.w / f), h = Math.floor(img.h / f), small = new Float32Array(w * h);
for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
let s = 0;
for (let dy = 0; dy < f; dy++) for (let dx = 0; dx < f; dx++) s += img.g[(y * f + dy) * img.w + x * f + dx];
small[y * w + x] = s / (f * f);
}
const thr = otsu(small);
const label = new Int32Array(w * h).fill(-1), cands = [];
const stack = [];
for (let start = 0; start < w * h; start++) {
if (label[start] !== -1 || small[start] > thr) continue;
// flood fill one dark component, keep per-row extents
const id = cands.length, rows = new Map();
let count = 0;
label[start] = id; stack.push(start);
while (stack.length) {
const i = stack.pop(), x = i % w, y = (i / w) | 0;
count++;
const r = rows.get(y);
if (r) { if (x < r[0]) r[0] = x; if (x > r[1]) r[1] = x; } else rows.set(y, [x, x]);
for (const j of [i - 1, i + 1, i - w, i + w]) {
if (j < 0 || j >= w * h || label[j] !== -1 || small[j] > thr) continue;
if ((j === i - 1 && x === 0) || (j === i + 1 && x === w - 1)) continue;
label[j] = id; stack.push(j);
}
}
cands.push(null);
if (count < 30 || rows.size < 6) continue;
// moments of the row-filled shape, so the light logo inside doesn't count as holes
let m0 = 0, mx = 0, my = 0, mxx = 0, myy = 0, mxy = 0;
for (const [y, [x0, x1]] of rows) {
const n = x1 - x0 + 1, sx = ((x0 + x1) * n) / 2, sxx = (x1 * (x1 + 1) * (2 * x1 + 1) - (x0 - 1) * x0 * (2 * x0 - 1)) / 6;
m0 += n; mx += sx; my += y * n; mxx += sxx; myy += y * y * n; mxy += y * sx;
}
const ux = mx / m0, uy = my / m0;
const cxx = mxx / m0 - ux * ux + 1 / 12, cyy = myy / m0 - uy * uy + 1 / 12, cxy = mxy / m0 - ux * uy;
const tr = cxx + cyy, dt = Math.sqrt(Math.max(0, ((cxx - cyy) / 2) ** 2 + cxy * cxy));
const l1 = tr / 2 + dt, l2 = tr / 2 - dt;
if (l2 <= 0) continue;
const a = 2 * Math.sqrt(l1), b = 2 * Math.sqrt(l2);
const fill = m0 / (Math.PI * a * b), solidity = count / m0;
if (fill < 0.86 || fill > 1.14 || solidity < 0.5 || b / a < 0.38 || b < 5) continue;
const phi = 0.5 * Math.atan2(2 * cxy, cxx - cyy);
const c = Math.cos(phi), s = Math.sin(phi);
const k1 = (a * f) / CENTER, k2 = (b * f) / CENTER;
cands[id] = { cx: (ux + 0.5) * f - 0.5, cy: (uy + 0.5) * f - 0.5, A: [c * k1, -s * k2, s * k1, c * k2], area: m0 };
}
return cands.filter(Boolean).sort((p, q) => q.area - p.area).slice(0, opts.max || 4);
}
// the rough ellipse from the center disc is a bit off, and more so as the radius grows.
// the rings themselves are the better reference: find their dark bands along rays,
// fit one concentric ellipse family, undo center/scale/shear
function refine(S) { function refine(S) {
const rows = []; const rows = [];
const rays = 160, r0 = 0.72, r1 = 1.48, dr = 0.005; const rays = 160, r0 = 0.74, r1 = 1.48, dr = 0.005;
for (let i = 0; i < rays; i++) { for (let i = 0; i < rays; i++) {
const phi = (i / rays) * 2 * Math.PI, dx = Math.sin(phi), dy = -Math.cos(phi); const phi = (i / rays) * 2 * Math.PI, dx = Math.sin(phi), dy = -Math.cos(phi);
const prof = []; const prof = [];
@@ -282,12 +341,12 @@ function refine(S) {
const sorted = [...prof].sort((a, b) => a - b); const sorted = [...prof].sort((a, b) => a - b);
const bg = sorted[Math.floor(sorted.length * 0.9)], lo = sorted[0]; const bg = sorted[Math.floor(sorted.length * 0.9)], lo = sorted[0];
if (bg - lo < 15) continue; if (bg - lo < 15) continue;
RADII.forEach((R, k) => { RADII.forEach((R) => {
const c = Math.round((R - r0) / dr), w = Math.round(0.065 / dr); const c = Math.round((R - r0) / dr), wdw = Math.round(0.065 / dr);
let m = -1; let m = -1;
for (let j = Math.max(1, c - w); j <= Math.min(prof.length - 2, c + w); j++) if (m < 0 || prof[j] < prof[m]) m = j; for (let j = Math.max(1, c - wdw); j <= Math.min(prof.length - 2, c + wdw); j++) if (m < 0 || prof[j] < prof[m]) m = j;
if (m <= 0 || m >= prof.length - 1) return; if (m <= 0 || m >= prof.length - 1) return;
// a ray through a gap between dashes has no real dip, skip it // a ray through a gap or a pale dash has no real dip, skip it
if (bg - prof[m] < 0.4 * (bg - lo)) return; if (bg - prof[m] < 0.4 * (bg - lo)) return;
const a = prof[m - 1], b = prof[m], cc = prof[m + 1], den = a - 2 * b + cc; const a = prof[m - 1], b = prof[m], cc = prof[m + 1], den = a - 2 * b + cc;
const off = den > 0 ? (0.5 * (a - cc)) / den : 0; const off = den > 0 ? (0.5 * (a - cc)) / den : 0;
@@ -302,30 +361,241 @@ function refine(S) {
const sol = solve(N, V); const sol = solve(N, V);
if (!sol) return null; if (!sol) return null;
const [a, b, c, d, e] = sol; const [a, b, c, d, e] = sol;
const det = a * c - (b * b) / 4; if (!(a > 0 && a * c - (b * b) / 4 > 0)) return null;
if (!(a > 0 && det > 0)) return null;
// center: grad = 0 -> [2a b; b 2c] x = -[d e]
const x0 = (-d * 2 * c + e * b) / (4 * a * c - b * b), y0 = (-e * 2 * a + d * b) / (4 * a * c - b * b); const x0 = (-d * 2 * c + e * b) / (4 * a * c - b * b), y0 = (-e * 2 * a + d * b) / (4 * a * c - b * b);
// cholesky of M = [[a, b/2], [b/2, c]] = A^T A, A upper triangular
const p = Math.sqrt(a), q = b / 2 / p, s = Math.sqrt(c - q * q); const p = Math.sqrt(a), q = b / 2 / p, s = Math.sqrt(c - q * q);
if (!(s > 0) || Math.hypot(x0, y0) > 0.15 || Math.abs(Math.log(p * s)) > 0.25) return null; if (!(s > 0) || Math.hypot(x0, y0) > 0.2 || Math.abs(Math.log(p * s)) > 0.35) return null;
// true ring space -> measured space: m = c0 + A^-1 t
const i11 = 1 / p, i12 = -q / (p * s), i22 = 1 / s; const i11 = 1 / p, i12 = -q / (p * s), i22 = 1 / s;
return (x, y) => S(x0 + i11 * x + i12 * y, y0 + i22 * y); return (x, y) => S(x0 + i11 * x + i12 * y, y0 + i22 * y);
} }
// returns { token, theta, score, scale } or null // ---- perspective from two concentric circles ----
export function decode(img, corners, opts = {}) { // images of concentric circles C1, C2 are conics Q1, Q2. the pencil Q1 - l*Q2 holds a rank-1 member,
const H = homography(corners); // the doubled vanishing line. knowing that line undoes the projective part, the rest is affine.
if (!H) return null;
const S = (opts.refine !== false && refine(sampler(img, H))) || sampler(img, H); function jacobi(M) {
// eigen decomposition of a small symmetric matrix
const n = M.length, A = M.map((r) => [...r]), V = Array.from({ length: n }, (_, i) => Array.from({ length: n }, (_, j) => +(i === j)));
for (let sweep = 0; sweep < 60; sweep++) {
let off = 0;
for (let i = 0; i < n; i++) for (let j = i + 1; j < n; j++) off += A[i][j] * A[i][j];
if (off < 1e-22) break;
for (let p = 0; p < n; p++) for (let q = p + 1; q < n; q++) {
if (Math.abs(A[p][q]) < 1e-30) continue;
const th = (A[q][q] - A[p][p]) / (2 * A[p][q]);
const t = Math.sign(th || 1) / (Math.abs(th) + Math.sqrt(th * th + 1)), c = 1 / Math.sqrt(t * t + 1), s = t * c;
for (let k = 0; k < n; k++) {
const akp = A[k][p], akq = A[k][q];
A[k][p] = c * akp - s * akq; A[k][q] = s * akp + c * akq;
}
for (let k = 0; k < n; k++) {
const apk = A[p][k], aqk = A[q][k];
A[p][k] = c * apk - s * aqk; A[q][k] = s * apk + c * aqk;
}
for (let k = 0; k < n; k++) {
const vkp = V[k][p], vkq = V[k][q];
V[k][p] = c * vkp - s * vkq; V[k][q] = s * vkp + c * vkq;
}
}
}
return { values: A.map((r, i) => r[i]), vectors: V };
}
function fitConic(pts) {
// algebraic fit, smallest eigenvector of the scatter matrix (points already normalized)
if (pts.length < 12) return null;
const S = Array.from({ length: 6 }, () => new Array(6).fill(0));
for (const [x, y] of pts) {
const r = [x * x, x * y, y * y, x, y, 1];
for (let i = 0; i < 6; i++) for (let j = 0; j < 6; j++) S[i][j] += r[i] * r[j];
}
const { values, vectors } = jacobi(S);
let k = 0;
for (let i = 1; i < 6; i++) if (values[i] < values[k]) k = i;
const [a, b, c, d, e, f] = vectors.map((row) => row[k]);
return [[a, b / 2, d / 2], [b / 2, c, e / 2], [d / 2, e / 2, f]];
}
const det3 = (m) => m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1]) - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0]) + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0]);
const sub3 = (A, B, l) => A.map((r, i) => r.map((v, j) => v - l * B[i][j]));
function inv3(m) {
const d = det3(m);
if (Math.abs(d) < 1e-30) return null;
const c = (i, j) => {
const r = [0, 1, 2].filter((k) => k !== i), q = [0, 1, 2].filter((k) => k !== j);
return ((i + j) % 2 ? -1 : 1) * (m[r[0]][q[0]] * m[r[1]][q[1]] - m[r[0]][q[1]] * m[r[1]][q[0]]);
};
return [0, 1, 2].map((i) => [0, 1, 2].map((j) => c(j, i) / d));
}
const mul3 = (A, B) => A.map((r) => [0, 1, 2].map((j) => r[0] * B[0][j] + r[1] * B[1][j] + r[2] * B[2][j]));
const tr3 = (A) => [0, 1, 2].map((i) => [0, 1, 2].map((j) => A[j][i]));
function cubicRoots(a, b, c, d) {
// real roots of a x^3 + b x^2 + c x + d
b /= a; c /= a; d /= a;
const p = c - (b * b) / 3, q = (2 * b * b * b) / 27 - (b * c) / 3 + d, disc = (q * q) / 4 + (p * p * p) / 27;
if (disc > 0) {
const u = Math.cbrt(-q / 2 + Math.sqrt(disc)), v = Math.cbrt(-q / 2 - Math.sqrt(disc));
// near a double root the pair turns complex with noise: report its real part twice
return [u + v - b / 3, -(u + v) / 2 - b / 3, -(u + v) / 2 - b / 3];
}
const r = 2 * Math.sqrt(-p / 3), phi = Math.acos(Math.max(-1, Math.min(1, (3 * q) / (p * r))));
return [0, 1, 2].map((k) => r * Math.cos(phi / 3 - (2 * Math.PI * k) / 3) - b / 3);
}
// image points on the center disc edge and on each ring, following rays of the rough affine map
function edgePoints(img, cand) {
const [a11, a12, a21, a22] = cand.A;
const map = (x, y) => [cand.cx + a11 * x + a12 * y, cand.cy + a21 * x + a22 * y];
const at = (x, y) => { const [u, v] = map(x, y); return bilinear(img, u, v); };
const disc = [], rings = RADII.map(() => []), rays = 160;
for (let i = 0; i < rays; i++) {
const phi = (i / rays) * 2 * Math.PI, dx = Math.sin(phi), dy = -Math.cos(phi);
// disc edge: strongest dark-to-light step between 0.42 and 0.8
let best = 0, br = 0;
const prof = [];
for (let r = 0.4; r <= 0.82; r += 0.005) prof.push(at(r * dx, r * dy));
if (!prof.some(Number.isNaN)) {
for (let j = 2; j < prof.length - 2; j++) {
const gstep = prof[j + 2] - prof[j - 2];
if (gstep > best) { best = gstep; br = 0.4 + j * 0.005; }
}
if (best > 20) disc.push(map(br * dx, br * dy));
}
// rings: darkest point around each radius, only when it is a clear dip (a dark dash)
RADII.forEach((R, k) => {
const op = [], span = 0.07;
for (let r = R - span; r <= R + span + 1e-9; r += 0.004) op.push(at(r * dx, r * dy));
if (op.some(Number.isNaN)) return;
let m = 0;
for (let j = 1; j < op.length; j++) if (op[j] < op[m]) m = j;
const edge = Math.max(op[0], op[op.length - 1]);
if (m > 1 && m < op.length - 2 && edge - op[m] > 35) {
const a = op[m - 1], b = op[m], c = op[m + 1], den = a - 2 * b + c;
const off = den > 0 ? (0.5 * (a - c)) / den : 0;
const r = R - span + (m + off) * 0.004;
rings[k].push(map(r * dx, r * dy));
}
});
}
return { disc, rings };
}
// center of a conic (3x3 symmetric), in its own coordinates
function conicCenter(Q) {
const d = Q[0][0] * Q[1][1] - Q[0][1] * Q[1][0];
if (Math.abs(d) < 1e-18) return null;
return [-(Q[1][1] * Q[0][2] - Q[0][1] * Q[1][2]) / d, -(-Q[1][0] * Q[0][2] + Q[0][0] * Q[1][2]) / d];
}
function nelderMead(f, x0, step, iters) {
let pts = [x0, [x0[0] + step, x0[1]], [x0[0], x0[1] + step]].map((x) => ({ x, v: f(x) }));
for (let it = 0; it < iters; it++) {
pts.sort((a, b) => a.v - b.v);
const [b, g, w] = pts, c = [(b.x[0] + g.x[0]) / 2, (b.x[1] + g.x[1]) / 2];
const at = (t) => [c[0] + t * (w.x[0] - c[0]), c[1] + t * (w.x[1] - c[1])];
const r = { x: at(-1) }; r.v = f(r.x);
if (r.v < b.v) { const e = { x: at(-2) }; e.v = f(e.x); pts[2] = e.v < r.v ? e : r; }
else if (r.v < g.v) pts[2] = r;
else { const k = { x: at(0.5) }; k.v = f(k.x); if (k.v < w.v) pts[2] = k; else pts = [b, ...[g, w].map((p) => { const x = [(p.x[0] + b.x[0]) / 2, (p.x[1] + b.x[1]) / 2]; return { x, v: f(x) }; })]; }
}
pts.sort((a, b) => a.v - b.v);
return pts[0].x;
}
// projective map code space -> image from the two conics, or null
export let lastProjective = null;
function projective(img, cand) {
const { disc, rings } = edgePoints(img, cand);
const outer = rings[rings.length - 1];
lastProjective = { disc: disc.length, rings: rings.map((r) => r.length), stage: 'points' };
if (disc.length < 40 || outer.length < 30) return null;
// normalize coordinates for a well conditioned fit
const all = [disc, ...rings].flat();
const mx = all.reduce((s, p) => s + p[0], 0) / all.length, my = all.reduce((s, p) => s + p[1], 0) / all.length;
const sc = Math.sqrt(all.reduce((s, p) => s + (p[0] - mx) ** 2 + (p[1] - my) ** 2, 0) / all.length) || 1;
const nrm = (p) => [(p[0] - mx) / sc, (p[1] - my) / sc];
const Q1 = fitConic(disc.map(nrm)), Q2 = fitConic(outer.map(nrm));
if (!Q1 || !Q2) return null;
// for concentric circles C1 C2^-1 = diag(1, 1, r1^2/r2^2): its simple eigenvalue belongs to the
// line at infinity. in the image that eigenvector of Q1 Q2^-1 is the vanishing line (stable, unlike the double one)
const Q2i = inv3(Q2);
if (!Q2i) return null;
const N = mul3(Q1, Q2i);
const tr = N[0][0] + N[1][1] + N[2][2];
const minors = N[0][0] * N[1][1] - N[0][1] * N[1][0] + N[0][0] * N[2][2] - N[0][2] * N[2][0] + N[1][1] * N[2][2] - N[1][2] * N[2][1];
const roots = cubicRoots(1, -tr, minors, -det3(N));
let mu = roots[0], gap = -1;
for (let i = 0; i < 3; i++) {
const g = Math.min(...roots.filter((_, j) => j !== i).map((r) => Math.abs(r - roots[i])));
if (g > gap) { gap = g; mu = roots[i]; }
}
lastProjective.roots = roots; lastProjective.stage = 'roots';
// left eigenvector: l^T (N - mu I) = 0, so l is orthogonal to the columns of (N - mu I)
const Mt = tr3(sub3(N, [[1, 0, 0], [0, 1, 0], [0, 0, 1]], mu));
const cross = (u, v) => [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]];
let l = null, ln = 0;
for (const [i, j] of [[0, 1], [0, 2], [1, 2]]) {
const c = cross(Mt[i], Mt[j]), n = Math.hypot(...c);
if (n > ln) { ln = n; l = c; }
}
if (!l || Math.abs(l[2]) < 1e-9) return null;
l = l.map((v) => v / l[2]);
lastProjective.l = l; lastProjective.stage = 'line';
// rectify: P maps the vanishing line to infinity
const P = [[1, 0, 0], [0, 1, 0], l];
const Pi = inv3(P);
if (!Pi) return null;
const Q1r = mul3(tr3(Pi), mul3(Q1, Pi));
// Q1r is now an ellipse: x^T M x + 2 g.x + f = 0
const M = [[Q1r[0][0], Q1r[0][1]], [Q1r[1][0], Q1r[1][1]]], g = [Q1r[0][2], Q1r[1][2]], f = Q1r[2][2];
const dm = M[0][0] * M[1][1] - M[0][1] * M[1][0];
if (Math.abs(dm) < 1e-18) return null;
const c0 = [-(M[1][1] * g[0] - M[0][1] * g[1]) / dm, -(-M[1][0] * g[0] + M[0][0] * g[1]) / dm];
const kk = -(f + g[0] * c0[0] + g[1] * c0[1]);
// (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) => {
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];
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 (x, y) => { const [u, v] = map(x, y); return bilinear(img, u, v); };
}
// reads one candidate. returns { token, theta, score, scale } or { token: null, ... } or null.
// tries the projective geometry (better under tilt) and the plain affine one (safer on soft frames)
export function decodeAt(img, cand, opts = {}) {
const [a11, a12, a21, a22] = cand.A;
const affine = (x, y) => bilinear(img, cand.cx + a11 * x + a12 * y, cand.cy + a21 * x + a22 * y);
const maps = [opts.projective !== false && projective(img, cand), affine].filter(Boolean);
let best = null;
for (const S0 of maps) {
const S = (opts.refine !== false && refine(S0)) || S0;
const r = readRings(S, opts);
if (r && r.token) return r;
if (r && (!best || r.score > best.score)) best = r;
}
return best;
}
function readRings(S, opts) {
const steps = opts.steps || 360, minScore = opts.minScore ?? 0.8; const steps = opts.steps || 360, minScore = opts.minScore ?? 0.8;
let best = null; let best = null;
for (const scale of opts.scales || [0.94, 0.97, 1.0, 1.03, 1.06]) { for (const scale of opts.scales || [0.95, 0.975, 1.0, 1.025, 1.05]) {
const r0 = RADII[0] * scale, n0 = RING_SECTORS[0], step0 = (2 * Math.PI) / n0; const r0 = RADII[0] * scale, n0 = RING_SECTORS[0], step0 = (2 * Math.PI) / n0;
// full turn: the sync pattern has no rotational symmetry // full turn: the sync pattern has no rotational symmetry
for (let t = 0; t < steps; t++) { for (let t = 0; t < steps; t++) {
const theta = (t / steps) * step0 * n0; const theta = (t / steps) * 2 * Math.PI;
const vals = []; const vals = [];
for (let j = 0; j < n0; j++) vals.push(sector(S, r0, sectorAngle(theta, j, n0), step0)); for (let j = 0; j < n0; j++) vals.push(sector(S, r0, sectorAngle(theta, j, n0), step0));
if (vals.some(Number.isNaN)) return null; if (vals.some(Number.isNaN)) return null;
@@ -337,12 +607,11 @@ export function decode(img, corners, opts = {}) {
if (!best || best.score < minScore) return best ? { token: null, ...best } : null; if (!best || best.score < minScore) return best ? { token: null, ...best } : null;
const dark = [], light = []; const dark = [], light = [];
best.vals.forEach((v, j) => (SYNC_BITS[j] ? dark : light).push(v)); best.vals.forEach((v, j) => (SYNC_BITS[j] ? dark : light).push(v));
const md = dark.reduce((a, b) => a + b) / dark.length, ml = light.reduce((a, b) => a + b) / light.length; const md = dark.reduce((x, y) => x + y) / dark.length, ml = light.reduce((x, y) => x + y) / light.length;
if (ml - md < 12) return { token: null, ...best }; if (ml - md < 12) return { token: null, ...best };
const bits = []; const bits = [];
for (let k = 1; k < RING_SECTORS.length; k++) { for (let k = 1; k < RING_SECTORS.length; k++) {
// corners come from the small center square, so outer rings drift under perspective: // nudge scale and rotation per ring (perspective is only approximated) and keep the cleanest split
// nudge scale and rotation per ring and keep the cleanest dark/light split
const n = RING_SECTORS[k], step = (2 * Math.PI) / n; const n = RING_SECTORS[k], step = (2 * Math.PI) / n;
let pick = null; let pick = null;
for (const ds of [-0.03, -0.015, 0, 0.015, 0.03]) for (const dt of [-0.22, 0, 0.22]) { for (const ds of [-0.03, -0.015, 0, 0.015, 0.03]) for (const dt of [-0.22, 0, 0.22]) {
@@ -356,5 +625,17 @@ export function decode(img, corners, opts = {}) {
for (const v of pick.vals) bits.push(v < pick.thr ? 1 : 0); for (const v of pick.vals) bits.push(v < pick.thr ? 1 : 0);
} }
const msg = rsDecode(bytesFromBits(bits)); const msg = rsDecode(bytesFromBits(bits));
return { ...best, bits: bits.join(""), token: msg ? tokenFromPayload(msg) : null }; return { ...best, vals: undefined, bits: bits.join(""), token: msg ? tokenFromPayload(msg) : null };
}
// whole frame: find center discs, read the first one that yields a valid token
export function decodeFrame(img, opts = {}) {
const cands = locate(img, opts);
let last = null;
for (const c of cands) {
const r = decodeAt(img, c, opts);
if (r && r.token) return { ...r, cand: c, found: cands.length };
last = r || last;
}
return { token: null, found: cands.length, score: last?.score ?? null };
} }
+79 -39
View File
@@ -3,7 +3,8 @@
<head><meta charset="utf-8"><title>Ring code bench</title> <head><meta charset="utf-8"><title>Ring code bench</title>
<script src="/static/vendor/qr-scanner.umd.min.js"></script> <script src="/static/vendor/qr-scanner.umd.min.js"></script>
<script type="module"> <script type="module">
import { render, decode, grayOf, homography, DISC } from "/static/js/ringcode.js"; import { render, decodeFrame, grayOf, locate, decodeAt, DISC } from "/static/js/ringcode.js";
import * as RC from "/static/js/ringcode.js";
// warps canvas `src` onto a new w x h canvas so that src's unit square maps to quad `dst` (perspective) // warps canvas `src` onto a new w x h canvas so that src's unit square maps to quad `dst` (perspective)
function warp(src, dst, w, h, bg) { function warp(src, dst, w, h, bg) {
@@ -34,16 +35,17 @@ function warp(src, dst, w, h, bg) {
for (let c = 0; c < 3; c++) { for (let c = 0; c < 3; c++) {
od.data[o + c] = (s.data[i + c] * (1 - fx) + s.data[i + 4 + c] * fx) * (1 - fy) + (s.data[i + sw * 4 + c] * (1 - fx) + s.data[i + sw * 4 + 4 + c] * fx) * fy; od.data[o + c] = (s.data[i + c] * (1 - fx) + s.data[i + 4 + c] * fx) * (1 - fy) + (s.data[i + sw * 4 + c] * (1 - fx) + s.data[i + sw * 4 + 4 + c] * fx) * fy;
} }
} else { od.data[o] = bg[0]; od.data[o + 1] = bg[1]; od.data[o + 2] = bg[2]; } od.data[o + 3] = 255;
od.data[o + 3] = 255; } else od.data[o + 3] = 0;
} }
octx.putImageData(od, 0, 0); octx.putImageData(od, 0, 0);
return out; return out;
} }
// square of the code area, centred at (cx, cy) with diameter d, tilted by `tilt` deg around an axis at angle `axis` // square of the code area, centred at (cx, cy) with diameter d, tilted by `tilt` deg around an axis at angle `axis`
function quad(cx, cy, d, tilt, axis) { function quad(cx, cy, d, tilt, axis, dist = 3.5) {
const t = tilt * Math.PI / 180, a = axis * Math.PI / 180, f = 1.6 * d; // dist: camera distance in code diameters (3.5 ~ a 1 m code seen from a few metres)
const t = tilt * Math.PI / 180, a = axis * Math.PI / 180, f = dist * d;
const pts = [[-1, -1], [1, -1], [1, 1], [-1, 1]].map(([x, y]) => { const pts = [[-1, -1], [1, -1], [1, 1], [-1, 1]].map(([x, y]) => {
// rotate into axis frame, tilt around that axis, rotate back, perspective project // rotate into axis frame, tilt around that axis, rotate back, perspective project
let X = x * Math.cos(a) + y * Math.sin(a), Y = -x * Math.sin(a) + y * Math.cos(a), Z = 0; let X = x * Math.cos(a) + y * Math.sin(a), Y = -x * Math.sin(a) + y * Math.cos(a), Z = 0;
@@ -55,59 +57,97 @@ function quad(cx, cy, d, tilt, axis) {
return pts; return pts;
} }
function clutter(ctx, w, h, rnd) {
const g = ctx.createLinearGradient(0, 0, w, h);
g.addColorStop(0, `hsl(${rnd() * 360}, 15%, ${30 + rnd() * 40}%)`); g.addColorStop(1, `hsl(${rnd() * 360}, 20%, ${20 + rnd() * 50}%)`);
ctx.fillStyle = g; ctx.fillRect(0, 0, w, h);
for (let i = 0; i < 18; i++) {
const l = rnd() * 100;
ctx.fillStyle = `hsl(${rnd() * 360}, ${rnd() * 40}%, ${l}%)`;
const k = rnd();
if (k < 0.4) ctx.fillRect(rnd() * w, rnd() * h, 20 + rnd() * 200, 10 + rnd() * 120);
else if (k < 0.6) { ctx.beginPath(); ctx.arc(rnd() * w, rnd() * h, 10 + rnd() * 60, 0, 7); ctx.fill(); } // decoy discs
else if (k < 0.8) { ctx.font = `${14 + rnd() * 40}px system-ui`; ctx.fillText("Assemblée générale 2026", rnd() * w, rnd() * h); }
else { ctx.lineWidth = 2 + rnd() * 10; ctx.strokeStyle = ctx.fillStyle; ctx.beginPath(); ctx.moveTo(rnd() * w, rnd() * h); ctx.lineTo(rnd() * w, rnd() * h); ctx.stroke(); }
}
}
window.runBench = async (cfg) => { window.runBench = async (cfg) => {
const engine = await QrScanner.createQrEngine(); let seed = 12345;
QrScanner._disableBarcodeDetector = !!cfg.noBarcodeDetector; const rnd = () => ((seed = (seed * 1103515245 + 12345) & 0x7fffffff) / 0x7fffffff);
const results = []; const results = [];
const A = document.createElement("canvas"); A.width = A.height = 800; const A = document.createElement("canvas"); A.width = A.height = 800;
const actx = A.getContext("2d"); const actx = A.getContext("2d");
for (const trial of cfg.trials) { for (const trial of cfg.trials) {
const side = A.width / (2 * DISC);
actx.fillStyle = "#f5f6fa"; actx.fillRect(0, 0, A.width, A.height);
render(actx, A.width / 2, A.height / 2, side, trial.theta, trial.bits, cfg.modules);
const q = quad(480 + trial.dx, 360 + trial.dy, trial.d, trial.tilt, trial.axis);
let B = warp(A, q, 960, 720, [60, 62, 74]);
const C = document.createElement("canvas"); C.width = 960; C.height = 720; const C = document.createElement("canvas"); C.width = 960; C.height = 720;
const cctx = C.getContext("2d"); const cctx = C.getContext("2d", { willReadFrequently: true });
const scene = document.createElement("canvas"); scene.width = 960; scene.height = 720;
const sctx = scene.getContext("2d");
clutter(sctx, 960, 720, rnd);
if (!trial.nocode) {
actx.clearRect(0, 0, A.width, A.height);
render(actx, A.width / 2, A.height / 2, A.width / (2 * DISC), trial.theta, trial.bits, trial.anim);
const q = quad(480 + trial.dx, 360 + trial.dy, trial.d, trial.tilt, trial.axis, trial.dist || 3.5);
sctx.drawImage(warp(A, q, 960, 720), 0, 0);
}
cctx.filter = `blur(${trial.blur}px) contrast(${trial.contrast}) brightness(${trial.bright})`; cctx.filter = `blur(${trial.blur}px) contrast(${trial.contrast}) brightness(${trial.bright})`;
cctx.drawImage(B, 0, 0); cctx.drawImage(scene, 0, 0);
cctx.filter = "none"; cctx.filter = "none";
if (trial.noise) { if (trial.noise) {
const id = cctx.getImageData(0, 0, 960, 720); const id = cctx.getImageData(0, 0, 960, 720);
for (let i = 0; i < id.data.length; i += 4) { const n = (Math.random() - 0.5) * 2 * trial.noise; id.data[i] += n; id.data[i + 1] += n; id.data[i + 2] += n; } for (let i = 0; i < id.data.length; i += 4) { const n = (rnd() - 0.5) * 2 * trial.noise; id.data[i] += n; id.data[i + 1] += n; id.data[i + 2] += n; }
cctx.putImageData(id, 0, 0); cctx.putImageData(id, 0, 0);
} }
const t0 = performance.now(); const t0 = performance.now();
let res = null, qr = false; const d = decodeFrame(grayOf(cctx.getImageData(0, 0, 960, 720)));
try { res = await QrScanner.scanImage(C, { qrEngine: engine, returnDetailedScanResult: true }); qr = true; } catch { /* no qr */ } const out = { found: d.found, token: d.token, score: d.score == null ? null : +d.score.toFixed(3), ms: Math.round(performance.now() - t0) };
let out = { qr, token: null, score: null }; out.ok = trial.nocode ? !d.token : d.token === trial.token;
if (res) { if (d.bits && !trial.nocode) {
const d = decode(grayOf(cctx.getImageData(0, 0, 960, 720)), res.cornerPoints); const truth = trial.bits.slice(24);
if (d) { let k = 0; out.errs = [];
out = { qr, token: d.token, score: +d.score.toFixed(3), scale: d.scale }; for (const n of [28, 32, 36]) { let e = 0; for (let j = 0; j < n; j++) e += d.bits[k + j] !== truth[k + j]; out.errs.push(e); k += n; }
if (d.bits) {
const truth = trial.bits.slice(24);
let k = 0; out.errs = [];
for (const n of [28, 32, 36]) { let e = 0; for (let j = 0; j < n; j++) e += d.bits[k + j] !== truth[k + j]; out.errs.push(e); k += n; }
}
}
} }
// same decode with the exact qr corners, to tell corner error from decoder bugs
{
const Hq = homography(q.map(([x, y]) => ({ x, y })));
const hs = side / 2 / A.width;
const tc = [[-hs, -hs], [hs, -hs], [hs, hs], [-hs, hs]].map(([u, v]) => { const [x, y] = Hq(u, v); return { x, y }; });
const dt = decode(grayOf(cctx.getImageData(0, 0, 960, 720)), tc);
out.truthOk = !!dt && dt.token === trial.token;
if (res) out.cornerErr = +Math.max(...res.cornerPoints.map((p, i) => Math.hypot(p.x - tc[i].x, p.y - tc[i].y))).toFixed(2);
}
out.ms = Math.round(performance.now() - t0);
out.ok = out.token === trial.token;
results.push({ ...trial, bits: undefined, ...out }); results.push({ ...trial, bits: undefined, ...out });
if (cfg.keep && results.length <= cfg.keep) results[results.length - 1].png = C.toDataURL("image/jpeg", 0.8); if (cfg.keep && results.length <= cfg.keep) results[results.length - 1].png = C.toDataURL("image/jpeg", 0.8);
} }
return results; return results;
}; };
window.debugOne = (trial) => {
const A = document.createElement("canvas"); A.width = A.height = 800;
const actx = A.getContext("2d");
render(actx, 400, 400, 800 / (2 * DISC), trial.theta, trial.bits, trial.anim);
const q = quad(480, 360, trial.d, trial.tilt, trial.axis);
const scene = document.createElement("canvas"); scene.width = 960; scene.height = 720;
const sctx = scene.getContext("2d", { willReadFrequently: true });
sctx.fillStyle = "#555"; sctx.fillRect(0, 0, 960, 720);
sctx.drawImage(warp(A, q, 960, 720), 0, 0);
const img = grayOf(sctx.getImageData(0, 0, 960, 720));
const cands = locate(img);
const out = cands.map((c) => { const r = decodeAt(img, c, trial.opts || {}); return { cx: c.cx, cy: c.cy, A: c.A.map((v) => +v.toFixed(1)), r, proj: JSON.parse(JSON.stringify(RC.lastProjective)) }; });
// truth: code space -> A canvas -> quad (forward homography solved from the 4 corner pairs)
const src = [[0, 0], [800, 0], [800, 800], [0, 800]];
const M = [], V = [];
for (let i = 0; i < 4; i++) { const [x, y] = src[i], [u, v] = q[i]; M.push([x, y, 1, 0, 0, 0, -u * x, -u * y]); V.push(u); M.push([0, 0, 0, x, y, 1, -v * x, -v * y]); V.push(v); }
for (let i = 0; i < 8; i++) { let p = i; for (let r = i + 1; r < 8; r++) if (Math.abs(M[r][i]) > Math.abs(M[p][i])) p = r; [M[i], M[p]] = [M[p], M[i]]; [V[i], V[p]] = [V[p], V[i]]; for (let r = 0; r < 8; r++) if (r !== i) { const f = M[r][i] / M[i][i]; for (let k = i; k < 8; k++) M[r][k] -= f * M[i][k]; V[r] -= f * V[i]; } }
const h = V.map((v, i) => v / M[i][i]);
const unit = 800 / (2 * DISC);
const truth = (x, y) => { const X = 400 + x * unit, Y = 400 + y * unit, w = h[6] * X + h[7] * Y + 1; return [(h[0] * X + h[1] * Y + h[2]) / w, (h[3] * X + h[4] * Y + h[5]) / w]; };
// compare: the mapping is only defined up to a rotation, so compare radii from the true center
RC.decodeAt(img, cands[1], {});
const pm = RC.lastProjective && RC.lastProjective.map;
const cTrue = truth(0, 0), cEst = pm ? pm(0, 0) : null;
const radial = [];
if (pm) for (const R of [0.62, 0.9, 1.35]) for (let k = 0; k < 8; k++) {
const a = k * Math.PI / 4;
// true image radius along that image direction vs estimated: sample the estimated point and find its true code radius
const [ex, ey] = pm(R * Math.sin(a), -R * Math.cos(a));
// invert truth numerically: search code point mapping to (ex, ey)
let best = null;
for (let rr = R - 0.15; rr <= R + 0.15; rr += 0.002) for (let aa = 0; aa < 2 * Math.PI; aa += 0.01) { const [tx, ty] = truth(rr * Math.sin(aa), -rr * Math.cos(aa)); const d = (tx - ex) ** 2 + (ty - ey) ** 2; if (!best || d < best.d) best = { d, rr }; }
radial.push(+(best.rr - R).toFixed(3));
}
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; window.benchReady = true;
</script></head> </script></head>
<body></body></html> <body></body></html>
+2 -2
View File
@@ -9,8 +9,8 @@
<div class="grid"> <div class="grid">
<div>Images analysées<b id="frames">0</b></div> <div>Images analysées<b id="frames">0</b></div>
<div>Images par seconde<b id="fps">0</b></div> <div>Images par seconde<b id="fps">0</b></div>
<div>QR central détecté<b id="qr">0 %</b></div> <div>Disque central repéré<b id="qr">0 %</b></div>
<div>Anneaux lus (si QR vu)<b id="ring">0 %</b></div> <div>Images lues<b id="ring">0 %</b></div>
<div>Codes distincts<b id="count">0 / 5</b></div> <div>Codes distincts<b id="count">0 / 5</b></div>
<div>Mode vu<b id="mode">aucun</b></div> <div>Mode vu<b id="mode">aucun</b></div>
</div> </div>
+11 -14
View File
@@ -1,4 +1,4 @@
import { decode, grayOf } from "/static/js/ringcode.js"; import { decodeFrame, grayOf } from "/static/js/ringcode.js";
const $ = (id) => document.getElementById(id); const $ = (id) => document.getElementById(id);
const video = $("v"), canvas = document.createElement("canvas"), ctx = canvas.getContext("2d", { willReadFrequently: true }); const video = $("v"), canvas = document.createElement("canvas"), ctx = canvas.getContext("2d", { willReadFrequently: true });
@@ -31,18 +31,15 @@ async function loop() {
canvas.height = Math.round(video.videoHeight * k); canvas.height = Math.round(video.videoHeight * k);
ctx.drawImage(video, 0, 0, canvas.width, canvas.height); ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
frames++; fpsN++; frames++; fpsN++;
let res = null; const img = grayOf(ctx.getImageData(0, 0, canvas.width, canvas.height));
try { res = await QrScanner.scanImage(canvas, { qrEngine: engine, returnDetailedScanResult: true }); } catch { /* none */ } const d = decodeFrame(img);
if (res) { if (d.found) qr++;
qr++; if (d.token) { ring++; mode = "anneaux"; tokens.add(d.token); }
if (res.data.includes("#")) { else if (mode !== "anneaux") {
mode = "QR classique"; // reference mode: the classic rotating qr
tokens.add(res.data.split("#")[1]); let res = null;
} else { try { res = await QrScanner.scanImage(canvas, { qrEngine: engine, returnDetailedScanResult: true }); } catch { /* none */ }
mode = "anneaux"; if (res && res.data.includes("#")) { mode = "QR classique"; tokens.add(res.data.split("#")[1]); }
const d = decode(grayOf(ctx.getImageData(0, 0, canvas.width, canvas.height)), res.cornerPoints);
if (d && d.token) { ring++; tokens.add(d.token); }
}
} }
if (tokens.size >= 5 && t0) { if (tokens.size >= 5 && t0) {
const s = (performance.now() - t0) / 1000; const s = (performance.now() - t0) / 1000;
@@ -55,7 +52,7 @@ async function loop() {
if (now - fpsT > 1000) { $("fps").textContent = (fpsN * 1000 / (now - fpsT)).toFixed(1); fpsT = now; fpsN = 0; } if (now - fpsT > 1000) { $("fps").textContent = (fpsN * 1000 / (now - fpsT)).toFixed(1); fpsT = now; fpsN = 0; }
$("frames").textContent = frames; $("frames").textContent = frames;
$("qr").textContent = `${Math.round((100 * qr) / Math.max(1, frames))} %`; $("qr").textContent = `${Math.round((100 * qr) / Math.max(1, frames))} %`;
$("ring").textContent = mode === "anneaux" ? `${Math.round((100 * ring) / Math.max(1, qr))} %` : "–"; $("ring").textContent = `${Math.round((100 * ring) / Math.max(1, frames))} %`;
$("count").textContent = `${Math.min(tokens.size, 5)} / 5`; $("count").textContent = `${Math.min(tokens.size, 5)} / 5`;
$("mode").textContent = mode; $("mode").textContent = mode;
} }
+1 -1
View File
@@ -29,7 +29,7 @@ function frame(t) {
const size = Math.min(w, h) * 0.9; const size = Math.min(w, h) * 0.9;
if (MODE === "ring") { if (MODE === "ring") {
// one full turn every 45 s // one full turn every 45 s
render(ctx, w / 2, h / 2, size / (2 * DISC), (t / 1000) * (2 * Math.PI / 45), bits, lab.center); render(ctx, w / 2, h / 2, size / (2 * DISC), (t / 1000) * (2 * Math.PI / 45), bits, t / 1000);
} else { } else {
const m = lab.classic[idx].modules, n = m.length, s = Math.floor(size / (n + 8)); const m = lab.classic[idx].modules, n = m.length, s = Math.floor(size / (n + 8));
const x0 = (w - n * s) / 2, y0 = (h - n * s) / 2; const x0 = (w - n * s) / 2, y0 = (h - n * s) / 2;
+183
View File
@@ -0,0 +1,183 @@
"""tiny chrome devtools protocol client: headless chrome, pages, eval, screencast"""
import asyncio
import base64
import itertools
import json
import os
import shutil
import subprocess
import tempfile
import time
import urllib.request
import websockets
CHROME = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
class Browser:
def __init__(self, port=9333):
self.port = port
self.ids = itertools.count(1)
self.pending = {}
self.listeners = {}
async def start(self):
self.profile = tempfile.mkdtemp(prefix="rv-chrome-")
self.proc = subprocess.Popen([
CHROME, "--headless=new", f"--remote-debugging-port={self.port}", f"--user-data-dir={self.profile}",
"--no-first-run", "--no-default-browser-check", "--hide-scrollbars", "--mute-audio",
"--disable-background-timer-throttling", "--disable-renderer-backgrounding",
"--disable-backgrounding-occluded-windows", "--use-fake-ui-for-media-stream",
"--force-color-profile=srgb", "--window-size=1920,1080", "about:blank",
], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
for _ in range(100):
try:
info = json.load(urllib.request.urlopen(f"http://127.0.0.1:{self.port}/json/version"))
break
except OSError:
await asyncio.sleep(0.1)
self.ws = await websockets.connect(info["webSocketDebuggerUrl"], max_size=None)
self.reader = asyncio.create_task(self._read())
async def _read(self):
async for raw in self.ws:
m = json.loads(raw)
if "id" in m:
fut = self.pending.pop(m["id"], None)
if fut and not fut.done():
if "error" in m:
fut.set_exception(RuntimeError(m["error"]))
else:
fut.set_result(m.get("result", {}))
else:
cb = self.listeners.get(m.get("sessionId"))
if cb:
cb(m["method"], m.get("params", {}))
async def send(self, method, params=None, session=None):
i = next(self.ids)
fut = asyncio.get_running_loop().create_future()
self.pending[i] = fut
msg = {"id": i, "method": method, "params": params or {}}
if session:
msg["sessionId"] = session
await self.ws.send(json.dumps(msg))
return await asyncio.wait_for(fut, 60)
async def page(self, width, height, dsf=1, mobile=False):
tid = (await self.send("Target.createTarget", {"url": "about:blank", "newWindow": True}))["targetId"]
sid = (await self.send("Target.attachToTarget", {"targetId": tid, "flatten": True}))["sessionId"]
p = Page(self, sid, width, height, dsf)
self.listeners[sid] = p._event
for m in ("Page.enable", "Runtime.enable"):
await p.send(m)
await p.send("Page.setBypassCSP", {"enabled": True})
await p.send("Emulation.setFocusEmulationEnabled", {"enabled": True})
await p.send("Emulation.setDeviceMetricsOverride",
{"width": width, "height": height, "deviceScaleFactor": dsf, "mobile": mobile})
if mobile:
await p.send("Emulation.setTouchEmulationEnabled", {"enabled": True, "maxTouchPoints": 5})
return p
async def close(self):
try:
await asyncio.wait_for(self.send("Browser.close"), 5)
except Exception:
pass
try:
self.proc.wait(5)
except Exception:
self.proc.kill()
shutil.rmtree(self.profile, ignore_errors=True)
class Page:
def __init__(self, browser, sid, w, h, dsf):
self.b, self.sid, self.w, self.h, self.dsf = browser, sid, w, h, dsf
self.load = None
self.frames = None
def send(self, method, params=None):
return self.b.send(method, params, self.sid)
def _event(self, method, params):
if method == "Page.loadEventFired" and self.load and not self.load.done():
self.load.set_result(True)
elif method == "Page.screencastFrame":
if self.frames is not None:
ts = params["metadata"].get("timestamp", time.time())
path = os.path.join(self.frame_dir, f"{len(self.frames):06d}.jpg")
with open(path, "wb") as f:
f.write(base64.b64decode(params["data"]))
self.frames.append((ts, path))
asyncio.get_running_loop().create_task(
self.send("Page.screencastFrameAck", {"sessionId": params["sessionId"]}))
async def goto(self, url):
self.load = asyncio.get_running_loop().create_future()
await self.send("Page.navigate", {"url": url})
await asyncio.wait_for(self.load, 20)
async def js(self, expr):
r = await self.send("Runtime.evaluate", {"expression": expr, "awaitPromise": True, "returnByValue": True})
if "exceptionDetails" in r:
raise RuntimeError(r["exceptionDetails"].get("exception", {}).get("description", r["exceptionDetails"]))
return r.get("result", {}).get("value")
async def on_new_document(self, source):
await self.send("Page.addScriptToEvaluateOnNewDocument", {"source": source})
async def record(self, frame_dir):
os.makedirs(frame_dir, exist_ok=True)
self.frame_dir = frame_dir
self.frames = []
await self.send("Page.startScreencast", {"format": "jpeg", "quality": 90,
"maxWidth": int(self.w * self.dsf), "maxHeight": int(self.h * self.dsf)})
async def stop(self):
if getattr(self, "shooter", None):
self.shooting = False
try:
await asyncio.wait_for(self.shooter, 3)
except Exception:
self.shooter.cancel()
else:
try:
await asyncio.wait_for(self.send("Page.stopScreencast"), 3)
except Exception:
pass
async def record_shots(self, frame_dir, fps=24):
"""screenshot polling: slower than screencast but honours deviceScaleFactor"""
os.makedirs(frame_dir, exist_ok=True)
self.frames, self.shooting = [], True
async def loop():
while self.shooting:
t = time.time()
r = await self.send("Page.captureScreenshot", {"format": "jpeg", "quality": 90})
path = os.path.join(frame_dir, f"{len(self.frames):06d}.jpg")
with open(path, "wb") as f:
f.write(base64.b64decode(r["data"]))
self.frames.append((t, path))
await asyncio.sleep(max(0, 1 / fps - (time.time() - t)))
self.shooter = asyncio.get_running_loop().create_task(loop())
async def png(self, path, transparent=False):
if transparent:
await self.send("Emulation.setDefaultBackgroundColorOverride", {"color": {"r": 0, "g": 0, "b": 0, "a": 0}})
r = await self.send("Page.captureScreenshot", {"format": "png"})
with open(path, "wb") as f:
f.write(base64.b64decode(r["data"]))
async def mouse(self, kind, x, y, button="left", clicks=1):
await self.send("Input.dispatchMouseEvent",
{"type": kind, "x": x, "y": y, "button": button, "clickCount": clicks})
async def type(self, text, rng, target="document.activeElement"):
# write into the field directly: focus can drift between headless targets while screenshotting
await self.js(f"window.__tt = {target}; __tt.focus()")
for ch in text:
await self.js("__tt.value += " + json.dumps(ch) + "; __tt.dispatchEvent(new Event('input', {bubbles: true}))")
await asyncio.sleep(rng.uniform(0.05, 0.14) + (0.18 if ch == " " and rng.random() < 0.2 else 0))
+96
View File
@@ -0,0 +1,96 @@
"""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]"""
import asyncio
import base64
import collections
import itertools
import json
import os
import random
import subprocess
import sys
from pathlib import Path
import httpx
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
sys.path.insert(0, str(ROOT / "tools"))
from cdp import Browser # noqa: E402
from rotatyvote import ringcode # noqa: E402
PORT = 8200
rng = random.Random(11)
def trials(n):
out = []
grid = itertools.product([560, 420, 320, 250, 200], [0, 20, 35], [0, 1.2, 2.2], [(1.0, 1.0), (0.55, 1.12)])
for d, tilt, blur, (contrast, bright) in grid:
for _ in range(n):
secret, slot = rng.randbytes(32), rng.randrange(1 << 36)
out.append({"d": d, "tilt": tilt, "axis": rng.uniform(0, 360), "blur": blur, "contrast": contrast,
"bright": bright, "noise": 7, "dx": rng.uniform(-80, 80), "dy": rng.uniform(-50, 50),
"theta": rng.uniform(0, 6.283), "anim": rng.uniform(0, 100),
"bits": ringcode.render_bits(secret, "abcdefgh", 1000, slot),
"token": ringcode.token(secret, "abcdefgh", 1000, slot)})
# harsh perspective (phone very close to the screen), for information
for _ in range(n * 6):
secret, slot = rng.randbytes(32), rng.randrange(1 << 36)
out.append({"d": 420, "tilt": 25, "axis": rng.uniform(0, 360), "blur": 0.6, "contrast": 1, "bright": 1, "noise": 7,
"dx": 0, "dy": 0, "theta": rng.uniform(0, 6.283), "anim": rng.uniform(0, 100), "dist": 1.6, "harsh": True,
"bits": ringcode.render_bits(secret, "abcdefgh", 1000, slot), "token": ringcode.token(secret, "abcdefgh", 1000, slot)})
for _ in range(40):
out.append({"nocode": True, "d": 0, "tilt": 0, "blur": rng.choice([0, 1.2]), "contrast": 1, "bright": 1, "noise": 7})
return out
async def main():
n = int(sys.argv[1]) if len(sys.argv) > 1 else 3
env = {**os.environ, "PORT": str(PORT), "HOST": "127.0.0.1", "DB_PATH": "/tmp/rv-bench.db"}
server = subprocess.Popen([sys.executable, "-m", "rotatyvote"], cwd=ROOT, env=env,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
try:
for _ in range(100):
try:
httpx.get(f"http://127.0.0.1:{PORT}/api/config", timeout=0.5)
break
except httpx.HTTPError:
await asyncio.sleep(0.1)
b = Browser(9336)
await b.start()
p = await b.page(960, 720)
await p.goto(f"http://127.0.0.1:{PORT}/static/ringlab/bench.html")
for _ in range(50):
if await p.js("!!window.benchReady"):
break
await asyncio.sleep(0.1)
ts = trials(n)
res = await p.js(f"runBench({json.dumps({'trials': ts, 'keep': 4})})")
harsh = [r for r in res if r.get("harsh")]
print(f"harsh perspective (close-up, 25 deg): {sum(r['ok'] for r in harsh)}/{len(harsh)}")
codes = [r for r in res if not r.get("nocode") and not r.get("harsh")]
for key in ("d", "tilt", "blur", "contrast"):
agg = collections.defaultdict(lambda: [0, 0, 0])
for r in codes:
a = agg[r[key]]
a[0] += 1; a[1] += (r["found"] or 0) > 0; a[2] += r["ok"]
print(f"{key:8s}", " ".join(f"{k}: ok {v[2]}/{v[0]}" for k, v in sorted(agg.items())))
ok = sum(r["ok"] for r in codes)
print(f"codes read {ok}/{len(codes)} ({100 * ok / len(codes):.0f} %), median {sorted(r['ms'] for r in codes)[len(codes) // 2]} ms/frame")
fails = [r for r in codes if not r["ok"]]
print("failures (d, tilt, blur, contrast, found, score, errs):",
[(r["d"], r["tilt"], r["blur"], r["contrast"], r["found"], r["score"], r.get("errs")) for r in fails[:16]])
wrong = [r for r in res if r["token"] and not r["ok"]]
print("false tokens:", len(wrong), "(no-code frames:", sum(1 for r in res if r.get("nocode")), ")")
out = ROOT / "tools" / "bench_out"
out.mkdir(exist_ok=True)
for i, r in enumerate(res[:4]):
if r.get("png"):
(out / f"sample_{i}.jpg").write_bytes(base64.b64decode(r["png"].split(",")[1]))
await b.close()
finally:
server.terminate()
asyncio.run(main())