Accept a camera read only when three frames agree

One frame was enough to accept an ISBN, on the theory that the check
digit makes a false read unlikely. About one multi-digit misread in ten
still passes the check, and a single book put two phantom ISBNs in the
queue. A read now has to repeat on three consecutive frames (two in a
capture burst), and a frame that yields two different ISBNs is ignored.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-22 11:58:46 -07:00
1 parent a210576661
commit ddf6020731
5 files changed
+172 -22

No files matched your search

+27
View File
@@ -5,6 +5,8 @@ import { createRequire } from 'node:module';
import { prepareZXingModule, readBarcodes } from 'zxing-wasm/reader';
import { BASE, VARIANTS, toImageForTest, decodeLive, decodeThorough, newLiveState, rowAverage, sharpness, upscale } from './decode.ts';
import type { Pixels } from './decode.ts';
import { normalizeIsbn } from '../shared/isbn.ts';
import { acceptRead, newReadState } from './readstate.ts';
before(async () => {
const wasm = readFileSync(createRequire(import.meta.url).resolve('zxing-wasm/reader').replace(/dist[\\/].*$/, 'dist/reader/zxing_reader.wasm'));
@@ -118,3 +120,28 @@ test('decodeLive and decodeThorough return the ISBN of a readable frame', async
assert.equal(live.out.isbn, CODE);
assert.equal((await decodeThorough(p, null)).isbn, CODE);
});
// --- misreads: the phantom ISBNs ----------------------------------------------------------------------
test('the decoder only returns a 13-digit code whose check digit is right, but a blurred frame can misread two digits so that it still is', async () => {
const real = '9781937052898', phantom = '9781937041298';
// A noisy frame of the real barcode through the first live variant: the reader reports the real code and, as a
// second symbol, one with two digits off whose check digit (8) is still valid. Found by sweeping the synthetic seeds.
const v = VARIANTS[0]!;
const texts = (await readBarcodes(toImageForTest(render(real, 2, 19), v) as ImageData, { ...v.opts })).map(r => r.text);
assert.ok(texts.includes(phantom), texts.join(','));
assert.equal(normalizeIsbn(phantom), phantom); // it passes the check digit, so only agreement between frames can stop it
// Before agreement was required a single such frame was queued at once; now it is not.
assert.equal(acceptRead(newReadState(), phantom, 0).emit, null);
});
test('a barcode whose check digit is wrong is never turned into an ISBN, on any variant', async () => {
const bad = '9781937052899'; // real body, check digit 9 instead of 8
const p = render(bad, 3, 1);
assert.equal((await decodeLive(p, newLiveState())).out.isbn, null);
assert.equal((await decodeThorough(p, null)).isbn, null);
for (const v of VARIANTS) {
const r = await readBarcodes(toImageForTest(p, v) as ImageData, { ...v.opts, tryRotate: true });
assert.deepEqual(r.map(x => x.text).filter(t => t === '9781937052898'), [], v.name);
}
});
+7 -1
View File
@@ -107,11 +107,17 @@ export const WHOLE_VARIANTS: Variant[] = [
{ name: 'whole-rows', opts: { ...BASE, binarizer: 'GlobalHistogram' }, prep: g => sharpenAcross(rowAverage(g, 6), 1, 1) },
];
/**
* Only a 13-digit code that passes the check digit as printed counts as an ISBN; nothing is repaired or completed.
* Two different ISBNs in one picture of one barcode strip means one of them is a misread, so neither is trusted.
*/
function judge(codes: { text: string }[], into: DecodeOutcome): void {
const isbns = new Set<string>();
for (const c of codes) {
const isbn = /^\d{13}$/.test(c.text) ? normalizeIsbn(c.text) : null;
if (isbn) into.isbn ??= isbn; else into.other ??= c.text;
if (isbn) isbns.add(isbn); else into.other ??= c.text;
}
if (isbns.size === 1) into.isbn ??= [...isbns][0]!;
}
async function tryVariant(g: Grey, v: Variant, extra: ReaderOptions, into: DecodeOutcome): Promise<void> {
+98 -12
View File
@@ -1,28 +1,108 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { acceptRead, markEmitted, newReadState } from './readstate.ts';
import { acceptRead, agree, markEmitted, newReadState, AGREE_READS, AGREE_GAP_MS } from './readstate.ts';
import { normalizeIsbn } from '../shared/isbn.ts';
import type { ReadState } from './readstate.ts';
const ISBN = '9780306406157';
const REAL = '9781937052898';
// The phantoms seen in the queue: both pass the ISBN-13 check digit, neither is a real book.
const PHANTOM_1 = '9781037052897', PHANTOM_2 = '9781037042898';
test('a valid ISBN-13 is accepted on the first read', () => {
const r = acceptRead(newReadState(), ISBN, 0);
assert.equal(r.emit, ISBN);
assert.equal(r.reject, false);
/** Feed one code per frame, 100 ms apart; returns what was emitted and the final state. */
function frames(codes: string[], state: ReadState = newReadState(), t0 = 0): { emitted: string[]; state: ReadState } {
const emitted: string[] = [];
codes.forEach((code, i) => {
const r = acceptRead(state, code, t0 + i * 100);
state = r.state;
if (r.emit) emitted.push(r.emit);
});
return { emitted, state };
}
test('a clean ISBN-13 is emitted on its AGREE_READS-th agreeing frame, not before', () => {
assert.equal(AGREE_READS, 3);
let st = newReadState();
for (let i = 0; i < AGREE_READS - 1; i++) {
const r = acceptRead(st, ISBN, i * 100);
assert.equal(r.emit, null);
assert.equal(r.reject, false);
st = r.state;
}
assert.equal(acceptRead(st, ISBN, (AGREE_READS - 1) * 100).emit, ISBN);
});
test('a single stray read is ignored', () => {
const r = frames([PHANTOM_1]);
assert.deepEqual(r.emitted, []);
assert.deepEqual(frames([REAL, REAL, PHANTOM_1, REAL]).emitted, []);
});
test('the phantoms seen in the queue are not accepted, alone or around the real book', () => {
assert.deepEqual(frames([REAL, PHANTOM_1, REAL, PHANTOM_2, REAL, PHANTOM_1]).emitted, []);
assert.deepEqual(frames([PHANTOM_1, PHANTOM_2, PHANTOM_1, PHANTOM_2]).emitted, []);
// Held steady on the book with one wrong frame in the middle: the wrong frame costs a restart, nothing more.
assert.deepEqual(frames([REAL, REAL, PHANTOM_1, REAL, REAL, REAL]).emitted, [REAL]);
});
test('alternating reads are never accepted', () => {
const alt = Array.from({ length: 20 }, (_, i) => (i % 2 ? PHANTOM_2 : REAL));
assert.deepEqual(frames(alt).emitted, []);
});
test('empty frames in between do not reset the count, but a long gap does', () => {
let st = newReadState();
st = acceptRead(st, REAL, 0).state;
st = acceptRead(st, REAL, 500).state; // frames with no read happened in between
assert.equal(acceptRead(st, REAL, 1000).emit, REAL);
let late = acceptRead(newReadState(), REAL, 0).state;
late = acceptRead(late, REAL, AGREE_GAP_MS + 1).state; // too late to count as the second
assert.equal(acceptRead(late, REAL, AGREE_GAP_MS + 100).emit, null);
});
test('a rejected code (not an ISBN) in between does not disturb the count', () => {
const r = frames([REAL, '036000291452', REAL, REAL]);
assert.deepEqual(r.emitted, [REAL]);
});
test('agree() counts and resets on its own, with a custom requirement', () => {
let a = agree(newReadState(), REAL, 0, 2);
assert.equal(a.agreed, false);
a = agree(a.state, REAL, 100, 2);
assert.equal(a.agreed, true);
a = agree(newReadState(), REAL, 0, 2);
a = agree(a.state, PHANTOM_1, 100, 2);
a = agree(a.state, REAL, 200, 2);
assert.equal(a.agreed, false);
});
test('the same ISBN is not repeated within 5 s, then is again', () => {
let r = acceptRead(newReadState(), ISBN, 0);
r = acceptRead(r.state, ISBN, 150);
const first = frames([ISBN, ISBN, ISBN]);
assert.deepEqual(first.emitted, [ISBN]); // emitted at t = 200
let r = acceptRead(first.state, ISBN, 300);
assert.equal(r.emit, null);
assert.equal(r.reject, false);
r = acceptRead(r.state, ISBN, 4900);
assert.equal(r.emit, null);
r = acceptRead(r.state, ISBN, 5100);
assert.equal(r.emit, ISBN);
const again = frames([ISBN, ISBN, ISBN], r.state, 5300);
assert.deepEqual(again.emitted, [ISBN]);
});
test('a 979 ISBN is accepted', () => {
assert.equal(acceptRead(newReadState(), '9791034305261', 0).emit, '9791034305261');
test('a 979 ISBN is accepted once confirmed', () => {
assert.deepEqual(frames(Array(3).fill('9791034305261')).emitted, ['9791034305261']);
});
test('a check digit is verified, never computed: a wrong one rejects, however often it repeats', () => {
// Real body, wrong check digit (the real one is 8); and the 12-digit body alone (UPC-A reading of the same bars).
for (const code of ['9781937052899', '9781937052890', '978193705289']) {
const r = frames([code, code, code]);
assert.deepEqual(r.emitted, [], code);
assert.equal(acceptRead(newReadState(), code, 0).reject, true, code);
}
});
test('a 10-digit ISBN from a barcode is not converted to an ISBN-13', () => {
assert.equal(acceptRead(newReadState(), '0306406152', 0).reject, true);
});
test('a UPC-A rejects once per 5 s', () => {
@@ -41,8 +121,14 @@ test('a 13-digit code without a 978/979 prefix, or with a bad check digit, rejec
assert.equal(acceptRead(newReadState(), '9780306406158', 0).reject, true);
});
test('the phantom check digits are valid, which is why the check alone is not enough', () => {
assert.equal(normalizeIsbn(PHANTOM_1), PHANTOM_1);
assert.equal(normalizeIsbn(PHANTOM_2), PHANTOM_2);
assert.equal(normalizeIsbn('9781937052899'), null);
});
test('markEmitted silences the loop for 5 s', () => {
const s = markEmitted(newReadState(), ISBN, 1000);
assert.equal(acceptRead(s, ISBN, 2000).emit, null);
assert.equal(acceptRead(s, ISBN, 6100).emit, ISBN);
assert.deepEqual(frames([ISBN, ISBN, ISBN], s, 6100).emitted, [ISBN]);
});
+31 -6
View File
@@ -1,21 +1,44 @@
import { normalizeIsbn } from '../shared/isbn.ts';
export const REPEAT_MS = 5000;
/**
* A barcode read is only believed once the same full code has been decoded on this many separate frames, each
* within AGREE_GAP_MS of the one before. The EAN check digit alone is not enough: a blurred frame sometimes
* misreads two digits so that the check still passes (about one misread in ten), and the same wrong code can
* come up again on the next frame, so two agreeing reads are not safe. Three still land in about 0.3 s on a
* clean barcode.
*/
export const AGREE_READS = 3;
export const AGREE_GAP_MS = 1500;
/** Remembers when each code was last reported, so a barcode held in view is announced once per 5 seconds. */
export interface ReadState {
emittedAt: Record<string, number>;
rejectedAt: Record<string, number>;
/** The ISBN being confirmed: how many frames in a row have read it, and when the latest one did. */
seen: { isbn: string; count: number; at: number } | null;
}
export function newReadState(): ReadState {
return { emittedAt: {}, rejectedAt: {} };
return { emittedAt: {}, rejectedAt: {}, seen: null };
}
/**
* Judge one decoded barcode. A valid ISBN-13 (check digit, 978 or 979 prefix) is accepted at once, with no
* second confirming read: the EAN checksum already makes a false read very unlikely. Anything else
* (a UPC, a price code, a bad check digit) is rejected. Neither is repeated within REPEAT_MS.
* Count one frame's read of a valid ISBN. The count restarts when a different valid ISBN was read in between
* or the last agreeing read is older than AGREE_GAP_MS. `agreed` is true once `need` frames in a row agree.
*/
export function agree(state: ReadState, isbn: string, now: number, need: number = AGREE_READS): { state: ReadState; agreed: boolean } {
const s = state.seen;
const count = s && s.isbn === isbn && now - s.at <= AGREE_GAP_MS ? s.count + 1 : 1;
if (count >= need) return { state: { ...state, seen: null }, agreed: true };
return { state: { ...state, seen: { isbn, count, at: now } }, agreed: false };
}
/**
* Judge one decoded barcode, one call per frame. A 13-digit code with a correct check digit and a 978 or 979
* prefix counts toward AGREE_READS agreeing frames and is emitted on the last of them; the check digit is only
* ever verified, never computed. Anything else (a UPC, a price code, a bad check digit) is rejected. Neither is
* repeated within REPEAT_MS.
*/
export function acceptRead(
state: ReadState, code: string, now: number,
@@ -27,8 +50,10 @@ export function acceptRead(
return { state: { ...state, rejectedAt: { ...state.rejectedAt, [code]: now } }, emit: null, reject: true };
}
const last = state.emittedAt[isbn];
if (last !== undefined && now - last < REPEAT_MS) return { state, emit: null, reject: false };
return { state: { ...state, emittedAt: { ...state.emittedAt, [isbn]: now } }, emit: isbn, reject: false };
if (last !== undefined && now - last < REPEAT_MS) return { state: { ...state, seen: null }, emit: null, reject: false };
const a = agree(state, isbn, now);
if (!a.agreed) return { state: a.state, emit: null, reject: false };
return { state: { ...a.state, emittedAt: { ...a.state.emittedAt, [isbn]: now } }, emit: isbn, reject: false };
}
/** Record that an ISBN was just reported by some other path (the Capture button), so the loop stays quiet. */
+9 -3
View File
@@ -1,5 +1,5 @@
import { prepareZXingModule } from 'zxing-wasm/reader';
import { acceptRead, markEmitted, newReadState } from './readstate.ts';
import { acceptRead, agree, markEmitted, newReadState } from './readstate.ts';
import { cropRect } from './frame.ts';
import { decodeLive, decodeThorough, newLiveState, sharpness, wantsFull } from './decode.ts';
import type { DecodeOutcome, Pixels } from './decode.ts';
@@ -81,6 +81,7 @@ export interface Scanner {
const FRAME_FALLBACK_MS = 60;
const BURST_MS = 1500;
const BURST_AGREE_READS = 2;
/** Ask for the biggest picture the camera has; failures are ignored (the camera keeps what it gave). */
async function wantResolution(track: MediaStreamTrack | undefined): Promise<void> {
@@ -181,8 +182,13 @@ export async function startScanner(
const out = await decodeThorough(crop, full);
other ??= out.other;
if (out.isbn) {
state = markEmitted(state, out.isbn, Date.now());
return { isbn: out.isbn, other, saved: null };
// The same agreement rule as the live loop, a little looser (two frames) since the burst is short and was asked for.
const a = agree(state, out.isbn, Date.now(), BURST_AGREE_READS);
state = a.state;
if (a.agreed) {
state = markEmitted(state, out.isbn, Date.now());
return { isbn: out.isbn, other, saved: null };
}
}
}
if (other) return { isbn: null, other, saved: null };