Ring locator: contrast ranking, all-round ink check; bench baseline switch

This commit is contained in:
2026-08-16 20:12:33 +01:00
parent e677e270fd
commit b314f01efc
6 changed files with 30 additions and 10 deletions
+14 -2
View File
@@ -351,6 +351,15 @@ function ringness(img, cand) {
const mean = rb.reduce((x, y) => x + y, 0) / rb.length, q = (G - mean) / span; const mean = rb.reduce((x, y) => x + y, 0) / rb.length, q = (G - mean) / span;
const dev = Math.sqrt(rb.reduce((x, y) => x + (y - mean) ** 2, 0) / rb.length) / span; const dev = Math.sqrt(rb.reduce((x, y) => x + (y - mean) ** 2, 0) / rb.length) / span;
if (q < 0.1 || q > 0.8 || dev < 0.1) return null; if (q < 0.1 || q > 0.8 || dev < 0.1) return null;
// dashes go all the way round: text or a line next to a dark disc only inks one side
for (let k = 0; k < 4; k++) {
let s = 0, g = 0;
for (let i = k * 48; i < (k + 1) * 48; i++) s += rb[i];
// against the gap of the same side, bands shift whole sides
for (let i = k * 6; i < (k + 1) * 6; i++) g += gp[i];
const qk = (g / 6 - s / 48) / span;
if (qk < 0.08 || qk > 0.85) return null;
}
return { span, black: D, white: G }; return { span, black: D, white: G };
} }
@@ -389,9 +398,10 @@ export function locate(img, opts = {}) {
const fit = 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 (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 >= 8) break;
} }
return out; // a projected code is the most contrasted thing around: dim look-alikes in the room go last
return out.sort((p, q) => q.span - p.span).slice(0, opts.max || 5);
} }
// the rough ellipse from the center disc is a bit off, and more so as the radius grows. // the rough ellipse from the center disc is a bit off, and more so as the radius grows.
@@ -775,6 +785,8 @@ function readRings(S, opts) {
} }
} }
coarse.sort((p, q) => q.score - p.score); coarse.sort((p, q) => q.score - p.score);
// nothing like the sync pattern at any angle: not a code, skip the fine search
if (coarse[0].score < 0.5) return { token: null, ...coarse[0], vals: undefined };
let best = null; let best = null;
for (const c of coarse.slice(0, 3)) { for (const c of coarse.slice(0, 3)) {
for (const ds of [-0.02, 0, 0.02]) for (let dt = -10; dt <= 10; dt++) { for (const ds of [-0.02, 0, 0.02]) for (let dt = -10; dt <= 10; dt++) {
+1 -1
View File
@@ -43,7 +43,7 @@ export function makeRingScanner(opts = {}) {
// plain bilinear at 3x reduction skips pixels and keeps the noise // plain bilinear at 3x reduction skips pixels and keeps the noise
wctx.imageSmoothingQuality = "high"; wctx.imageSmoothingQuality = "high";
wctx.drawImage(src, 0, 0, wide.width, wide.height); wctx.drawImage(src, 0, 0, wide.width, wide.height);
const cands = locate(grayOf(wctx.getImageData(0, 0, wide.width, wide.height)), { max: 3 }); const cands = locate(grayOf(wctx.getImageData(0, 0, wide.width, wide.height)), { max: 5 });
let last = null; let last = null;
for (const c of cands) { for (const c of cands) {
const d = readAt(src, sw, sh, { cx: (c.cx + 0.5) / k, cy: (c.cy + 0.5) / k, unit: c.r / CENTER / k, A: c.A.map((v) => v / k) }, now); const d = readAt(src, sw, sh, { cx: (c.cx + 0.5) / k, cy: (c.cy + 0.5) / k, unit: c.r / CENTER / k, A: c.A.map((v) => v / k) }, now);
+1 -1
View File
@@ -88,7 +88,7 @@ window.runBench = async (cfg) => {
clutter(sctx, 960, 720, rnd); clutter(sctx, 960, 720, rnd);
if (!trial.nocode) { if (!trial.nocode) {
actx.clearRect(0, 0, A.width, A.height); 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); (cfg.v1 ? V1.render : 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); 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); sctx.drawImage(warp(A, q, 960, 720), 0, 0);
} }
+3 -1
View File
@@ -1,6 +1,6 @@
// far / low contrast bench: stills with per-stage diagnosis, and timed sequences // far / low contrast bench: stills with per-stage diagnosis, and timed sequences
import * as RC from "/static/js/ringcode.js"; import * as RC from "/static/js/ringcode.js";
import { lcg, makeRoom, frame, jpeg } from "/static/ringlab/synth.js"; import { lcg, makeRoom, frame, jpeg, design } from "/static/ringlab/synth.js";
import * as V1 from "/static/ringlab/ringcode_v1.js"; import * as V1 from "/static/ringlab/ringcode_v1.js";
import { makeRingScanner } from "/static/js/ringscan.js"; import { makeRingScanner } from "/static/js/ringscan.js";
@@ -131,6 +131,7 @@ function toneLab(img, T, t) {
window.runFar = async (cfg) => { window.runFar = async (cfg) => {
const rnd = lcg(cfg.seed || 4242), results = []; const rnd = lcg(cfg.seed || 4242), results = [];
design.v1 = !!cfg.v1;
for (const t of cfg.trials) { for (const t of cfg.trials) {
const room = makeRoom(t.W, t.H, t.room, rnd); const room = makeRoom(t.W, t.H, t.room, rnd);
let f = frame(room, t, rnd); let f = frame(room, t, rnd);
@@ -157,6 +158,7 @@ window.runFar = async (cfg) => {
// seq: frame params + { fps, secs, interval, tokens: [{ bits, token }], shake } // seq: frame params + { fps, secs, interval, tokens: [{ bits, token }], shake }
window.runSeq = async (cfg) => { window.runSeq = async (cfg) => {
const rnd = lcg(cfg.seed || 777), results = []; const rnd = lcg(cfg.seed || 777), results = [];
design.v1 = !!cfg.v1;
for (const s of cfg.seqs) { for (const s of cfg.seqs) {
const room = makeRoom(s.W, s.H, s.room, rnd); const room = makeRoom(s.W, s.H, s.room, rnd);
const res = { ...s, tokens: undefined }; const res = { ...s, tokens: undefined };
+5 -1
View File
@@ -1,5 +1,9 @@
// synthetic camera frames of a projected ring code: a washed-out screen in a room, seen by a phone sensor // synthetic camera frames of a projected ring code: a washed-out screen in a room, seen by a phone sensor
import { render, DISC } from "/static/js/ringcode.js"; import { render, DISC } from "/static/js/ringcode.js";
import { render as renderV1 } from "/static/ringlab/ringcode_v1.js";
// v1: draw the code as it was before the far-reading work, for baselines
export const design = { v1: false };
export function lcg(seed) { export function lcg(seed) {
let s = (seed >>> 0) || 1; let s = (seed >>> 0) || 1;
@@ -51,7 +55,7 @@ function page(pw, ph, d, t, rnd) {
const ctx = c.getContext("2d", { willReadFrequently: true }); const ctx = c.getContext("2d", { willReadFrequently: true });
ctx.fillStyle = "#f5f6fa"; ctx.fillRect(0, 0, pw, ph); ctx.fillStyle = "#f5f6fa"; ctx.fillRect(0, 0, pw, ph);
const cx = pw * 0.36, cy = ph * 0.54, unit = (d / 2 / DISC); const cx = pw * 0.36, cy = ph * 0.54, unit = (d / 2 / DISC);
if (!t.nocode) render(ctx, cx, cy, unit, t.theta, t.bits, t.anim, t.fade || null); if (!t.nocode) (design.v1 ? renderV1 : render)(ctx, cx, cy, unit, t.theta, t.bits, t.anim, t.fade || null);
ctx.fillStyle = "#1c2036"; ctx.fillStyle = "#1c2036";
ctx.font = `700 ${d * 0.11}px system-ui`; ctx.fillText("Inscription", pw * 0.66, ph * 0.2); ctx.font = `700 ${d * 0.11}px system-ui`; ctx.fillText("Inscription", pw * 0.66, ph * 0.2);
ctx.font = `${d * 0.05}px system-ui`; ctx.font = `${d * 0.05}px system-ui`;
+6 -4
View File
@@ -1,6 +1,7 @@
"""ring code bench: renders codes with perspective, blur, washed contrast and clutter in headless chrome, """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] 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,scan DIAG=legacy|native NEG=300 CPU=6 (slow phone)""" env: SUITE=legacy,far,seq,neg (default all) PIPES=legacy,cap960,scan DIAG=legacy|native FAR_D=80,100 NEG=300
CPU=6 (slow phone) V1=1 (decoder and dash design from before the far-reading work, the baseline)"""
import asyncio import asyncio
import base64 import base64
import collections import collections
@@ -22,6 +23,7 @@ from cdp import Browser # noqa: E402
from rotatyvote import ringcode # noqa: E402 from rotatyvote import ringcode # noqa: E402
PORT = 8200 PORT = 8200
V1 = bool(os.environ.get("V1"))
rng = random.Random(11) rng = random.Random(11)
@@ -120,13 +122,13 @@ async def chunks(p, fn, key, items, cfg, size):
# cdp calls time out after 60 s # cdp calls time out after 60 s
out = [] out = []
for i in range(0, len(items), size): for i in range(0, len(items), size):
out += await p.js(f"{fn}({json.dumps({**cfg, key: items[i:i + size], 'seed': 1000 + i})})") out += await p.js(f"{fn}({json.dumps({**cfg, key: items[i:i + size], 'seed': 1000 + i, 'v1': V1})})")
return out return out
async def run_legacy(p, n): async def run_legacy(p, n):
ts = trials(n) ts = trials(n)
res = await p.js(f"runBench({json.dumps({'trials': ts, 'keep': 4, 'v1': bool(os.environ.get('V1'))})})") res = await p.js(f"runBench({json.dumps({'trials': ts, 'keep': 4, 'v1': V1})})")
harsh = [r for r in res if r.get("harsh")] 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)}") 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")] codes = [r for r in res if not r.get("nocode") and not r.get("harsh")]
@@ -212,7 +214,7 @@ async def run_seq(p, n, pipes):
async def main(): async def main():
n = int(sys.argv[1]) if len(sys.argv) > 1 else 3 n = int(sys.argv[1]) if len(sys.argv) > 1 else 3
suites = os.environ.get("SUITE", "legacy,far,seq,neg").split(",") suites = os.environ.get("SUITE", "legacy,far,seq,neg").split(",")
pipes = os.environ.get("PIPES", "legacy,scan").split(",") pipes = os.environ.get("PIPES", "legacy" if V1 else "scan").split(",")
env = {**os.environ, "PORT": str(PORT), "HOST": "127.0.0.1", "DB_PATH": "/tmp/rv-bench.db"} 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, server = subprocess.Popen([sys.executable, "-m", "rotatyvote"], cwd=ROOT, env=env,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)