@xprite/pixelate 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/deskew.js CHANGED
@@ -1,4 +1,4 @@
1
- import { neighbourSteps, stepOf } from "./color-step.js";
1
+ import { neighbourSteps, OPAQUE_STEPS, stepOf, TRANSLUCENT } from "./color-step.js";
2
2
  /**
3
3
  * Tilt estimation and straightening for pixel grids that were photographed, scanned or rotated a
4
4
  * little before they reached the importer. The tilt is the angle that makes the projection
@@ -49,13 +49,21 @@ function collectEdges(image) {
49
49
  let vertical = 0, horizontal = 0;
50
50
  for (let y = 0, p = 0; y < height; y++)
51
51
  for (let x = 0; x < width; x++, p++) {
52
- if (x + 1 < width && stepOf(right, data, p, 1) > EDGE_STEP) {
53
- flags[p] |= VERTICAL_EDGE;
54
- vertical++;
52
+ if (x + 1 < width) {
53
+ const rc = right[p];
54
+ const rStep = rc < TRANSLUCENT ? OPAQUE_STEPS[rc] : stepOf(right, data, p, 1);
55
+ if (rStep > EDGE_STEP) {
56
+ flags[p] |= VERTICAL_EDGE;
57
+ vertical++;
58
+ }
55
59
  }
56
- if (y + 1 < height && stepOf(down, data, p, width) > EDGE_STEP) {
57
- flags[p] |= HORIZONTAL_EDGE;
58
- horizontal++;
60
+ if (y + 1 < height) {
61
+ const dc = down[p];
62
+ const dStep = dc < TRANSLUCENT ? OPAQUE_STEPS[dc] : stepOf(down, data, p, width);
63
+ if (dStep > EDGE_STEP) {
64
+ flags[p] |= HORIZONTAL_EDGE;
65
+ horizontal++;
66
+ }
59
67
  }
60
68
  }
61
69
  return {
@@ -71,13 +79,18 @@ function sharpness(points, degrees, scale, bins, offset) {
71
79
  const cos = Math.cos(degrees * DEGREES) * scale, sin = Math.sin(degrees * DEGREES) * scale;
72
80
  const { vertical, horizontal } = points;
73
81
  // Vertical edges project on u = x cos + y sin, horizontal edges on v = -x sin + y cos.
82
+ // With offset = longest * scale and |degrees| <= MAX_TILT_DEGREES, projections are strictly >= 0.
74
83
  bins.fill(0);
75
- for (let i = 0; i < vertical.length; i += 2)
76
- bins[Math.floor(vertical[i] * cos + vertical[i + 1] * sin + offset)]++;
84
+ for (let i = 0, len = vertical.length; i < len; i += 2) {
85
+ const val = vertical[i] * cos + vertical[i + 1] * sin + offset;
86
+ bins[val >= 0 ? val | 0 : Math.floor(val)]++;
87
+ }
77
88
  let total = squaredCounts(bins);
78
89
  bins.fill(0);
79
- for (let i = 0; i < horizontal.length; i += 2)
80
- bins[Math.floor(-horizontal[i] * sin + horizontal[i + 1] * cos + offset)]++;
90
+ for (let i = 0, len = horizontal.length; i < len; i += 2) {
91
+ const val = -horizontal[i] * sin + horizontal[i + 1] * cos + offset;
92
+ bins[val >= 0 ? val | 0 : Math.floor(val)]++;
93
+ }
81
94
  total += squaredCounts(bins);
82
95
  return total / Math.max(1, (vertical.length + horizontal.length) / 2);
83
96
  }
@@ -117,15 +130,15 @@ function measureTilt(image) {
117
130
  return UPRIGHT;
118
131
  const bins = new Int32Array(Math.ceil(3 * longest) + 8);
119
132
  const offset = longest;
120
- const evaluate = (points, degrees, scale) => sharpness(points, degrees, scale, bins, offset * scale);
121
133
  // Coarse pass on a shrunken copy of the coordinates so the narrow peak is not stepped over.
122
134
  const coarseScale = Math.min(1, COARSE_SIZE / longest);
135
+ const coarseBins = coarseScale < 1 ? new Int32Array(Math.ceil(3 * longest * coarseScale) + 8) : bins;
123
136
  const coarsePoints = scaled(edges, coarseScale);
124
137
  let best = 0, bestScore = -Infinity;
125
138
  const scores = new Map();
126
139
  for (let step = -MAX_TILT_DEGREES / COARSE_STEP; step <= MAX_TILT_DEGREES / COARSE_STEP; step++) {
127
140
  const degrees = Math.round(step * COARSE_STEP * 1000) / 1000;
128
- const score = evaluate(coarsePoints, degrees, coarseScale);
141
+ const score = sharpness(coarsePoints, degrees, coarseScale, coarseBins, offset * coarseScale);
129
142
  scores.set(degrees, score);
130
143
  if (score > bestScore) {
131
144
  bestScore = score;
@@ -136,13 +149,13 @@ function measureTilt(image) {
136
149
  const fineStep = Math.max(0.005, Math.min(0.05, 1 / longest / DEGREES / 2));
137
150
  let fine = best, fineScore = -Infinity;
138
151
  for (let degrees = best - FINE_SPAN; degrees <= best + FINE_SPAN + 1e-9; degrees += fineStep) {
139
- const score = evaluate(edges, degrees, 1);
152
+ const score = sharpness(edges, degrees, 1, bins, offset);
140
153
  if (score > fineScore) {
141
154
  fineScore = score;
142
155
  fine = degrees;
143
156
  }
144
157
  }
145
- const upright = evaluate(edges, 0, 1);
158
+ const upright = sharpness(edges, 0, 1, bins, offset);
146
159
  const gain = upright > 0 ? fineScore / upright : 1;
147
160
  const angle = Math.round(fine * 1000) / 1000;
148
161
  if (Math.abs(angle) < MIN_TILT_DEGREES || gain < MIN_SHARPNESS_GAIN)
@@ -0,0 +1,12 @@
1
+ /**
2
+ * 1D Radix-2 Cooley-Tukey FFT autocorrelation for real signals.
3
+ *
4
+ * Computes the unnormalized linear autocorrelation R[lag] = sum_{i=0}^{n-1-lag} x[i] * x[i+lag]
5
+ * for lag = 0..maxLag in O(N log N) time where N = nextPow2(n + maxLag), matching the naive
6
+ * O(n * maxLag) inner product to floating-point precision (~1e-12).
7
+ */
8
+ /**
9
+ * Computes linear autocorrelation `out[lag] = sum_{i=0}^{n-1-lag} signal[i] * signal[i+lag]`
10
+ * for `0 <= lag <= maxLag`. Uses direct summation for small inputs where FFT overhead exceeds it.
11
+ */
12
+ export declare function linearAutocorrelation(signal: Float64Array, maxLag: number, out: Float64Array): void;
@@ -0,0 +1,116 @@
1
+ /**
2
+ * 1D Radix-2 Cooley-Tukey FFT autocorrelation for real signals.
3
+ *
4
+ * Computes the unnormalized linear autocorrelation R[lag] = sum_{i=0}^{n-1-lag} x[i] * x[i+lag]
5
+ * for lag = 0..maxLag in O(N log N) time where N = nextPow2(n + maxLag), matching the naive
6
+ * O(n * maxLag) inner product to floating-point precision (~1e-12).
7
+ */
8
+ const plans = new Map();
9
+ function getPlan(size) {
10
+ let plan = plans.get(size);
11
+ if (plan)
12
+ return plan;
13
+ const bits = Math.round(Math.log2(size));
14
+ const bitrev = new Uint32Array(size);
15
+ for (let i = 0; i < size; i++) {
16
+ let x = i;
17
+ let r = 0;
18
+ for (let b = 0; b < bits; b++) {
19
+ r = (r << 1) | (x & 1);
20
+ x >>= 1;
21
+ }
22
+ bitrev[i] = r;
23
+ }
24
+ const half = size >> 1;
25
+ const cos = new Float64Array(half);
26
+ const sin = new Float64Array(half);
27
+ const step = (-2 * Math.PI) / size;
28
+ for (let k = 0; k < half; k++) {
29
+ const angle = k * step;
30
+ cos[k] = Math.cos(angle);
31
+ sin[k] = Math.sin(angle);
32
+ }
33
+ plan = {
34
+ size,
35
+ bitrev,
36
+ cos,
37
+ sin,
38
+ re: new Float64Array(size),
39
+ im: new Float64Array(size),
40
+ };
41
+ plans.set(size, plan);
42
+ return plan;
43
+ }
44
+ function fftInPlace(plan, inverse) {
45
+ const { size, bitrev, cos, sin, re, im } = plan;
46
+ for (let i = 0; i < size; i++) {
47
+ const j = bitrev[i];
48
+ if (j > i) {
49
+ const tr = re[i];
50
+ re[i] = re[j];
51
+ re[j] = tr;
52
+ const ti = im[i];
53
+ im[i] = im[j];
54
+ im[j] = ti;
55
+ }
56
+ }
57
+ const sign = inverse ? -1 : 1;
58
+ for (let len = 2; len <= size; len <<= 1) {
59
+ const half = len >> 1;
60
+ const stride = size / len;
61
+ for (let start = 0; start < size; start += len) {
62
+ for (let k = 0, tw = 0; k < half; k++, tw += stride) {
63
+ const wr = cos[tw];
64
+ const wi = sign * sin[tw];
65
+ const u = start + k;
66
+ const v = u + half;
67
+ const vr = re[v] * wr - im[v] * wi;
68
+ const vi = re[v] * wi + im[v] * wr;
69
+ re[v] = re[u] - vr;
70
+ im[v] = im[u] - vi;
71
+ re[u] += vr;
72
+ im[u] += vi;
73
+ }
74
+ }
75
+ }
76
+ if (inverse) {
77
+ const inv = 1 / size;
78
+ for (let i = 0; i < size; i++) {
79
+ re[i] *= inv;
80
+ im[i] *= inv;
81
+ }
82
+ }
83
+ }
84
+ /**
85
+ * Computes linear autocorrelation `out[lag] = sum_{i=0}^{n-1-lag} signal[i] * signal[i+lag]`
86
+ * for `0 <= lag <= maxLag`. Uses direct summation for small inputs where FFT overhead exceeds it.
87
+ */
88
+ export function linearAutocorrelation(signal, maxLag, out) {
89
+ const n = signal.length;
90
+ if (n * (maxLag + 1) <= 8192) {
91
+ for (let lag = 0; lag <= maxLag; lag++) {
92
+ let s = 0;
93
+ for (let i = 0, end = n - lag; i < end; i++)
94
+ s += signal[i] * signal[i + lag];
95
+ out[lag] = s;
96
+ }
97
+ return;
98
+ }
99
+ let size = 1;
100
+ const needed = n + maxLag;
101
+ while (size < needed)
102
+ size <<= 1;
103
+ const plan = getPlan(size);
104
+ const { re, im } = plan;
105
+ re.set(signal);
106
+ re.fill(0, n);
107
+ im.fill(0);
108
+ fftInPlace(plan, false);
109
+ for (let i = 0; i < size; i++) {
110
+ re[i] = re[i] * re[i] + im[i] * im[i];
111
+ im[i] = 0;
112
+ }
113
+ fftInPlace(plan, true);
114
+ for (let lag = 0; lag <= maxLag; lag++)
115
+ out[lag] = re[lag];
116
+ }
@@ -37,12 +37,20 @@ export declare class GridEvidenceReader {
37
37
  private readonly described;
38
38
  private readonly strips;
39
39
  private readonly pixels;
40
+ private readonly placedReadings;
40
41
  private readonly readings;
41
42
  constructor(image: PixelBuffer);
43
+ private admit;
44
+ private toEvidence;
42
45
  read(grids: readonly PixelGridAnalysis[]): {
43
46
  readings: GridEvidence[];
44
47
  pixels: number;
45
48
  };
49
+ /**
50
+ * Two-pass arbitration: evaluate cheap placed readings first to tighten passthrough and global
51
+ * score bounds before running expensive strip-shift / phase-field / chance-evidence searches.
52
+ */
53
+ arbitrate(grids: readonly PixelGridAnalysis[]): ArbitratedGrid | null;
46
54
  }
47
55
  /**
48
56
  * The best-scoring grid among the proposals, or null when the passthrough scores lower. The
@@ -190,9 +190,9 @@ function shiftedReadings(strips, cutsX, cutsY) {
190
190
  ];
191
191
  });
192
192
  }
193
- function readingOf(strips, described, grid, cutsX, cutsY, shifted) {
193
+ function unshiftedReadingOf(strips, described, grid, cutsX, cutsY) {
194
194
  const placed = placedReading(strips.image, described, grid, cutsX, cutsY);
195
- let best = {
195
+ return {
196
196
  cuts: placed.cuts,
197
197
  length: placed.length,
198
198
  twin: descriptionLength(described, placed.twin()),
@@ -200,6 +200,10 @@ function readingOf(strips, described, grid, cutsX, cutsY, shifted) {
200
200
  frame: () => described,
201
201
  sampling: strips.image.sampling,
202
202
  };
203
+ }
204
+ function applyShiftedReadings(base, grid, cutsX, cutsY, shifted, bounds) {
205
+ let best = base;
206
+ let exact = true;
203
207
  const cuts = {
204
208
  cutsX,
205
209
  cutsY,
@@ -220,25 +224,49 @@ function readingOf(strips, described, grid, cutsX, cutsY, shifted) {
220
224
  const optimistic = phaseScore(reading), incumbent = phaseScore(best);
221
225
  if (optimistic >= incumbent)
222
226
  continue;
227
+ // When called from arbitrateGrids: if this reading can neither lower passthrough nor beat the
228
+ // best known global score even with zero chance evidence, skip measuring chance evidence.
229
+ if (bounds && reading.length >= bounds.passthrough && optimistic >= bounds.score) {
230
+ exact = false;
231
+ continue;
232
+ }
223
233
  const canBound = Number.isFinite(reading.length) &&
224
234
  Number.isFinite(reading.twin) &&
225
235
  Number.isFinite(optimistic) &&
226
236
  Number.isFinite(incumbent);
237
+ const globalCanBound = canBound &&
238
+ bounds !== undefined &&
239
+ reading.length >= bounds.passthrough &&
240
+ Number.isFinite(bounds.score);
241
+ const effectiveCeiling = globalCanBound ? Math.min(incumbent, bounds.score) : incumbent;
227
242
  reading.chance = chance(canBound
228
243
  ? (lowerBound) => phaseScore({ length: reading.length, twin: reading.twin, chance: lowerBound }) >=
229
- incumbent
244
+ effectiveCeiling
230
245
  : undefined);
246
+ if (globalCanBound && reading.chance === Infinity && effectiveCeiling < incumbent)
247
+ exact = false;
231
248
  if (phaseScore(reading) < incumbent)
232
249
  best = reading;
233
250
  }
234
- return best;
251
+ return { reading: best, exact };
235
252
  }
253
+ /**
254
+ * When Pass 1 (placed readings) already finds a strongly phase-locked grid, non-coarser proposals
255
+ * that trail far behind do not need strip-shift / phase-field searches. Coarser proposals are
256
+ * always allowed to run shifted models because a drifted or block-reset grid can look locked at a
257
+ * finer octave before straightening.
258
+ */
259
+ const STRONG_PLACED_EVIDENCE = 0.2;
260
+ const STRONG_PLACED_MARGIN = 0.15;
261
+ const STRONG_PLACED_SHIFT_WINDOW = 0.3;
262
+ const COARSER_CELL_RATIO = 0.85;
236
263
  /** Reuse one evaluation view's descriptions and distinct readings during Auto's decision. */
237
264
  export class GridEvidenceReader {
238
265
  image;
239
266
  described;
240
267
  strips;
241
268
  pixels;
269
+ placedReadings = new Map();
242
270
  readings = new Map();
243
271
  constructor(image) {
244
272
  this.image = image;
@@ -246,11 +274,9 @@ export class GridEvidenceReader {
246
274
  this.strips = new StripImage(image);
247
275
  this.pixels = pixelLength(this.described);
248
276
  }
249
- read(grids) {
250
- const { image, described, strips } = this;
277
+ admit(grids) {
278
+ const { image } = this;
251
279
  const seen = new Set();
252
- const readings = [];
253
- // Admission is scoped to geometry; every model of admitted cuts is evaluated.
254
280
  const ordered = grids
255
281
  .map((grid) => {
256
282
  const { cutsX, cutsY } = cutsOf(image, grid);
@@ -265,17 +291,7 @@ export class GridEvidenceReader {
265
291
  a.grid.cellHeight - b.grid.cellHeight ||
266
292
  a.grid.offsetX - b.grid.offsetX ||
267
293
  a.grid.offsetY - b.grid.offsetY);
268
- // Only pending models of the same geometry need shared auxiliary descriptions. Release
269
- // those once both models are read; persistent readings retain only their winning frame.
270
- const pending = new Map();
271
- const corrections = new Map();
272
- for (const { geometry, key } of ordered) {
273
- if (this.readings.has(key))
274
- continue;
275
- const models = pending.get(geometry) ?? new Set();
276
- models.add(key);
277
- pending.set(geometry, models);
278
- }
294
+ const admitted = [];
279
295
  const admittedGeometries = new Set();
280
296
  let bestConfidence = -Infinity;
281
297
  for (const { grid, cutsX, cutsY, geometry, key } of ordered) {
@@ -286,14 +302,59 @@ export class GridEvidenceReader {
286
302
  continue;
287
303
  seen.add(key);
288
304
  if (!admittedGeometries.has(geometry) &&
289
- readings.length > 0 &&
305
+ admitted.length > 0 &&
290
306
  bestConfidence >= STRONG_GRID_CONFIDENCE &&
291
307
  bestConfidence - grid.confidence >= DISTINCT_GEOMETRY_CONFIDENCE_GAP)
292
308
  continue;
293
309
  admittedGeometries.add(geometry);
310
+ admitted.push({ grid, cutsX, cutsY, columns, rows, geometry, key });
311
+ bestConfidence = Math.max(bestConfidence, grid.confidence);
312
+ }
313
+ return admitted;
314
+ }
315
+ toEvidence(proposal, reading) {
316
+ const { grid, columns, rows } = proposal;
317
+ const { cuts, length, twin, chance, frame, sampling } = reading;
318
+ return {
319
+ grid: {
320
+ ...grid,
321
+ width: columns,
322
+ height: rows,
323
+ cutsX: [...cuts.cutsX],
324
+ cutsY: [...cuts.cutsY],
325
+ sampling,
326
+ },
327
+ length,
328
+ twin,
329
+ chance,
330
+ frame,
331
+ };
332
+ }
333
+ read(grids) {
334
+ const { described, strips } = this;
335
+ const admitted = this.admit(grids);
336
+ // Only pending models of the same geometry need shared auxiliary descriptions. Release
337
+ // those once both models are read; persistent readings retain only their winning frame.
338
+ const pending = new Map();
339
+ const corrections = new Map();
340
+ for (const { geometry, key } of admitted) {
341
+ if (this.readings.has(key))
342
+ continue;
343
+ const models = pending.get(geometry) ?? new Set();
344
+ models.add(key);
345
+ pending.set(geometry, models);
346
+ }
347
+ const readings = [];
348
+ for (const proposal of admitted) {
349
+ const { grid, cutsX, cutsY, geometry, key } = proposal;
294
350
  let reading = this.readings.get(key);
295
351
  if (!reading) {
296
- reading = readingOf(strips, described, grid, cutsX, cutsY, () => {
352
+ let base = this.placedReadings.get(key);
353
+ if (!base) {
354
+ base = unshiftedReadingOf(strips, described, grid, cutsX, cutsY);
355
+ this.placedReadings.set(key, base);
356
+ }
357
+ reading = applyShiftedReadings(base, grid, cutsX, cutsY, () => {
297
358
  if (grid.placed)
298
359
  return [];
299
360
  let shifted = corrections.get(geometry);
@@ -303,32 +364,151 @@ export class GridEvidenceReader {
303
364
  corrections.set(geometry, shifted);
304
365
  }
305
366
  return shifted;
306
- });
367
+ }).reading;
307
368
  this.readings.set(key, reading);
308
369
  const models = pending.get(geometry);
309
370
  models.delete(key);
310
371
  if (!models.size)
311
372
  corrections.delete(geometry);
312
373
  }
313
- const { cuts, length, twin, chance, frame, sampling } = reading;
314
- readings.push({
315
- grid: {
316
- ...grid,
317
- width: columns,
318
- height: rows,
319
- cutsX: [...cuts.cutsX],
320
- cutsY: [...cuts.cutsY],
321
- sampling,
322
- },
323
- length,
324
- twin,
325
- chance,
326
- frame,
327
- });
328
- bestConfidence = Math.max(bestConfidence, grid.confidence);
374
+ readings.push(this.toEvidence(proposal, reading));
329
375
  }
330
376
  return { readings, pixels: this.pixels };
331
377
  }
378
+ /**
379
+ * Two-pass arbitration: evaluate cheap placed readings first to tighten passthrough and global
380
+ * score bounds before running expensive strip-shift / phase-field / chance-evidence searches.
381
+ */
382
+ arbitrate(grids) {
383
+ const { described, strips } = this;
384
+ const admitted = this.admit(grids);
385
+ if (!admitted.length)
386
+ return null;
387
+ // Pass 1: placed readings (or cached full readings) for every admitted candidate.
388
+ const pass1 = [];
389
+ let passthrough = this.pixels;
390
+ for (const proposal of admitted) {
391
+ const { grid, cutsX, cutsY, key } = proposal;
392
+ const cached = this.readings.get(key);
393
+ if (cached) {
394
+ pass1.push({ proposal, reading: cached, complete: true });
395
+ passthrough = Math.min(passthrough, Math.max(cached.length, cached.twin - cached.chance));
396
+ continue;
397
+ }
398
+ let base = this.placedReadings.get(key);
399
+ if (!base) {
400
+ base = unshiftedReadingOf(strips, described, grid, cutsX, cutsY);
401
+ this.placedReadings.set(key, base);
402
+ }
403
+ const complete = !!grid.placed;
404
+ if (complete)
405
+ this.readings.set(key, base);
406
+ pass1.push({ proposal, reading: base, complete });
407
+ passthrough = Math.min(passthrough, Math.max(base.length, base.twin));
408
+ }
409
+ let bestPlaced = null;
410
+ let bestScore = passthrough - NULL_MARGIN;
411
+ for (const entry of [...pass1].sort((a, b) => phaseScore(a.reading) - phaseScore(b.reading))) {
412
+ const phase = phaseScore(entry.reading);
413
+ if (phase >= bestScore)
414
+ break;
415
+ const { cutsX, cutsY } = entry.reading.cuts;
416
+ const total = phase + octaveShortfall(entry.reading.frame(), cutsX, cutsY);
417
+ if (total < bestScore) {
418
+ bestPlaced = { proposal: entry.proposal, reading: entry.reading };
419
+ bestScore = total;
420
+ }
421
+ }
422
+ const strongPlaced = bestPlaced !== null &&
423
+ bestPlaced.reading.twin - bestPlaced.reading.length >= STRONG_PLACED_EVIDENCE &&
424
+ bestScore < passthrough - NULL_MARGIN - STRONG_PLACED_MARGIN;
425
+ // Pass 2: evaluate shifted models for candidates that can still compete.
426
+ // Under a strongly locked placed winner, keep at most the best placed candidate per
427
+ // (columns, rows) size within the shift window so duplicate offsets do not repeat shifts.
428
+ const bestPlacedKeyBySize = new Map();
429
+ if (strongPlaced) {
430
+ for (const entry of pass1) {
431
+ if (entry.complete)
432
+ continue;
433
+ const sizeKey = `${entry.proposal.columns}x${entry.proposal.rows}`;
434
+ const ps = phaseScore(entry.reading);
435
+ const prev = bestPlacedKeyBySize.get(sizeKey);
436
+ if (!prev || ps < prev.score)
437
+ bestPlacedKeyBySize.set(sizeKey, { key: entry.proposal.key, score: ps });
438
+ }
439
+ }
440
+ const pending = new Map();
441
+ const corrections = new Map();
442
+ const needShift = new Set();
443
+ for (const entry of pass1) {
444
+ if (entry.complete)
445
+ continue;
446
+ if (strongPlaced &&
447
+ entry.proposal.columns >= bestPlaced.proposal.columns * COARSER_CELL_RATIO &&
448
+ entry.proposal.rows >= bestPlaced.proposal.rows * COARSER_CELL_RATIO &&
449
+ (phaseScore(entry.reading) > bestScore + STRONG_PLACED_SHIFT_WINDOW ||
450
+ bestPlacedKeyBySize.get(`${entry.proposal.columns}x${entry.proposal.rows}`)?.key !==
451
+ entry.proposal.key))
452
+ continue;
453
+ const { geometry, key } = entry.proposal;
454
+ needShift.add(key);
455
+ const models = pending.get(geometry) ?? new Set();
456
+ models.add(key);
457
+ pending.set(geometry, models);
458
+ }
459
+ const bounds = { passthrough, score: bestScore };
460
+ const readings = [];
461
+ for (const entry of pass1) {
462
+ const { proposal } = entry;
463
+ let reading = entry.reading;
464
+ if (needShift.has(proposal.key)) {
465
+ const { grid, cutsX, cutsY, geometry, key } = proposal;
466
+ const result = applyShiftedReadings(reading, grid, cutsX, cutsY, () => {
467
+ let shifted = corrections.get(geometry);
468
+ if (!shifted) {
469
+ shifted = shiftedReadings(strips, cutsX, cutsY);
470
+ if (pending.get(geometry).size > 1)
471
+ corrections.set(geometry, shifted);
472
+ }
473
+ return shifted;
474
+ }, bounds);
475
+ reading = result.reading;
476
+ if (result.exact)
477
+ this.readings.set(key, reading);
478
+ const models = pending.get(geometry);
479
+ models.delete(key);
480
+ if (!models.size)
481
+ corrections.delete(geometry);
482
+ bounds.passthrough = Math.min(bounds.passthrough, Math.max(reading.length, reading.twin - reading.chance));
483
+ bounds.score = Math.min(bounds.score, bounds.passthrough - NULL_MARGIN);
484
+ }
485
+ readings.push(this.toEvidence(proposal, reading));
486
+ }
487
+ let finalPassthrough = this.pixels;
488
+ for (const reading of readings)
489
+ finalPassthrough = Math.min(finalPassthrough, Math.max(reading.length, reading.twin - reading.chance));
490
+ let best = null;
491
+ let score = finalPassthrough - NULL_MARGIN;
492
+ for (const reading of [...readings].sort((a, b) => phaseScore(a) - phaseScore(b))) {
493
+ const phase = phaseScore(reading);
494
+ if (phase >= score)
495
+ break;
496
+ const { cutsX, cutsY } = reading.grid;
497
+ const total = phase + octaveShortfall(reading.frame(), cutsX, cutsY);
498
+ if (total < score) {
499
+ best = reading;
500
+ score = total;
501
+ }
502
+ }
503
+ if (!best)
504
+ return null;
505
+ const share = Math.max(0, Math.min(1, (best.twin - best.length) / best.twin));
506
+ return {
507
+ grid: { ...best.grid, confidence: Math.max(best.grid.confidence, share), reliable: true },
508
+ length: best.length,
509
+ score,
510
+ };
511
+ }
332
512
  }
333
513
  /**
334
514
  * The best-scoring grid among the proposals, or null when the passthrough scores lower. The
@@ -336,31 +516,5 @@ export class GridEvidenceReader {
336
516
  * its phase saves.
337
517
  */
338
518
  export function arbitrateGrids(image, grids, evidence = new GridEvidenceReader(image)) {
339
- const { readings, pixels } = evidence.read(grids);
340
- let passthrough = pixels;
341
- for (const reading of readings)
342
- passthrough = Math.min(passthrough, Math.max(reading.length, reading.twin - reading.chance));
343
- let best = null;
344
- let score = passthrough - NULL_MARGIN;
345
- // The octave shortfall only adds to a score, so readings are checked best phase score first
346
- // and the search stops at the first that cannot win even without it.
347
- for (const reading of [...readings].sort((a, b) => phaseScore(a) - phaseScore(b))) {
348
- const phase = phaseScore(reading);
349
- if (phase >= score)
350
- break;
351
- const { cutsX, cutsY } = reading.grid;
352
- const total = phase + octaveShortfall(reading.frame(), cutsX, cutsY);
353
- if (total < score) {
354
- best = reading;
355
- score = total;
356
- }
357
- }
358
- if (!best)
359
- return null;
360
- const share = Math.max(0, Math.min(1, (best.twin - best.length) / best.twin));
361
- return {
362
- grid: { ...best.grid, confidence: Math.max(best.grid.confidence, share), reliable: true },
363
- length: best.length,
364
- score,
365
- };
519
+ return evidence.arbitrate(grids);
366
520
  }
@@ -1,3 +1,4 @@
1
+ import { imageStepProfiles } from "./grid-step-profiles.js";
1
2
  /**
2
3
  * A lattice whose cuts each moved to the strongest colour step within `radius` pixels: the cell
3
4
  * count of a regular grid with the cut positions of the raster that rounded it. A cut with no
@@ -5,48 +6,11 @@
5
6
  * where the cell before it stays within CELL_SPREAD of the pitch, so a strong edge inside a cell
6
7
  * (a highlight, an outline) cannot squeeze one cell and stretch the next.
7
8
  */
8
- const CHANNELS = 3;
9
- const STRIDE = 4;
10
- const ALPHA_CHANNEL = 3;
11
- const ALPHA_SCALE = 255;
12
9
  /** Share of a cell a cut may move. */
13
10
  const SNAP_SHARE = 0.25;
14
11
  /** Share of the pitch a snapped cell may differ from it. */
15
12
  const CELL_SPREAD = 0.25;
16
13
  const NO_STEP = -1;
17
- /**
18
- * Colour step between each pixel column (or row) and the one before it, summed along the line, on
19
- * premultiplied colour and alpha: a clear pixel's hidden colour (a removed background) is no edge.
20
- */
21
- function computeStepProfile(image, horizontal) {
22
- const { width, height, data } = image;
23
- const length = horizontal ? width : height;
24
- const profile = new Float64Array(length);
25
- for (let y = 0; y < height; y++)
26
- for (let x = 0; x < width; x++) {
27
- const along = horizontal ? x : y;
28
- if (along === 0)
29
- continue;
30
- const o = (y * width + x) * STRIDE;
31
- const p = horizontal ? o - STRIDE : o - width * STRIDE;
32
- const a = data[o + ALPHA_CHANNEL] / ALPHA_SCALE, b = data[p + ALPHA_CHANNEL] / ALPHA_SCALE;
33
- let step = Math.abs(data[o + ALPHA_CHANNEL] - data[p + ALPHA_CHANNEL]);
34
- for (let c = 0; c < CHANNELS; c++)
35
- step += Math.abs(data[o + c] * a - data[p + c] * b);
36
- profile[along] += step;
37
- }
38
- return profile;
39
- }
40
- /** Every reading of one image snaps against the same profiles. */
41
- const profiles = new WeakMap();
42
- function stepProfiles(image) {
43
- let cached = profiles.get(image);
44
- if (!cached) {
45
- cached = { x: computeStepProfile(image, true), y: computeStepProfile(image, false) };
46
- profiles.set(image, cached);
47
- }
48
- return cached;
49
- }
50
14
  function snapAxis(profile, cuts, avoid) {
51
15
  const cells = cuts.length - 1;
52
16
  const pitch = (cuts[cells] - cuts[0]) / cells;
@@ -69,7 +33,7 @@ function snapAxis(profile, cuts, avoid) {
69
33
  return { cuts: snapped, radius };
70
34
  }
71
35
  export function snapLatticeCuts(image, cutsX, cutsY, avoid = { x: [], y: [] }) {
72
- const profile = stepProfiles(image);
36
+ const profile = imageStepProfiles(image);
73
37
  return {
74
38
  x: snapAxis(profile.x, cutsX, avoid.x),
75
39
  y: snapAxis(profile.y, cutsY, avoid.y),