-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest-ocr.mjs
More file actions
57 lines (51 loc) · 2.22 KB
/
Copy pathtest-ocr.mjs
File metadata and controls
57 lines (51 loc) · 2.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// 头less 验证:用扩展里 vendor 的同一套 Tesseract 资源 + 同样的白名单/PSM 配置,
// 对合成的比赛计时器图做 OCR,确认"裁出的 ROI → OCR 数字"这一半链路可行且准确。
// (tabCapture 截帧那一半必须在真实 Chrome 里手动测。)
import { createCanvas } from "@napi-rs/canvas";
import { createWorker } from "tesseract.js";
import { fileURLToPath } from "node:url";
import path from "node:path";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const vendor = path.join(__dirname, "extension", "vendor");
function makeClockImage(text, scale = 3) {
// 模拟扩展里裁出的小 ROI 再放大 ROI_SCALE 倍的效果
const baseW = 120, baseH = 48;
const c = createCanvas(baseW * scale, baseH * scale);
const ctx = c.getContext("2d");
ctx.fillStyle = "#0b1a2b"; // 深色比分条背景
ctx.fillRect(0, 0, c.width, c.height);
ctx.fillStyle = "#ffffff";
ctx.font = `bold ${30 * scale}px Arial`;
ctx.textBaseline = "middle";
ctx.fillText(text, 8 * scale, c.height / 2);
return c;
}
async function run() {
const cases = ["67:23", "45:00", "90:12", "12:08"];
// Node 下用 tesseract.js 自带的 node worker/core;langPath 指向扩展 vendor 的语言包,
// 以验证我们打包进扩展的 eng.traineddata.gz 是有效的。
const worker = await createWorker("eng", 1, {
langPath: vendor,
gzip: true,
});
await worker.setParameters({
tessedit_char_whitelist: "0123456789:+",
tessedit_pageseg_mode: "7",
});
let pass = 0;
for (const expected of cases) {
const canvas = makeClockImage(expected);
const png = canvas.toBuffer("image/png");
const t0 = performance.now();
const { data } = await worker.recognize(png);
const ms = Math.round(performance.now() - t0);
const got = (data.text || "").replace(/\s+/g, "");
const ok = got === expected;
if (ok) pass++;
console.log(`${ok ? "✅" : "❌"} 期望 "${expected}" → OCR "${got}" (${ms}ms, conf ${Math.round(data.confidence)})`);
}
await worker.terminate();
console.log(`\n结果:${pass}/${cases.length} 通过`);
process.exit(pass === cases.length ? 0 : 1);
}
run().catch((e) => { console.error(e); process.exit(2); });