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
+79 -39
View File
@@ -3,7 +3,8 @@
<head><meta charset="utf-8"><title>Ring code bench</title>
<script src="/static/vendor/qr-scanner.umd.min.js"></script>
<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)
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++) {
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);
return out;
}
// 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) {
const t = tilt * Math.PI / 180, a = axis * Math.PI / 180, f = 1.6 * d;
function quad(cx, cy, d, tilt, axis, dist = 3.5) {
// 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]) => {
// 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;
@@ -55,59 +57,97 @@ function quad(cx, cy, d, tilt, axis) {
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) => {
const engine = await QrScanner.createQrEngine();
QrScanner._disableBarcodeDetector = !!cfg.noBarcodeDetector;
let seed = 12345;
const rnd = () => ((seed = (seed * 1103515245 + 12345) & 0x7fffffff) / 0x7fffffff);
const results = [];
const A = document.createElement("canvas"); A.width = A.height = 800;
const actx = A.getContext("2d");
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 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.drawImage(B, 0, 0);
cctx.drawImage(scene, 0, 0);
cctx.filter = "none";
if (trial.noise) {
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);
}
const t0 = performance.now();
let res = null, qr = false;
try { res = await QrScanner.scanImage(C, { qrEngine: engine, returnDetailedScanResult: true }); qr = true; } catch { /* no qr */ }
let out = { qr, token: null, score: null };
if (res) {
const d = decode(grayOf(cctx.getImageData(0, 0, 960, 720)), res.cornerPoints);
if (d) {
out = { qr, token: d.token, score: +d.score.toFixed(3), scale: d.scale };
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; }
}
}
const d = decodeFrame(grayOf(cctx.getImageData(0, 0, 960, 720)));
const out = { found: d.found, token: d.token, score: d.score == null ? null : +d.score.toFixed(3), ms: Math.round(performance.now() - t0) };
out.ok = trial.nocode ? !d.token : d.token === trial.token;
if (d.bits && !trial.nocode) {
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 });
if (cfg.keep && results.length <= cfg.keep) results[results.length - 1].png = C.toDataURL("image/jpeg", 0.8);
}
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;
</script></head>
<body></body></html>
+2 -2
View File
@@ -9,8 +9,8 @@
<div class="grid">
<div>Images analysées<b id="frames">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>Anneaux lus (si QR vu)<b id="ring">0 %</b></div>
<div>Disque central repéré<b id="qr">0 %</b></div>
<div>Images lues<b id="ring">0 %</b></div>
<div>Codes distincts<b id="count">0 / 5</b></div>
<div>Mode vu<b id="mode">aucun</b></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 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);
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
frames++; fpsN++;
let res = null;
try { res = await QrScanner.scanImage(canvas, { qrEngine: engine, returnDetailedScanResult: true }); } catch { /* none */ }
if (res) {
qr++;
if (res.data.includes("#")) {
mode = "QR classique";
tokens.add(res.data.split("#")[1]);
} else {
mode = "anneaux";
const d = decode(grayOf(ctx.getImageData(0, 0, canvas.width, canvas.height)), res.cornerPoints);
if (d && d.token) { ring++; tokens.add(d.token); }
}
const img = grayOf(ctx.getImageData(0, 0, canvas.width, canvas.height));
const d = decodeFrame(img);
if (d.found) qr++;
if (d.token) { ring++; mode = "anneaux"; tokens.add(d.token); }
else if (mode !== "anneaux") {
// reference mode: the classic rotating qr
let res = null;
try { res = await QrScanner.scanImage(canvas, { qrEngine: engine, returnDetailedScanResult: true }); } catch { /* none */ }
if (res && res.data.includes("#")) { mode = "QR classique"; tokens.add(res.data.split("#")[1]); }
}
if (tokens.size >= 5 && t0) {
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; }
$("frames").textContent = 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`;
$("mode").textContent = mode;
}
+1 -1
View File
@@ -29,7 +29,7 @@ function frame(t) {
const size = Math.min(w, h) * 0.9;
if (MODE === "ring") {
// 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 {
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;