offscreen-android 0.0.0-stage → 0.1.0

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/src/vision.js ADDED
@@ -0,0 +1,193 @@
1
+ /**
2
+ * vision.js —— 常驻 OpenCV 助手的 Node 侧封装。
3
+ *
4
+ * ## 为什么常驻
5
+ *
6
+ * 实测(tests/CV-BENCHMARK-ARM.md):`import cv2` 冷启 328ms。
7
+ * 每次起新进程的话,模板匹配从 5.7ms 变成 334ms(慢 58 倍)。
8
+ *
9
+ * 协议复用 ocr.js 那套已验证的:stdin/stdout 每行一个 JSON,
10
+ * 请求带 id,响应按 id 配对。
11
+ *
12
+ * ## 支持的操作(都是实测过的)
13
+ *
14
+ * | op | 用途 | 温态耗时 |
15
+ * |---|---|---|
16
+ * | dhash | 界面指纹,判断「是不是同一屏」 | 7ms |
17
+ * | diff | 两张图差异(MAD + maxCell) | 2.3ms |
18
+ * | match | 模板匹配(自动金字塔 + 低方差回退) | 5-30ms |
19
+ * | color | 颜色阈值 + 连通域 | 6.8ms |
20
+ * | edges | 边缘密度 | 0.7ms |
21
+ * | probe | 一次拿多个统计量,供方法选择打分 | ~20ms |
22
+ */
23
+ import { spawn } from 'node:child_process';
24
+ import { join, dirname } from 'node:path';
25
+ import { fileURLToPath } from 'node:url';
26
+ import { existsSync } from 'node:fs';
27
+
28
+ const __dirname = dirname(fileURLToPath(import.meta.url));
29
+ const HELPER = join(__dirname, 'vision_helper.py');
30
+ const TIMEOUT_MS = 15000;
31
+
32
+ const state = {
33
+ child: null,
34
+ ready: false,
35
+ error: null,
36
+ nextId: 1,
37
+ pending: new Map(),
38
+ buf: '',
39
+ started: false,
40
+ };
41
+
42
+ /** 起助手进程(幂等)。 */
43
+ function spawnHelper() {
44
+ if (state.child) return true;
45
+ if (state.started) return false;
46
+ state.started = true;
47
+ // **每次 spawn 前清残留。**
48
+ // S7:上一次 helper 写了一半 JSON 就被杀,残留半行会和新进程的 ready 行拼在一起,
49
+ // JSON.parse 失败 → ready 永远 false → 每次调用等 10 秒超时,而进程是活的所以不重建。
50
+ // S6:error 状态不复位的话,"装好 python3 也要重载插件才恢复"。
51
+ state.buf = '';
52
+ state.error = null;
53
+ state.ready = false;
54
+ try {
55
+ if (!existsSync(HELPER)) { state.error = '缺 vision_helper.py'; state.started = false; return false; }
56
+ const child = spawn('python3', [HELPER], { stdio: ['pipe', 'pipe', 'pipe'] });
57
+ state.child = child;
58
+ child.stdout.setEncoding('utf8');
59
+ child.stdout.on('data', (chunk) => {
60
+ state.buf += chunk;
61
+ let nl;
62
+ while ((nl = state.buf.indexOf('\n')) >= 0) {
63
+ const line = state.buf.slice(0, nl).trim();
64
+ state.buf = state.buf.slice(nl + 1);
65
+ if (!line) continue;
66
+ let msg;
67
+ try { msg = JSON.parse(line); } catch { continue; }
68
+ // 第一条是就绪消息
69
+ if (msg.ready !== undefined && msg.id === undefined) {
70
+ state.ready = !!msg.ready;
71
+ state.error = msg.ready ? null : (msg.error || '未知错误');
72
+ continue;
73
+ }
74
+ const p = state.pending.get(msg.id);
75
+ if (p) {
76
+ clearTimeout(p.timer);
77
+ state.pending.delete(msg.id);
78
+ p.resolve(msg);
79
+ }
80
+ }
81
+ });
82
+ child.stderr.on('data', () => { /* 助手不写 stderr,忽略 */ });
83
+ child.on('exit', () => {
84
+ state.child = null;
85
+ state.ready = false;
86
+ state.started = false;
87
+ state.buf = ''; // 进程没了,残留的半个 JSON 必须丢掉
88
+ for (const [, p] of state.pending) { clearTimeout(p.timer); p.resolve({ ok: false, hint: 'vision 助手退出了' }); }
89
+ state.pending.clear();
90
+ });
91
+ // **S6:error 时要把 started 复位。**
92
+ // ENOENT 时 Node 可能只发 error 不发 exit,started 会永远 true →
93
+ // spawnHelper 直接 return false,之后每次都报同一句"起不来",
94
+ // 装好 python3 也得重载插件才恢复(ocr.js 是对的,vision 退步了)。
95
+ child.on('error', (e) => {
96
+ state.error = String(e?.message || e);
97
+ state.child = null;
98
+ state.ready = false;
99
+ state.started = false;
100
+ for (const [, p] of state.pending) {
101
+ clearTimeout(p.timer);
102
+ p.resolve({ ok: false, hint: 'vision 助手启动失败:' + state.error });
103
+ }
104
+ state.pending.clear();
105
+ });
106
+ return true;
107
+ } catch (e) {
108
+ state.error = String(e?.message || e);
109
+ return false;
110
+ }
111
+ }
112
+
113
+ /** 等就绪(最多 10 秒)。 */
114
+ function waitReady(timeout = 10000) {
115
+ return new Promise((resolve) => {
116
+ const t0 = Date.now();
117
+ const tick = () => {
118
+ if (state.ready) return resolve(true);
119
+ if (state.error) return resolve(false);
120
+ if (Date.now() - t0 > timeout) return resolve(false);
121
+ setTimeout(tick, 100);
122
+ };
123
+ tick();
124
+ });
125
+ }
126
+
127
+ /**
128
+ * 发一个请求给助手。
129
+ * @param {string} op 操作名
130
+ * @param {object} params 参数
131
+ */
132
+ export async function call(op, params = {}) {
133
+ if (!spawnHelper()) {
134
+ return { ok: false, hint: `OpenCV 助手起不来:${state.error || '未知'}(装一下 pip install opencv-python-headless)` };
135
+ }
136
+ const ready = await waitReady();
137
+ if (!ready) {
138
+ return { ok: false, hint: state.error ? `OpenCV 不可用:${state.error}` : 'OpenCV 助手启动超时' };
139
+ }
140
+ const id = state.nextId++;
141
+ return await new Promise((resolve) => {
142
+ const timer = setTimeout(() => {
143
+ state.pending.delete(id);
144
+ resolve({ ok: false, hint: `vision 操作超时(${TIMEOUT_MS}ms)` });
145
+ }, TIMEOUT_MS);
146
+ state.pending.set(id, { resolve, timer });
147
+ try {
148
+ state.child.stdin.write(JSON.stringify({ id, op, ...params }) + '\n');
149
+ } catch (e) {
150
+ clearTimeout(timer);
151
+ state.pending.delete(id);
152
+ resolve({ ok: false, hint: `写不进助手:${String(e?.message || e)}` });
153
+ }
154
+ });
155
+ }
156
+
157
+ /** 界面指纹(64 位 dHash)。 */
158
+ export const dhash = (image) => call('dhash', { image });
159
+
160
+ /** 两张图差异。 */
161
+ export const diff = (image, image2) => call('diff', { image, image2 });
162
+
163
+ /** 模板匹配。 */
164
+ export const match = (image, template, opts = {}) => call('match', { image, template, ...opts });
165
+
166
+ /** 颜色阈值 + 连通域。 */
167
+ export const color = (image, target, opts = {}) => call('color', { image, target, ...opts });
168
+
169
+ /** 边缘密度。 */
170
+ export const edges = (image, opts = {}) => call('edges', { image, ...opts });
171
+
172
+ /** 一次拿多个统计量(方法选择用)。 */
173
+ export const probe = (image) => call('probe', { image });
174
+
175
+ /** 状态。 */
176
+ export function info() {
177
+ return { ready: state.ready, running: !!state.child, error: state.error };
178
+ }
179
+
180
+ /** 收工。 */
181
+ export function shutdown() {
182
+ // **先 flush pending 再杀**,否则正在等的调用会一直挂到 15 秒超时。
183
+ for (const [, p] of state.pending) {
184
+ clearTimeout(p.timer);
185
+ p.resolve({ ok: false, hint: 'vision 助手已关闭' });
186
+ }
187
+ state.pending.clear();
188
+ try { state.child?.kill('SIGKILL'); } catch { /* ignore */ }
189
+ state.child = null;
190
+ state.ready = false;
191
+ state.started = false;
192
+ state.buf = '';
193
+ }
@@ -0,0 +1,334 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ vision_helper.py —— 常驻的 OpenCV 助手。
4
+
5
+ ## 为什么必须常驻
6
+
7
+ 实测(tests/CV-BENCHMARK-ARM.md):`import cv2` 冷启 **328ms**。
8
+ 如果每次工具调用都起新进程,模板匹配从 5.7ms 变成 334ms(慢 58 倍)。
9
+
10
+ 所以复用 ocr.js 已验证的 stdin/stdout JSON 行协议:
11
+ 请求:{"id": N, "op": "...", ...}\n
12
+ 响应:{"id": N, "ok": true, ...}\n
13
+
14
+ ## 支持的操作
15
+
16
+ | op | 参数 | 返回 | 实测耗时 |
17
+ |---|---|---|---|
18
+ | dhash | image | hash(hex 16位) | 7ms |
19
+ | diff | image, image2 | mad, maxCell, cells | 2.3ms |
20
+ | match | image, template, region?, threshold? | score, x, y, w, h, method | 5.7ms |
21
+ | color | image, target(Lab), tolerance, region? | boxes | 6.8ms |
22
+ | edges | image, region? | density | 0.7ms |
23
+ | probe | image | 运动性/文本密度/颜色可分性 等统计 | ~20ms |
24
+
25
+ 全部基于 **1592×720** 的实测数字。
26
+ """
27
+ import sys, json, os, time
28
+
29
+ try:
30
+ import cv2
31
+ import numpy as np
32
+ READY = True
33
+ ERR = None
34
+ except Exception as e:
35
+ READY = False
36
+ ERR = str(e)
37
+ cv2 = None
38
+ np = None
39
+
40
+
41
+ def _load(path):
42
+ img = cv2.imread(path)
43
+ if img is None:
44
+ raise ValueError('读不到图: ' + path)
45
+ if img.ndim == 3 and img.shape[2] == 4:
46
+ img = cv2.cvtColor(img, cv2.COLOR_BGRA2BGR)
47
+ return img
48
+
49
+
50
+ def _region(img, region):
51
+ """region: {x,y,w,h}(可省)。越界自动裁剪。"""
52
+ if not region:
53
+ return img, 0, 0
54
+ h, w = img.shape[:2]
55
+ x = max(0, int(region.get('x', 0)))
56
+ y = max(0, int(region.get('y', 0)))
57
+ rw = min(int(region.get('w', w)), w - x)
58
+ rh = min(int(region.get('h', h)), h - y)
59
+ if rw <= 0 or rh <= 0:
60
+ raise ValueError('region 越界')
61
+ return img[y:y+rh, x:x+rw], x, y
62
+
63
+
64
+ def op_dhash(req):
65
+ """64 位 dHash 指纹(用来判断「是不是同一个界面」)。"""
66
+ img = _load(req['image'])
67
+ g = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
68
+ small = cv2.resize(g, (9, 8), interpolation=cv2.INTER_AREA)
69
+ bits = (small[:, 1:] > small[:, :-1]).flatten()
70
+ val = 0
71
+ for b in bits:
72
+ val = (val << 1) | int(b)
73
+ return {'ok': True, 'hash': format(val, '016x'), 'w': img.shape[1], 'h': img.shape[0]}
74
+
75
+
76
+ def op_diff(req):
77
+ """两张图的差异:MAD + 最大格差(maxCell 能抓到 MAD 漏掉的小区域变化)。"""
78
+ a = _load(req['image'])
79
+ b = _load(req['image2'])
80
+ if a.shape != b.shape:
81
+ b = cv2.resize(b, (a.shape[1], a.shape[0]))
82
+ ga = cv2.cvtColor(a, cv2.COLOR_BGR2GRAY).astype(np.int16)
83
+ gb = cv2.cvtColor(b, cv2.COLOR_BGR2GRAY).astype(np.int16)
84
+ d = np.abs(ga - gb)
85
+ mad = float(d.mean())
86
+ GH, GW = 24, 24
87
+ ch, cw = max(1, d.shape[0] // GH), max(1, d.shape[1] // GW)
88
+ cells = d[:ch*GH, :cw*GW].reshape(GH, ch, GW, cw).mean(axis=(1, 3))
89
+ idx = int(cells.argmax())
90
+ # **归一化到 0-1 再判断。**
91
+ # 原来用 0-255 原始灰度差(mad>0.5、maxCell>8),
92
+ # 而 PERF-AUDIT 标定的是归一化值(mad>0.005、maxCell>0.15)。
93
+ # maxCell>8 等同于归一化 0.031,比标定敏感 5 倍 → 秒数/光标/动画都判「有实质变化」。
94
+ mc = float(cells.max())
95
+ return {
96
+ 'ok': True, 'mad': round(mad / 255.0, 5), 'maxCell': round(mc / 255.0, 4),
97
+ 'madRaw': round(mad, 3), 'maxCellRaw': round(mc, 2),
98
+ 'maxCellAt': {'gx': idx % GW, 'gy': idx // GW},
99
+ 'changed': bool((mad / 255.0) > 0.005 or (mc / 255.0) > 0.15),
100
+ }
101
+
102
+
103
+ def op_match(req):
104
+ """
105
+ 模板匹配。**必须用金字塔**:全分辨率 129ms,1/4 金字塔 + 精修只要 5.7ms。
106
+
107
+ 返回最佳匹配的 score 和坐标(引擎坐标系,已加回 region 偏移)。
108
+ """
109
+ img0 = _load(req['image'])
110
+ # **必须先记原始尺寸。**
111
+ # _region 之后 img 已经是被裁剪的块,用它的 shape 当分母算出来的 cx/cy
112
+ # 是「region 内占比」,但调用方当成整屏 nx/ny 用 → 点歪到屏幕中间。
113
+ H0, W0 = img0.shape[:2]
114
+ img, ox, oy = _region(img0, req.get('region'))
115
+ tpl = _load(req['template'])
116
+ H, W = img.shape[:2]
117
+ th, tw = tpl.shape[:2]
118
+ # **这个检查不能放在尺度循环之前。**
119
+ # region 比模板小时(例:region 300×300、模板 540×540),
120
+ # 0.55 那一档是放得下的,但前置检查会直接返回失败 —— 多尺度在 region 场景下失效。
121
+ # 改成:按「最小尺度缩小后」判断。
122
+ _minScale = min([float(x) for x in (req.get('scales') or [1.0]) if float(x) > 0] or [1.0])
123
+ if th * _minScale > H or tw * _minScale > W:
124
+ return {'ok': False,
125
+ 'hint': '模板比搜索区域大(缩小到最小尺度 %.2f 也放不下)' % _minScale}
126
+ thr = float(req.get('threshold', 0.75))
127
+
128
+ # **纯色/低方差模板不能用 TM_CCOEFF_NORMED。**
129
+ # 它内部除以标准差,模板没有内部变化时 std≈0 → 结果恒为 0 或 NaN,
130
+ # 实测:从同一张图裁一块纯红矩形当模板,score=0.0、found=false。
131
+ # 这种模板改用 TM_SQDIFF_NORMED(越小越好),再把分数反转成「越大越好」。
132
+ tplStd = float(cv2.cvtColor(tpl, cv2.COLOR_BGR2GRAY).std())
133
+ # **纯黑模板会永远匹配失败**:SQDIFF_NORMED 的分母趋零,OpenCV 直接置 1,
134
+ # 1-1=0 → score 恒 0。提前拒绝,给可操作的提示。
135
+ if tplStd < 0.5:
136
+ return {'ok': False, 'hint': '模板几乎是单一颜色(含全黑),匹配不可靠。换一块有纹理的模板,或用 vdisplay_find_color'}
137
+ lowVar = tplStd < 6.0
138
+ method = cv2.TM_SQDIFF_NORMED if lowVar else cv2.TM_CCOEFF_NORMED
139
+
140
+ def scoreOf(r):
141
+ # **minMaxLoc 返回 (minVal, maxVal, minLoc, maxLoc)** —— 顺序别搞错。
142
+ # 我第一版写成 `_, _, mn, mnloc`,拿到的 mn 是 minLoc(tuple),
143
+ # 于是 1.0 - tuple 抛 TypeError。
144
+ mnv, mxv, mnloc, mxloc = cv2.minMaxLoc(r)
145
+ # SQDIFF 越小越好 → 转成越大越好
146
+ if lowVar:
147
+ return (1.0 - mnv), mnloc
148
+ return mxv, mxloc
149
+
150
+ # **多尺度是刚需,不是优化。**
151
+ # 文档教用户「用 vdisplay_shot 截图,裁出目标存成 PNG」,
152
+ # 但 vdisplay_shot 默认 540 宽 JPEG,而 find_image 走 PNG 分支拿原生 720 —
153
+ # 模板是 0.75 倍,尺寸差 33%,单尺度 CCOEFF 直接掉到 0.4-0.6 → 报「没找到」。
154
+ # 这是用户最会踩的坑(对抗审查 S3)。
155
+ scales = req.get('scales') or [1.0]
156
+ best = (-1.0, 0, 0, 1.0) # (score, x, y, scale)
157
+ q = 4
158
+ small = cv2.resize(img, (max(8, W // q), max(8, H // q)), interpolation=cv2.INTER_AREA)
159
+ for sc_ratio in scales:
160
+ s2 = float(sc_ratio)
161
+ if s2 <= 0:
162
+ continue
163
+ t2 = tpl if abs(s2 - 1.0) < 1e-6 else cv2.resize(
164
+ tpl, (max(4, int(round(tw * s2))), max(4, int(round(th * s2)))),
165
+ interpolation=cv2.INTER_AREA)
166
+ t2h, t2w = t2.shape[:2]
167
+ if t2h > H or t2w > W:
168
+ continue
169
+ st2 = cv2.resize(t2, (max(4, t2w // q), max(4, t2h // q)), interpolation=cv2.INTER_AREA)
170
+ if st2.shape[0] <= small.shape[0] and st2.shape[1] <= small.shape[1]:
171
+ r = cv2.matchTemplate(small, st2, method)
172
+ sc, loc = scoreOf(r)
173
+ cand = (sc, loc[0] * q, loc[1] * q, s2)
174
+ else:
175
+ r = cv2.matchTemplate(img, t2, method)
176
+ sc, loc = scoreOf(r)
177
+ cand = (sc, loc[0], loc[1], s2)
178
+ if cand[0] > best[0]:
179
+ best = cand
180
+
181
+ # ② 在粗位置周围 ±16px 全分辨率精修(用最佳尺度对应的模板)
182
+ bestScale = best[3]
183
+ tpl = tpl if abs(bestScale - 1.0) < 1e-6 else cv2.resize(
184
+ tpl, (max(4, int(round(tw * bestScale))), max(4, int(round(th * bestScale)))),
185
+ interpolation=cv2.INTER_AREA)
186
+ th2, tw2 = tpl.shape[:2]
187
+ cx, cy = int(best[1]), int(best[2])
188
+ pad = 16
189
+ x0, y0 = max(0, cx - pad), max(0, cy - pad)
190
+ x1, y1 = min(W, cx + tw2 + pad), min(H, cy + th2 + pad)
191
+ roi = img[y0:y1, x0:x1]
192
+ if roi.shape[0] >= th2 and roi.shape[1] >= tw2:
193
+ r2 = cv2.matchTemplate(roi, tpl, method)
194
+ sc2, loc2 = scoreOf(r2)
195
+ score, fx, fy = sc2, x0 + loc2[0], y0 + loc2[1]
196
+ else:
197
+ score, fx, fy = best[0], best[1], best[2]
198
+
199
+ found = score >= thr
200
+ return {
201
+ 'ok': True, 'found': bool(found), 'score': round(float(score), 4),
202
+ 'x': int(fx + ox), 'y': int(fy + oy), 'w': int(tw2), 'h': int(th2),
203
+ 'cx': round((fx + ox + tw2 / 2.0) / W0, 4),
204
+ 'cy': round((fy + oy + th2 / 2.0) / H0, 4),
205
+ 'scale': round(float(bestScale), 3),
206
+ 'threshold': thr,
207
+ 'method': 'SQDIFF' if lowVar else 'CCOEFF',
208
+ 'tplStd': round(tplStd, 1),
209
+ }
210
+
211
+
212
+ def op_color(req):
213
+ """
214
+ 颜色阈值 + 连通域。
215
+ **必须用 Lab 的 a/b 通道**,不能用绝对 RGB —— HDR/色偏会让 RGB 阈值失效。
216
+ """
217
+ img0 = _load(req['image'])
218
+ H0, W0 = img0.shape[:2] # 同上:归一化必须用原始尺寸
219
+ img, ox, oy = _region(img0, req.get('region'))
220
+ lab = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
221
+ tol = int(req.get('tolerance', 20))
222
+ tgt = req.get('target') # {a: 128, b: 128, l: 128} 或 {r,g,b}
223
+ # **兼容 b2**:旧 schema 里 Lab 的 b 被写成 b2(怕和 RGB 的 b 撞名),
224
+ # 但实现读的是 'b' → KeyError。这里两个都认。
225
+ if tgt and 'b2' in tgt and 'b' not in tgt:
226
+ tgt = dict(tgt); tgt['b'] = tgt['b2']
227
+ if tgt and 'a' in tgt:
228
+ a, b, l = int(tgt['a']), int(tgt['b']), int(tgt.get('l', 128))
229
+ lo = np.array([max(0, l - tol), max(0, a - tol), max(0, b - tol)])
230
+ hi = np.array([min(255, l + tol), min(255, a + tol), min(255, b + tol)])
231
+ elif tgt and 'r' in tgt:
232
+ bgr = np.uint8([[[tgt['b'], tgt['g'], tgt['r']]]])
233
+ l, a, b = cv2.cvtColor(bgr, cv2.COLOR_BGR2LAB)[0][0]
234
+ lo = np.array([max(0, int(l) - tol), max(0, int(a) - tol), max(0, int(b) - tol)])
235
+ hi = np.array([min(255, int(l) + tol), min(255, int(a) + tol), min(255, int(b) + tol)])
236
+ else:
237
+ return {'ok': False, 'hint': 'target 要给 {l,a,b} 或 {r,g,b}'}
238
+
239
+ mask = cv2.inRange(lab, lo, hi)
240
+ mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, np.ones((3, 3), np.uint8))
241
+ n, _, stats, cents = cv2.connectedComponentsWithStats(mask, 8)
242
+ minArea = int(req.get('minArea', 200))
243
+ boxes = []
244
+ H, W = mask.shape[:2]
245
+ for i in range(1, n):
246
+ x, y, w, h, area = stats[i]
247
+ if area < minArea:
248
+ continue
249
+ boxes.append({
250
+ 'x': int(x + ox), 'y': int(y + oy), 'w': int(w), 'h': int(h), 'area': int(area),
251
+ 'cx': round((x + ox + w / 2.0) / W0, 4), 'cy': round((y + oy + h / 2.0) / H0, 4),
252
+ })
253
+ boxes.sort(key=lambda b: -b['area'])
254
+ return {'ok': True, 'count': len(boxes), 'boxes': boxes[:int(req.get('max', 20))]}
255
+
256
+
257
+ def op_edges(req):
258
+ """边缘密度 —— 判断「这个界面适不适合用形状检测」。"""
259
+ img = _load(req['image'])
260
+ img, _, _ = _region(img, req.get('region'))
261
+ g = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
262
+ e = cv2.Canny(g, 50, 150)
263
+ return {'ok': True, 'density': round(float((e > 0).mean()), 4)}
264
+
265
+
266
+ def op_probe(req):
267
+ """一次采集多个统计量,供「选哪个识别方法」打分用。"""
268
+ img = _load(req['image'])
269
+ g = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
270
+ H, W = g.shape[:2]
271
+ # ① 边缘密度
272
+ e = cv2.Canny(g, 50, 150)
273
+ ed = float((e > 0).mean())
274
+ # ② 颜色可分性:8³ 量化直方图,top5 占比 + 色数
275
+ q = (img // 32).astype(np.int16)
276
+ codes = q[:, :, 0] * 64 + q[:, :, 1] * 8 + q[:, :, 2]
277
+ hist = np.bincount(codes.flatten(), minlength=512).astype(np.float32)
278
+ hist /= max(1.0, hist.sum())
279
+ top5 = float(np.sort(hist)[-5:].sum())
280
+ ncolors = int((hist > 0.0005).sum())
281
+ # ③ 亮度/对比
282
+ mean = float(g.mean())
283
+ std = float(g.std())
284
+ return {
285
+ 'ok': True, 'w': W, 'h': H,
286
+ 'edgeDensity': round(ed, 4),
287
+ 'colorTop5': round(top5, 4),
288
+ 'colorCount': ncolors,
289
+ 'brightness': round(mean, 1),
290
+ 'contrast': round(std, 1),
291
+ 'canTemplate': bool(ed < 0.30 and std > 8),
292
+ 'canColor': bool(top5 > 0.35 and ncolors < 260),
293
+ 'looksBlank': bool(std < 3),
294
+ }
295
+
296
+
297
+ OPS = {
298
+ 'dhash': op_dhash, 'diff': op_diff, 'match': op_match,
299
+ 'color': op_color, 'edges': op_edges, 'probe': op_probe,
300
+ }
301
+
302
+
303
+ def main():
304
+ out = sys.stdout
305
+ if not READY:
306
+ out.write(json.dumps({'ready': False, 'error': ERR}) + '\n')
307
+ out.flush()
308
+ return
309
+ out.write(json.dumps({'ready': True, 'cv2': cv2.__version__}) + '\n')
310
+ out.flush()
311
+ for line in sys.stdin:
312
+ line = line.strip()
313
+ if not line:
314
+ continue
315
+ req = None
316
+ try:
317
+ req = json.loads(line)
318
+ op = req.get('op')
319
+ fn = OPS.get(op)
320
+ if not fn:
321
+ resp = {'ok': False, 'hint': '不认识的 op: ' + str(op)}
322
+ else:
323
+ t0 = time.time()
324
+ resp = fn(req)
325
+ resp['elapsedMs'] = round((time.time() - t0) * 1000, 2)
326
+ except Exception as e:
327
+ resp = {'ok': False, 'hint': '%s: %s' % (type(e).__name__, e)}
328
+ resp['id'] = req.get('id') if isinstance(req, dict) else None
329
+ out.write(json.dumps(resp) + '\n')
330
+ out.flush()
331
+
332
+
333
+ if __name__ == '__main__':
334
+ main()