tapirscan 1.2.0 → 1.2.2

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.
Files changed (62) hide show
  1. package/README.md +9 -10
  2. package/dist/index.d.ts +24 -29
  3. package/dist/index.js +64 -154
  4. package/dist/multiformat/format-registry.d.ts +26 -0
  5. package/dist/multiformat/format-registry.js +62 -0
  6. package/dist/multiformat/formats.d.ts +2 -24
  7. package/dist/multiformat/formats.js +3 -41
  8. package/dist/rust-session.d.ts +19 -0
  9. package/dist/rust-session.js +92 -0
  10. package/package.json +7 -9
  11. package/wasm/high-release-1.2.2-public-low-r2.wasm +0 -0
  12. package/wasm/low-release-1.2.2-public-low-r2.wasm +0 -0
  13. package/wasm/medium-release-1.2.2-public-low-r2.wasm +0 -0
  14. package/wasm/very-high-release-1.2.2-public-low-r2.wasm +0 -0
  15. package/dist/completion-host.d.mts +0 -40
  16. package/dist/completion-host.mjs +0 -188
  17. package/dist/detail-20260914/continuity.d.mts +0 -2
  18. package/dist/detail-20260914/continuity.mjs +0 -62
  19. package/dist/detail-20260914/detail-proposals-rich.d.mts +0 -13
  20. package/dist/detail-20260914/detail-proposals-rich.mjs +0 -53
  21. package/dist/detail-20260914/direct-recovery.d.mts +0 -28
  22. package/dist/detail-20260914/direct-recovery.mjs +0 -139
  23. package/dist/detail-20260914/host.d.mts +0 -40
  24. package/dist/detail-20260914/host.mjs +0 -280
  25. package/dist/detail-20260914/scanner.d.mts +0 -12
  26. package/dist/detail-20260914/scanner.mjs +0 -64
  27. package/dist/detail-20260914/source-evidence.d.mts +0 -10
  28. package/dist/detail-20260914/source-evidence.mjs +0 -94
  29. package/dist/detail-canvas.d.ts +0 -35
  30. package/dist/detail-canvas.js +0 -73
  31. package/dist/detail-runtime/direct-recovery.d.mts +0 -28
  32. package/dist/detail-runtime/direct-recovery.mjs +0 -142
  33. package/dist/detail-runtime/host.d.mts +0 -40
  34. package/dist/detail-runtime/host.mjs +0 -282
  35. package/dist/detail-runtime/scanner.d.mts +0 -12
  36. package/dist/detail-runtime/scanner.mjs +0 -70
  37. package/dist/detail.d.ts +0 -18
  38. package/dist/detail.js +0 -84
  39. package/dist/host.d.ts +0 -112
  40. package/dist/host.js +0 -184
  41. package/dist/host64.d.ts +0 -112
  42. package/dist/host64.js +0 -184
  43. package/dist/multiformat/coverage.d.ts +0 -7
  44. package/dist/multiformat/coverage.js +0 -26
  45. package/dist/multiformat/geometry.d.ts +0 -37
  46. package/dist/multiformat/geometry.js +0 -132
  47. package/dist/multiformat/linear-duplicates.d.ts +0 -16
  48. package/dist/multiformat/linear-duplicates.js +0 -163
  49. package/dist/multiformat/pixels.d.ts +0 -3
  50. package/dist/multiformat/pixels.js +0 -36
  51. package/dist/multiformat/scanner.d.ts +0 -60
  52. package/dist/multiformat/scanner.js +0 -361
  53. package/dist/multiformat-host.d.ts +0 -121
  54. package/dist/multiformat-host.js +0 -207
  55. package/dist/policy.d.ts +0 -12
  56. package/dist/policy.js +0 -12
  57. package/wasm/high-complete-release-20260916.wasm +0 -0
  58. package/wasm/low-complete-release-20260916.wasm +0 -0
  59. package/wasm/medium-complete-release-20260916.wasm +0 -0
  60. package/wasm/multiformat.json +0 -7
  61. package/wasm/multiformat.wasm +0 -0
  62. package/wasm/very-high-complete-release-20260916.wasm +0 -0
@@ -0,0 +1,92 @@
1
+ export class ScannerError extends Error {
2
+ code;
3
+ constructor(code, message) {
4
+ super(message);
5
+ this.code = code;
6
+ this.name = "ScannerError";
7
+ }
8
+ }
9
+ const exportNames = [
10
+ "tapirscan_abi_version",
11
+ "tapirscan_mode",
12
+ "tapirscan_create",
13
+ "tapirscan_destroy",
14
+ "tapirscan_prepare",
15
+ "tapirscan_input_ptr",
16
+ "tapirscan_input_len",
17
+ "tapirscan_scan",
18
+ "tapirscan_output_ptr",
19
+ "tapirscan_output_len",
20
+ ];
21
+ function status(code, operation) {
22
+ if (code === 0)
23
+ return;
24
+ const names = {
25
+ 1: "invalid_input",
26
+ 2: "disposed",
27
+ 4: "engine",
28
+ 5: "capacity",
29
+ };
30
+ throw new ScannerError(names[code] ?? `core_${String(code)}`, `${operation} failed (${String(code)})`);
31
+ }
32
+ export class RustScannerSession {
33
+ exports;
34
+ handle;
35
+ constructor(exports, handle) {
36
+ this.exports = exports;
37
+ this.handle = handle;
38
+ }
39
+ static async create(bytes, mode, formats, addOnPolicy) {
40
+ const instance = await WebAssembly.instantiate(bytes, {});
41
+ const exports = instance.instance.exports;
42
+ if (!(exports.memory instanceof WebAssembly.Memory))
43
+ throw new ScannerError("abi_shape", "Missing WASM memory");
44
+ for (const name of exportNames)
45
+ if (typeof exports[name] !== "function")
46
+ throw new ScannerError("abi_shape", `Missing WASM export: ${name}`);
47
+ if (exports.tapirscan_abi_version() !== 1)
48
+ throw new ScannerError("abi_version", "Unsupported scanner ABI");
49
+ if (exports.tapirscan_mode() !== mode)
50
+ throw new ScannerError("abi_mode", "Scanner WASM mode does not match the requested mode");
51
+ const handle = exports.tapirscan_create(mode, formats, addOnPolicy);
52
+ if (!handle)
53
+ throw new ScannerError("capacity", "Could not create scanner session");
54
+ return new RustScannerSession(exports, handle);
55
+ }
56
+ scan(image, flags, formats) {
57
+ const exports = this.activeExports();
58
+ status(exports.tapirscan_prepare(this.handle, image.width, image.height, image.channels, image.stride), "Image preparation");
59
+ const length = exports.tapirscan_input_len(this.handle);
60
+ const expected = (image.height - 1) * image.stride + image.width * image.channels;
61
+ if (length !== expected)
62
+ throw new ScannerError("abi_shape", "Input allocation mismatch");
63
+ new Uint8Array(exports.memory.buffer, exports.tapirscan_input_ptr(this.handle), length).set(image.data.subarray(0, length));
64
+ const result = exports.tapirscan_scan(this.handle, flags, formats);
65
+ const output = new Uint8Array(exports.memory.buffer, exports.tapirscan_output_ptr(this.handle), exports.tapirscan_output_len(this.handle));
66
+ let decoded;
67
+ try {
68
+ decoded = JSON.parse(new TextDecoder().decode(output));
69
+ }
70
+ catch {
71
+ throw new ScannerError("invalid_output", "Scanner returned invalid JSON");
72
+ }
73
+ if (result !== 0) {
74
+ const message = decoded && typeof decoded === "object" && "error" in decoded
75
+ ? String(decoded.error)
76
+ : `Scan failed (${String(result)})`;
77
+ throw new ScannerError(result === 4 ? "engine" : `core_${String(result)}`, message);
78
+ }
79
+ return decoded;
80
+ }
81
+ dispose() {
82
+ if (!this.handle)
83
+ return;
84
+ status(this.exports.tapirscan_destroy(this.handle), "Scanner disposal");
85
+ this.handle = 0;
86
+ }
87
+ activeExports() {
88
+ if (!this.handle)
89
+ throw new ScannerError("disposed", "Scanner is disposed");
90
+ return this.exports;
91
+ }
92
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tapirscan",
3
- "version": "1.2.0",
3
+ "version": "1.2.2",
4
4
  "type": "module",
5
5
  "description": "Orientation-aware barcode scanning with a Rust/WASM core and four effort modes",
6
6
  "exports": {
@@ -12,17 +12,15 @@
12
12
  "files": [
13
13
  "dist",
14
14
  "examples",
15
- "wasm/multiformat.json",
16
15
  "THIRD_PARTY_NOTICES.md",
17
- "wasm/low-complete-release-20260916.wasm",
18
- "wasm/medium-complete-release-20260916.wasm",
19
- "wasm/high-complete-release-20260916.wasm",
20
- "wasm/very-high-complete-release-20260916.wasm",
21
- "wasm/multiformat.wasm"
16
+ "wasm/low-release-1.2.2-public-low-r2.wasm",
17
+ "wasm/medium-release-1.2.2-public-low-r2.wasm",
18
+ "wasm/high-release-1.2.2-public-low-r2.wasm",
19
+ "wasm/very-high-release-1.2.2-public-low-r2.wasm"
22
20
  ],
23
21
  "scripts": {
24
- "build": "tsc -p tsconfig.json",
25
- "test": "node --test test/scanner.mjs test/linear-duplicates.mjs && tsc --noEmit --strict --skipLibCheck --target ES2022 --module NodeNext test/api-types.ts",
22
+ "build": "node scripts/clean-dist.mjs && tsc -p tsconfig.json",
23
+ "test": "node --test test/scanner.mjs test/shared-retail.mjs && tsc --noEmit --strict --skipLibCheck --target ES2022 --module NodeNext test/api-types.ts",
26
24
  "prepack": "npm run build && node scripts/verify-package.mjs"
27
25
  },
28
26
  "devDependencies": {
@@ -1,40 +0,0 @@
1
- /** Explicit indices reject sparse arrays; nonfinite numeric geometry reaches Rust. */
2
- export function isQuadShape(value: any): boolean;
3
- /** Validate before asynchronous work; returned bytes are owned by the caller. */
4
- export function snapshotImage(image: any): {
5
- data: Uint8Array<any>;
6
- width: any;
7
- height: any;
8
- channels: any;
9
- stride: any;
10
- };
11
- export function snapshotPolicy(policy: any): any;
12
- /** Uncalibrated support ordering; ties preserve spatial output order. */
13
- export function rankBarcodes(barcodes: any): any[];
14
- export class ScannerError extends Error {
15
- constructor(code: any, message: any);
16
- code: any;
17
- }
18
- export class IndependentScanner {
19
- static create(bytes: any): Promise<IndependentScanner>;
20
- constructor(exports: any);
21
- /** All supplied regions receive the cheap pass; successful reads do not end scanning. */
22
- scan(image: any, quads: any, policy?: {}): any;
23
- /** Synchronous transaction: upload once, localize, decode the same owned pixels. */
24
- scanLocalized(image: any, policy?: {}, fitLimit?: number, fullFrame?: boolean): {
25
- localization: any;
26
- searchWindows: {
27
- kind: string;
28
- polygon: number[][];
29
- candidateIndex: any;
30
- }[];
31
- scan: any;
32
- localizationMs: number;
33
- decodingMs: number;
34
- scanMs: number;
35
- };
36
- /** Separate convenience; it never changes find-all work or suppresses frame evidence. */
37
- best(result: any): any;
38
- dispose(): void;
39
- #private;
40
- }
@@ -1,188 +0,0 @@
1
- /** Explicit indices reject sparse arrays; nonfinite numeric geometry reaches Rust. */
2
- export function isQuadShape(value) {
3
- if (!Array.isArray(value) || value.length !== 4)
4
- return false;
5
- for (let i = 0; i < 4; i++) {
6
- if (!Object.hasOwn(value, i))
7
- return false;
8
- const point = value[i];
9
- if (!Array.isArray(point) || point.length !== 2)
10
- return false;
11
- for (let j = 0; j < 2; j++)
12
- if (!Object.hasOwn(point, j) || typeof point[j] !== 'number')
13
- return false;
14
- }
15
- return true;
16
- }
17
- export class ScannerError extends Error {
18
- code;
19
- constructor(code, message) { super(message); this.name = 'ScannerError'; this.code = code; }
20
- }
21
- function integer(value, min, max, name) {
22
- if (!Number.isSafeInteger(value) || value < min || value > max)
23
- throw new ScannerError('invalid_input', `Invalid ${name}`);
24
- return value;
25
- }
26
- function status(code) {
27
- if (code !== 0)
28
- throw new ScannerError(`core_${code}`, `Independent scanner rejected operation (${code})`);
29
- }
30
- function parseFrame(text, count) {
31
- const v = JSON.parse(text);
32
- if (!v || typeof v !== 'object')
33
- throw new ScannerError('invalid_output', 'Expected frame object');
34
- const f = v;
35
- if (!Array.isArray(f.candidates) || f.candidates.length !== count || !Array.isArray(f.barcodes) || typeof f.unfinished !== 'boolean' || !f.reconciliation)
36
- throw new ScannerError('invalid_output', 'Invalid frame shape');
37
- for (let i = 0; i < f.candidates.length; i++) {
38
- const c = f.candidates[i];
39
- if (c.candidate_index !== i || !Array.isArray(c.coverage) || c.coverage.length !== 4 || !Array.isArray(c.observations) || !Array.isArray(c.detections) || typeof c.error !== 'boolean')
40
- throw new ScannerError('invalid_output', 'Invalid candidate shape');
41
- }
42
- for (const b of f.barcodes)
43
- if (!/^\d{13}$/.test(b.text) || !Array.isArray(b.polygon) || b.polygon.length !== 4 || !Array.isArray(b.candidate_indices) || b.candidate_indices.some(i => !Number.isInteger(i) || i < 0 || i >= count))
44
- throw new ScannerError('invalid_output', 'Invalid barcode shape');
45
- return f;
46
- }
47
- /** Validate before asynchronous work; returned bytes are owned by the caller. */
48
- export function snapshotImage(image) {
49
- if (!image || typeof image !== 'object')
50
- throw new ScannerError('invalid_input', 'Invalid image');
51
- const width = integer(image.width, 1, 0xffffffff, 'width'), height = integer(image.height, 1, 0xffffffff, 'height');
52
- if (![1, 3, 4].includes(image.channels) || !(image.data instanceof Uint8Array))
53
- throw new ScannerError('invalid_input', 'Invalid image buffer/channels');
54
- const stride = integer(image.stride, width * image.channels, 0xffffffff, 'stride');
55
- const required = integer((height - 1) * stride + width * image.channels, 1, 128 * 1024 * 1024, 'image length');
56
- if (image.data.byteLength < required)
57
- throw new ScannerError('invalid_input', 'Image buffer is too short');
58
- return { data: new Uint8Array(image.data.subarray(0, required)), width, height, channels: image.channels, stride };
59
- }
60
- export function snapshotPolicy(policy) {
61
- if (!policy || typeof policy !== 'object')
62
- throw new ScannerError('invalid_input', 'Invalid policy');
63
- const copy = { ...policy };
64
- for (const key of ['transitionCleanup', 'sourceIdentity', 'interiorNormalization', 'guardBias', 'allowSingleRow'])
65
- if (copy[key] !== undefined && typeof copy[key] !== 'boolean')
66
- throw new ScannerError('invalid_input', `Invalid ${key}`);
67
- integer(copy.maxRetryPathsPerCandidate ?? 512, 0, 4096, 'candidate budget');
68
- integer(copy.maxRetryPathsPerFrame ?? 8192, 0, 65536, 'frame budget');
69
- integer(copy.maxAssociationChecks ?? 200000, 0, 2000000, 'comparison budget');
70
- integer(copy.maxAssociationPixels ?? 2000000, 0, 16000000, 'pixel budget');
71
- integer(copy.maxResults ?? 1024, 1, 4096, 'result budget');
72
- return copy;
73
- }
74
- /** Uncalibrated support ordering; ties preserve spatial output order. */
75
- export function rankBarcodes(barcodes) {
76
- return [...barcodes].sort((a, b) => b.support - a.support);
77
- }
78
- export class IndependentScanner {
79
- #exports;
80
- #handle;
81
- constructor(exports) {
82
- this.#exports = exports;
83
- if (exports.regions_version() !== 1)
84
- throw new ScannerError('abi_version', 'Unsupported scanner ABI');
85
- this.#handle = exports.regions_new();
86
- if (!this.#handle)
87
- throw new ScannerError('capacity', 'Scanner handle capacity exhausted');
88
- }
89
- static async create(bytes) {
90
- const module = await WebAssembly.compile(bytes);
91
- const instance = await WebAssembly.instantiate(module, {});
92
- const exports = instance.exports;
93
- for (const name of ['regions_localize', 'regions_version', 'regions_new', 'regions_destroy', 'regions_prepare', 'regions_input_ptr', 'regions_input_len', 'regions_quads_ptr', 'regions_output_ptr', 'regions_output_len', 'regions_scan']) {
94
- if (typeof instance.exports[name] !== 'function')
95
- throw new ScannerError('abi_shape', `Missing ${name}`);
96
- }
97
- if (!(exports.memory instanceof WebAssembly.Memory))
98
- throw new ScannerError('abi_shape', 'Missing memory');
99
- return new IndependentScanner(exports);
100
- }
101
- /** All supplied regions receive the cheap pass; successful reads do not end scanning. */
102
- scan(image, quads, policy = {}) {
103
- return this.#scan(image, quads, policy, false);
104
- }
105
- /** Synchronous transaction: upload once, localize, decode the same owned pixels. */
106
- scanLocalized(image, policy = {}, fitLimit = 8, fullFrame = false) {
107
- const start = performance.now();
108
- if (!this.#handle)
109
- throw new ScannerError('disposed', 'Scanner is disposed');
110
- if (!image || typeof image !== 'object')
111
- throw new ScannerError('invalid_input', 'Invalid image');
112
- const width = integer(image.width, 3, 0xffffffff, 'width'), height = integer(image.height, 3, 0xffffffff, 'height');
113
- if (![1, 3, 4].includes(image.channels) || !(image.data instanceof Uint8Array))
114
- throw new ScannerError('invalid_input', 'Invalid image buffer/channels');
115
- const stride = integer(image.stride, width * image.channels, 0xffffffff, 'stride');
116
- const required = integer((height - 1) * stride + width * image.channels, 1, 128 * 1024 * 1024, 'image length');
117
- if (image.data.byteLength < required)
118
- throw new ScannerError('invalid_input', 'Image buffer is too short');
119
- integer(fitLimit, 0, 8, 'shear limit');
120
- const e = this.#exports, id = this.#handle;
121
- status(e.regions_prepare(id, width, height, image.channels, stride));
122
- if (e.regions_input_len(id) !== required)
123
- throw new ScannerError('abi_shape', 'Input allocation mismatch');
124
- new Uint8Array(e.memory.buffer, e.regions_input_ptr(id), required).set(image.data.subarray(0, required));
125
- status(e.regions_localize(id, fitLimit));
126
- const localization = JSON.parse(new TextDecoder().decode(new Uint8Array(e.memory.buffer, e.regions_output_ptr(id), e.regions_output_len(id))));
127
- if (!Array.isArray(localization.proposals) || localization.proposals.length > 32 || localization.proposals.some((p) => !isQuadShape(p.polygon)))
128
- throw new ScannerError('abi_shape', 'Invalid localization');
129
- const searchWindows = fullFrame ? [{ kind: 'full_frame_search', polygon: [[0, 0], [width - 1, 0], [width - 1, height - 1], [0, height - 1]], candidateIndex: localization.proposals.length }] : [];
130
- const localizationMs = performance.now() - start, decodeStart = performance.now();
131
- const scan = this.#scan(image, [...localization.proposals.map((p) => p.polygon), ...searchWindows.map(p => p.polygon)], policy, true);
132
- return { localization, searchWindows, scan, localizationMs, decodingMs: performance.now() - decodeStart, scanMs: performance.now() - start };
133
- }
134
- #scan(image, quads, policy, prepared) {
135
- const start = performance.now();
136
- if (!this.#handle)
137
- throw new ScannerError('disposed', 'Scanner is disposed');
138
- if (!image || typeof image !== 'object' || !Array.isArray(quads) || !policy || typeof policy !== 'object')
139
- throw new ScannerError('invalid_input', 'Invalid scan arguments');
140
- for (const key of ['transitionCleanup', 'sourceIdentity', 'interiorNormalization', 'guardBias', 'allowSingleRow'])
141
- if (policy[key] !== undefined && typeof policy[key] !== 'boolean')
142
- throw new ScannerError('invalid_input', `Invalid ${key}`);
143
- const e = this.#exports, id = this.#handle;
144
- const width = integer(image.width, 1, 0xffffffff, 'width'), height = integer(image.height, 1, 0xffffffff, 'height');
145
- if (![1, 3, 4].includes(image.channels) || !(image.data instanceof Uint8Array))
146
- throw new ScannerError('invalid_input', 'Invalid image buffer/channels');
147
- const stride = integer(image.stride, width * image.channels, 0xffffffff, 'stride');
148
- const required = integer((height - 1) * stride + width * image.channels, 1, 128 * 1024 * 1024, 'image length');
149
- if (image.data.byteLength < required)
150
- throw new ScannerError('invalid_input', 'Image buffer is too short');
151
- integer(quads.length, 0, 64, 'candidate count');
152
- for (const q of quads)
153
- if (!isQuadShape(q))
154
- throw new ScannerError('invalid_input', 'Invalid quad shape');
155
- const perCandidate = integer(policy.maxRetryPathsPerCandidate ?? 512, 0, 4096, 'candidate budget');
156
- const perFrame = integer(policy.maxRetryPathsPerFrame ?? 8192, 0, 65536, 'frame budget');
157
- const checks = integer(policy.maxAssociationChecks ?? 200000, 0, 2000000, 'comparison budget');
158
- const pixels = integer(policy.maxAssociationPixels ?? 2000000, 0, 16000000, 'pixel budget');
159
- const results = integer(policy.maxResults ?? 1024, 1, 4096, 'result budget');
160
- if (policy.finishCandidates && e.regions_completion_supported?.() !== 1)
161
- throw new Error("This WASM build does not support finishCandidates");
162
- const flags = (policy.transitionCleanup ? 1 : 0) | (policy.sourceIdentity ? 2 : 0) | (policy.interiorNormalization ? 4 : 0) | (policy.guardBias ? 8 : 0) | (policy.allowSingleRow ? 16 : 0) | (policy.finishCandidates ? 32 : 0);
163
- if (!prepared) {
164
- status(e.regions_prepare(id, width, height, image.channels, stride));
165
- if (e.regions_input_len(id) !== required)
166
- throw new ScannerError('abi_shape', 'Input allocation mismatch');
167
- new Uint8Array(e.memory.buffer, e.regions_input_ptr(id), required).set(image.data.subarray(0, required));
168
- }
169
- const coordinates = new Float64Array(e.memory.buffer, e.regions_quads_ptr(id), 512);
170
- quads.forEach((q, i) => q.forEach((p, j) => { coordinates[i * 8 + j * 2] = p[0]; coordinates[i * 8 + j * 2 + 1] = p[1]; }));
171
- status(e.regions_scan(id, quads.length, flags, perCandidate, perFrame, checks, pixels, results));
172
- // Scan can grow memory. Never reuse the earlier input/coordinate views.
173
- const output = new Uint8Array(e.memory.buffer, e.regions_output_ptr(id), e.regions_output_len(id)).slice();
174
- const frame = parseFrame(new TextDecoder().decode(output), quads.length);
175
- return { ...frame, candidateTimingsAvailable: false, elapsedMs: performance.now() - start };
176
- }
177
- /** Separate convenience; it never changes find-all work or suppresses frame evidence. */
178
- best(result) {
179
- return rankBarcodes(result.barcodes)[0];
180
- }
181
- dispose() {
182
- if (this.#handle) {
183
- const id = this.#handle;
184
- this.#handle = 0;
185
- status(this.#exports.regions_destroy(id));
186
- }
187
- }
188
- }
@@ -1,2 +0,0 @@
1
- /** A bounded physical continuity claim; equal text alone never establishes identity. */
2
- export function coveredByContinuousBars(image: any, point: any, barcode: any): boolean;
@@ -1,62 +0,0 @@
1
- /** A bounded physical continuity claim; equal text alone never establishes identity. */
2
- export function coveredByContinuousBars(image, point, barcode) {
3
- const polygon = barcode.polygon;
4
- const left = [(polygon[0][0] + polygon[3][0]) / 2, (polygon[0][1] + polygon[3][1]) / 2];
5
- const right = [(polygon[1][0] + polygon[2][0]) / 2, (polygon[1][1] + polygon[2][1]) / 2];
6
- const dx = right[0] - left[0], dy = right[1] - left[1], width = Math.hypot(dx, dy);
7
- if (width < 45)
8
- return false;
9
- const nx = -dy / width, ny = dx / width;
10
- const along = ((point[0] - left[0]) * dx + (point[1] - left[1]) * dy) / (width * width);
11
- const offset = (point[0] - left[0]) * nx + (point[1] - left[1]) * ny;
12
- if (along < 0 || along > 1 || Math.abs(offset) > Math.min(128, width * 0.5))
13
- return false;
14
- const { data, width: iw, height: ih } = image;
15
- const gray = (x, y) => {
16
- x = Math.max(0, Math.min(iw - 1, x));
17
- y = Math.max(0, Math.min(ih - 1, y));
18
- const x0 = Math.floor(x), y0 = Math.floor(y), x1 = Math.min(iw - 1, x0 + 1), y1 = Math.min(ih - 1, y0 + 1), fx = x - x0, fy = y - y0;
19
- const sample = (a, b) => {
20
- const k = (b * iw + a) * 4;
21
- return (77 * data[k] + 150 * data[k + 1] + 29 * data[k + 2]) / 256;
22
- };
23
- return ((sample(x0, y0) * (1 - fx) + sample(x1, y0) * fx) * (1 - fy) +
24
- (sample(x0, y1) * (1 - fx) + sample(x1, y1) * fx) * fy);
25
- };
26
- const count = Math.min(256, Math.max(95, Math.round(width * 1.5)));
27
- const profile = (displacement) => {
28
- const values = new Float64Array(count);
29
- let sum = 0, energy = 0;
30
- for (let i = 0; i < count; i++) {
31
- const fraction = 0.02 + (0.96 * i) / (count - 1);
32
- const v = gray(left[0] + dx * fraction + nx * displacement, left[1] + dy * fraction + ny * displacement);
33
- values[i] = v;
34
- sum += v;
35
- energy += v * v;
36
- }
37
- return {
38
- values,
39
- mean: sum / count,
40
- deviation: Math.sqrt(Math.max(0, energy / count - (sum / count) ** 2)),
41
- };
42
- };
43
- const reference = profile(0);
44
- if (reference.deviation < 5)
45
- return false;
46
- const agrees = (displacement) => {
47
- const row = profile(displacement);
48
- if (row.deviation < reference.deviation * 0.65 || row.deviation < 5)
49
- return false;
50
- let covariance = 0;
51
- for (let i = 0; i < count; i++)
52
- covariance += (reference.values[i] - reference.mean) * (row.values[i] - row.mean);
53
- return covariance / (count * reference.deviation * row.deviation) > 0.8;
54
- };
55
- if (!agrees(offset) || !agrees(offset / 2))
56
- return false;
57
- const steps = Math.ceil(Math.abs(offset) * 2);
58
- for (let i = 1; i < steps; i++)
59
- if (!agrees((offset * i) / steps))
60
- return false;
61
- return true;
62
- }
@@ -1,13 +0,0 @@
1
- /** Source-resolution directional texture proposals. No labels or decoded text as inputs. */
2
- export function detailProposals(image: any, count?: number, tileSize?: number, sampleStep?: number): {
3
- left: number;
4
- top: number;
5
- width: number;
6
- height: number;
7
- x: number;
8
- y: number;
9
- score: number;
10
- coherence: number;
11
- energy: number;
12
- angle: number;
13
- }[];
@@ -1,53 +0,0 @@
1
- /** Source-resolution directional texture proposals. No labels or decoded text as inputs. */
2
- export function detailProposals(image, count = 4, tileSize = 320, sampleStep = 2) {
3
- const { data, width, height } = image;
4
- const size = 24, step = sampleStep, cells = [];
5
- const gray = (x, y) => {
6
- const i = (y * width + x) * 4;
7
- return (77 * data[i] + 150 * data[i + 1] + 29 * data[i + 2]) / 256;
8
- };
9
- for (let y = 1; y + size < height; y += size)
10
- for (let x = 1; x + size < width; x += size) {
11
- let xx = 0, yy = 0, xy = 0, sx = 0, sy = 0, n = 0;
12
- for (let j = y; j < y + size; j += step)
13
- for (let i = x; i < x + size; i += step) {
14
- const v = gray(i, j), gx = gray(i + 1, j) - v, gy = gray(i, j + 1) - v;
15
- xx += gx * gx;
16
- yy += gy * gy;
17
- xy += gx * gy;
18
- sx += gx;
19
- sy += gy;
20
- n++;
21
- }
22
- xx = Math.max(0, xx - (sx * sx) / n);
23
- yy = Math.max(0, yy - (sy * sy) / n);
24
- xy -= (sx * sy) / n;
25
- const energy = (xx + yy) / n, coherence = Math.sqrt((xx - yy) ** 2 + 4 * xy * xy) / (xx + yy + 1);
26
- const score = Math.sqrt(energy) * coherence * coherence;
27
- if (score > 5)
28
- cells.push({
29
- x: x + size / 2,
30
- y: y + size / 2,
31
- score,
32
- coherence,
33
- energy,
34
- angle: 0.5 * Math.atan2(2 * xy, xx - yy),
35
- });
36
- }
37
- cells.sort((a, b) => b.score - a.score);
38
- const selected = [];
39
- for (const c of cells) {
40
- if (selected.some((s) => Math.hypot(s.x - c.x, s.y - c.y) < 128))
41
- continue;
42
- selected.push({
43
- ...c,
44
- left: Math.max(0, Math.min(width - tileSize, Math.round(c.x - tileSize / 2))),
45
- top: Math.max(0, Math.min(height - tileSize, Math.round(c.y - tileSize / 2))),
46
- width: Math.min(width, tileSize),
47
- height: Math.min(height, tileSize),
48
- });
49
- if (selected.length === count)
50
- break;
51
- }
52
- return selected;
53
- }
@@ -1,28 +0,0 @@
1
- /** Bounded source-guided hypotheses, without another localizer/shear search per crop. */
2
- export function recoverDirectSeed(image: any, scanner: any, policy: any, baseline: any, budget?: number, factor?: number, sequential?: boolean, scharr?: boolean, minimumSpan?: number, maxDirections?: number): {
3
- barcodes: any[];
4
- additions: any[];
5
- attempts: {
6
- x: number;
7
- y: number;
8
- w: number;
9
- h: number;
10
- factor: number;
11
- frame: any;
12
- reads: any;
13
- deferredReads: any;
14
- proposals: {
15
- polygon: number[][];
16
- score: number;
17
- text: string;
18
- }[];
19
- unfinished: any;
20
- }[];
21
- proposals: {
22
- polygon: number[][];
23
- score: number;
24
- text: string;
25
- }[];
26
- extraMs: number;
27
- searchLimited: boolean;
28
- };