From ea7b678b3712bd02f35edc322bc99a18bbb12ce7 Mon Sep 17 00:00:00 2001 From: zhy200308 <2258391712@qq.com> Date: Tue, 11 Aug 2026 09:08:04 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=96=B0=E5=A2=9E=20QFT5=20=E5=85=89?= =?UTF-8?q?=E5=AD=A6=E9=93=BE=E8=B7=AF=E6=96=B9=E6=A1=88=E4=B8=8E=E5=88=86?= =?UTF-8?q?=E8=BE=A8=E7=8E=87=E6=A5=94=E5=BD=A2=E6=A0=87=E5=AE=9A=E5=B7=A5?= =?UTF-8?q?=E5=85=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 当前光学链路传 3MB 需要 1 小时,瓶颈不是解码慢而是无反馈重传浪费: 按 320B 分片、45FPS 反推,每轮约捕获 44%,收齐需 16.5 轮, 约 86% 的信道被已收到的重复分片占用。 docs/OPTICAL_V5_PLAN.md 给出完整改造方案: - 条带级喷泉码消除重传浪费,撕裂只损失 1/12 而非整帧 - MANIFEST 每 32~64 帧插播,消除平均 109 秒的启动空转 - 相机帧率三级锁定 + 手动短曝光(3px/模块下 33ms 自动曝光 会产生 8.7px 运动模糊,等于抹掉近 3 个模块,必然解不出) - 陀螺仪前馈跟踪四角单应,解决手持抖动丢锁 - 位阵列替代 QR,突破 v40 的 177 模块上限 scripts/wedge_*.py 是配套标定工具。方案里所有吞吐数字都建立在 「px/模块 的真实下限」这一未实测假设上,而合成实验显示该值仅因 对焦质量不同就能在 3.1~5.7 之间摆动,必须先实测: - wedge_gen.py 生成 7 档 pitch 的伪随机标定图 + 1:1 全屏查看器 - wedge_analyze.py 照片 → 实测 px/模块 → 对比度 → 误码率曲线 - wedge_selftest.py 合成相机模型端到端自检,无需真实硬件 标定同时暴露了方案的一个缺口:条带只有 CRC 没有内码,1750B 条带 约 14000 bit,1 bit 错即整条报废,要求原始 BER 低于 1e-5。 故需改为「内码纠错 + 外层喷泉码纠删」的级联结构,已记入文档。 --- .gitignore | 2 + docs/OPTICAL_V5_PLAN.md | 433 ++++++++++++++++++++++++++++++++++ scripts/run_all_selftests.py | 1 + scripts/wedge_analyze.py | 446 +++++++++++++++++++++++++++++++++++ scripts/wedge_common.py | 229 ++++++++++++++++++ scripts/wedge_gen.py | 132 +++++++++++ scripts/wedge_selftest.py | 162 +++++++++++++ 7 files changed, 1405 insertions(+) create mode 100644 docs/OPTICAL_V5_PLAN.md create mode 100644 scripts/wedge_analyze.py create mode 100644 scripts/wedge_common.py create mode 100644 scripts/wedge_gen.py create mode 100644 scripts/wedge_selftest.py diff --git a/.gitignore b/.gitignore index 0ed5ad6..0b0c9e0 100644 --- a/.gitignore +++ b/.gitignore @@ -10,3 +10,5 @@ local.properties # OS .DS_Store Thumbs.db +# 标定工具产物(wedge_gen.py 默认输出目录) +/out diff --git a/docs/OPTICAL_V5_PLAN.md b/docs/OPTICAL_V5_PLAN.md new file mode 100644 index 0000000..11d5466 --- /dev/null +++ b/docs/OPTICAL_V5_PLAN.md @@ -0,0 +1,433 @@ +# QFT5 光学链路方案(黑白 · 位阵列 · 陀螺仪稳定) + +目标: +- **A**:相机 24 FPS 下,1 MB < 5 s(≥ 209.7 KB/s) +- **B**:相机 50~60 FPS 下,10 MB < 10 s(≥ 1048.6 KB/s) +- 相机帧率自动取系统最高值并锁死、稳定 +- 手持抖动不导致丢锁重捕获 + +全程纯黑白(二值),不使用彩色或灰阶调制。 + +--- + +## 0. 选型结论:必须放弃 QR + +| 方案 | B/画布 | @24fps | @60fps | 目标A | 目标B | +|---|---|---|---|---|---| +| QR 2×1 v40 @720p | 5 729 | 130 KB/s | 325 KB/s | 7.9 s ❌ | 32 s ❌ | +| QR 3×1 v40 @1080p | 8 593 | 193 KB/s | 463 KB/s | 5.3 s ❌ | 22.1 s ❌ | +| 位阵列 3.5 px/模块 @1080p | 15 571 | 350 KB/s | 839 KB/s | 2.9 s ✅ | 12.2 s ❌ | +| **位阵列 3.0 px/模块 @1080p** | **21 209** | 477 KB/s | **1143 KB/s** | **2.5 s ✅** | **9.0 s ✅** | + +原因:QR 单符号上限 v40 = 177 模块。在 1080p 取景下相机能分辨约 330 模块/边, +单个 QR 只能用掉约 40% 的像素预算;横向排 3 个又受 16:9 宽度限制。 +QR-L 本身还要付 finder/timing/format/RS 约 14% 的结构开销。 + +位阵列取消这三项限制:无版本上限、无 finder 图案、纠错交给喷泉码。 +代价是不能再用 ZXing,需要自研采样解码器(见 §3.6,实际比 RS 解码更简单)。 + +**硬件前提(不满足则目标 B 无法达成,需在 App 内检测并提示):** +- 手机后摄支持 **1920×1080 ImageAnalysis @ 60 FPS**(用 `getOutputMinFrameDuration` 实测,非 flagship 常见只有 1080p30) +- 显示器 **≥ 60 Hz**,画布区可用宽度 **≥ 1824 逻辑像素**(3 显示 px/模块 × 608 模块) +- 取景需填满约 95% 画面 → 目标 B 建议使用支架 + +--- + +## 1. 需求一:相机帧率的获取、锁定与稳定 + +### 1.1 现有实现的三个缺陷 + +`MainActivity.chooseCameraFpsPlan()`(约 452 行): + +1. **只读 `CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES`,没有按目标分辨率校验。** + 该表是相机级能力,与具体输出尺寸无关。1080p 常见只支持 30 FPS,而 720p 支持 60。 + 现在的代码会对 1080p 请求一个它根本达不到的 `[60,60]`,结果要么被拒(走 fallback + 丢失全部控制),要么被静默降频。 + → 必须用 `StreamConfigurationMap.getOutputMinFrameDuration(ImageFormat.YUV_420_888, size)` + 算出**该尺寸的真实上限** `1e9 / minFrameDuration`,再与 AE 表求交集。 + +2. **没有优先选固定区间。** 排序是 `upper` 降序,所以 `[15,60]` 会排在 `[30,30]` 前面被选中。 + 可变区间授权 AE 在光线不足时把帧率降到 `lower`——这正是"不稳定"的根源。 + → 必须优先 `lower == upper` 的固定区间。 + +3. **没有验证实际达成帧率。** 请求 ≠ 实际。 + +### 1.2 三级锁定策略 + +``` +L1 固定 AE 区间 CONTROL_AE_TARGET_FPS_RANGE = [max, max] + ↓ 实测不达标 +L2 全手动曝光(推荐) CONTROL_AE_MODE = OFF + SENSOR_FRAME_DURATION = 1e9 / fps + SENSOR_EXPOSURE_TIME = 2~4 ms + SENSOR_SENSITIVITY = ISO 200~400(按实测亮度标定一次) + ↓ 设备拒绝该组合 +L3 回退设备默认 + 降级目标(告知用户目标 B 不可达) +``` + +**L2 是真正的"锁死"**,也是本方案的推荐路径:屏幕是自发光强光源,2~4 ms 曝光完全够用; +AE 关闭后帧间隔由 `SENSOR_FRAME_DURATION` 精确决定,不再受测光波动影响。 +更重要的是——**短曝光同时是防抖的第一杠杆**(见 §2.1)。 + +标定流程:启动时用 AE 自动跑 10 帧,读回 `CaptureResult` 的 +`SENSOR_EXPOSURE_TIME` × `SENSOR_SENSITIVITY` 乘积作为曝光量基准, +再按"曝光缩到 3 ms、ISO 等比放大并夹到设备 `SENSOR_INFO_SENSITIVITY_RANGE` 上限"求解, +之后切 `AE_MODE_OFF` 固定住。 + +### 1.3 必须关闭 / 必须开启 + +| 项 | 设置 | 理由 | +|---|---|---| +| `CONTROL_VIDEO_STABILIZATION_MODE` | **OFF** | EIS 会逐帧裁切+几何形变,直接破坏单应矩阵跟踪 | +| `CONTROL_AE_ANTIBANDING_MODE` | **OFF** | 50 Hz 抗闪烁会把曝光量化到 10 ms 整数倍,与 2~4 ms 短曝光直接冲突,并把帧率钉死 | +| `NOISE_REDUCTION_MODE` | **OFF / FAST** | 强降噪会抹平单像素级模块边界 | +| `EDGE_MODE` | **OFF / FAST** | 锐化会产生振铃,制造伪模块边缘 | +| `LENS_OPTICAL_STABILIZATION_MODE` | **ON** | OIS 是光学补偿,不改成像几何,纯收益 | +| `CONTROL_AF_MODE` | 锁定后 **OFF** + 固定 `LENS_FOCUS_DISTANCE` | 连续 AF 每次搜索都产生几帧模糊 | + +现有代码用 `AF_MODE_CONTINUOUS_PICTURE`(MainActivity 约 306 行)并在稳定锁定时 +还周期性重新触发对焦(约 272 行)——对着固定距离的屏幕,这是纯负收益,必须改掉。 + +### 1.4 闭环验证("稳定下来"的判据) + +用 `CaptureResult.SENSOR_TIMESTAMP` 做差分,滑动窗口 60 帧: + +``` +p50(Δt) → 实际帧率 +p95(Δt) / p50(Δt) > 1.30 → 判定"不稳定",降一档重试 +丢帧率 = count(Δt > 1.5 × p50) / N +``` + +三档实测都不稳定时,把目标降到"尽力而为"模式并在 UI 明示。 +实测帧率必须回传给 Windows 端(通过配对二维码之外的一次性握手,或让用户手动选档), +**Windows 显示帧率 = 手机实测相机帧率**(见 §3.3,无需更精细的同步)。 + +--- + +## 2. 需求二:防抖 / 锁定不丢失 + +现有实现是"轴对齐矩形 + `smoothToward` 平滑 + 连续 miss 逐级扩大 + 10 次 miss 全幅重搜" +(`QrAnalyzer.decodeOptical` / `LockRect`)。三个结构性问题: + +- 轴对齐矩形无法表达旋转与透视,手一歪矩形就被迫变大,分析面积和解码成本同时上升; +- ROI 只在**解码成功后**才更新,一旦 miss 就完全没有状态推进(无航位推算); +- 恢复策略是"扩大并祈祷"。 + +### 2.1 第一杠杆:短曝光(量化) + +1080p、65° FOV → 等效焦距 **f ≈ 1507 px/rad**。运动模糊长度 = ω × t_exposure × f。 + +| 手持角速度 | 曝光 33 ms(自动) | 8 ms | 4 ms | 2 ms | +|---|---|---|---|---| +| 3 °/s(平稳) | 2.60 px = 0.87 模块 ❌ | 0.63 px ✅ | 0.32 px ✅ | 0.16 px ✅ | +| 10 °/s(典型手持) | **8.68 px = 2.89 模块 ❌** | 2.10 px ❌ | 1.05 px ⚠️ | 0.53 px ✅ | +| 20 °/s(明显晃动) | 17.36 px ❌ | 4.21 px ❌ | 2.10 px ❌ | 1.05 px ⚠️ | + +**在 3 px/模块下,自动曝光的 33 ms 会抹掉近 3 个模块——必然解不出。** +这解释了当前"识别率不高"的相当一部分。锁到 2~4 ms 后模糊降到 1 px 以内。 +判据:`blur = ω · t_exp · f < 0.7 模块`。 + +### 2.2 第二杠杆:陀螺仪前馈(真正的"防抖") + +60 FPS 下 10 °/s 的帧间像素位移 = **4.4 px**,看似很小,但连续 10 帧漂移 44 px, +远超 `smoothToward` 的跟随带宽——这就是丢锁的直接机理。陀螺仪可以**提前**算出这个位移。 + +``` +SensorManager.registerListener(TYPE_GYROSCOPE_UNCALIBRATED, SENSOR_DELAY_FASTEST) // ~200 Hz +环形缓冲 (timestampNanos, ωx, ωy, ωz) + +对每个相机帧 t: + 1. 校验 SENSOR_INFO_TIMESTAMP_SOURCE == REALTIME, + 使 ImageProxy.imageInfo.timestamp 与陀螺时间戳同域(elapsedRealtimeNanos) + 2. 积分 [t-1, t] 区间的角速度 → Δθ = (Δθx, Δθy, Δθz) + 3. 小角近似的图像位移: + dx ≈ -f · Δθy dy ≈ f · Δθx roll ≈ Δθz + (需按 sensorOrientation / 显示旋转做一次坐标系映射) + 4. 用 dx, dy, roll 预推上一帧的 4 个角标位置 + 5. 只在预测点 ±12 px 的窗口内做角标模板匹配 +``` + +效果:搜索窗从"全幅" 降到 4 个 25×25 px 的小窗,即使剧烈晃动也能保持跟踪。 +陀螺仪对**旋转**敏感,而手持抖动在 30 cm 距离上 90% 以上的像素位移来自旋转而非平移, +所以纯陀螺前馈就足够,不需要 IMU 融合。 + +### 2.3 第三杠杆:模糊门控 + +在解码前用陀螺仪算曝光窗口内的模糊长度。若 `blur > 0.7 模块`, +**直接跳过该帧的采样解码**,只更新位姿预测。省下的 CPU 留给清晰帧。 +这比"试着解、失败、扩大 ROI"的现有策略便宜一个数量级。 + +### 2.4 跟踪 4 角单应,不跟踪矩形 + +画布四角放**同心方环**基准标(比 QR finder 更抗透视,且可做亚像素质心定位), +四边中点再各放一个辅助标 → 8 个点解 8-DOF 单应矩阵 H。 + +- H 直接给出"画布坐标 → 图像坐标"的完整映射,倾斜/旋转/透视全部被吸收; +- 采样时用 H 逆映射,**不需要把图像旋正**,省掉一次全帧变换; +- 8 点冗余 → 遮挡 1~2 个标仍可解(最小二乘 + RANSAC 剔除)。 + +### 2.5 永不完全丢锁:三级恢复 + +``` +L1 窄窗跟踪 预测点 ±12 px 每帧,成本 ~4 × 625 px + ↓ 连续 3 帧失败 +L2 陀螺预测窗 预测点 ±40 px + 放宽阈值 成本 ~4 × 6400 px + ↓ 持续 0.5 s 失败 +L3 全幅重捕获 降采样 1/4 的粗搜 + 精定位 +``` + +关键是**永远保留最后一次有效的 H**,L3 也以它为先验起点。 +现有的"10 次 miss 后 `lockRegion = null` 全量重来"必须删掉。 + +### 2.6 诚实提醒 + +目标 B(3.0 px/模块 @1080p60)在手持下几乎不可能长时间守住。 +App 应持续统计陀螺 RMS,超阈值时明确提示"请靠稳桌沿或使用支架", +并在支架模式下自动切到更激进的参数档。目标 A(3.5 px/模块 @24fps)手持可行。 + +--- + +## 3. 需求三:QFT5 位阵列格式 + +### 3.1 画布布局 + +``` +┌─◎──────────────────────────────────────◎─┐ ◎ = 同心方环基准标(4 角 + 4 边中点) +│ ▓▓░░▓░▓▓░ 帧序号条纹(上) ░▓░▓▓░░▓▓ │ 帧计数 8 bit,撕裂检测用 +├──────────────────────────────────────────┤ +│ 条带 0 ← 独立喷泉包(头 + 数据 + CRC)│ +│ 条带 1 │ +◎ 条带 … ◎ 共 12 条(@1080p 每条约 28 模块高) +│ 条带 11 │ +├──────────────────────────────────────────┤ +│ ▓▓░░▓░▓▓░ 帧序号条纹(下) ░▓░▓▓░░▓▓ │ +└─◎──────────────────────────────────────◎─┘ +``` + +@1080p / 3.0 px/模块 → **608 × 342 模块 = 207 936 模块/画布** +减去基准标、条纹、参考网格(约 4%)与喷泉冗余(15%)→ **净 21 209 B/画布**。 + +### 3.2 抗撕裂的水平条带设计(本方案的关键) + +卷帘快门自上而下扫描,读出耗时 T_r ≈ 16~20 ms。期间显示器换页会在某一行产生撕裂: +上半部分是显示帧 k,下半部分是 k+1。 + +**如果画布是一个整体(如单个大 QR),撕裂帧 100% 报废。** + +改成 12 条独立水平条带后,每条带自带头部(条带序号 + 喷泉种子 + CRC),于是: + +- 撕裂线只穿过 **1 条**条带 → 只损失 1/12; +- 撕裂线上方的 11 条属于帧 k,下方的属于帧 k+1,**两边都是有效的新数据**; +- 效率 = (B − T_r·f_display) / B。@60 FPS、T_r=16 ms、B=12 → **92%**。 + +**推论:显示帧率直接设成相机帧率即可,不需要任何显示/相机同步机制。** +这消除了整个方案里最难工程化的一环。 + +(条带数 B 的选择:B 越大抗撕裂越好,但每条带的头部开销占比上升。 +B=12 时头部开销约 0.9%,是合理平衡点。) + +### 3.3 帧序号条纹(tear guard) + +上下各一条 8 格黑白条纹,编码同一个 8-bit 帧计数。解码时先读这 16 个采样点: + +- 上下一致 → 整帧属于同一显示帧,全部 12 条带可信; +- 不一致 → 存在撕裂,用二分法在条带边界上定位撕裂行,只丢弃跨越它的那一条。 + +成本:16 次采样。收益:把"撕裂帧全废"变成"损失 1/12"。 + +### 3.4 参考模块网格(局部阈值) + +屏幕亮度不均、镜头暗角、moiré 会让全局阈值失效。 +每 **16×16 模块**嵌入一对已知的黑/白参考模块(开销 0.78%),解码时: + +``` +读取所有参考对 → 得到稀疏的 (black_level, white_level) 采样点 +→ 双线性插值出全画布的阈值面 threshold(x,y) = (black + white) / 2 +→ 每个数据模块与其所在位置的插值阈值比较 +``` + +这同时天然抵抗屏幕 PWM 调光造成的整体亮度波动。 + +### 3.5 喷泉码(条带级) + +每条带 = 一个独立喷泉包: + +``` +条带头(12 B):magic(2) | sessionId(4) | blockId(2) | seed(4) +条带数据:~1 750 B +CRC32(4 B) +``` + +- 文件按 **块(block)** 切分,每块 64 个源分片; +- 编码包 = 块内随机子集的 XOR,参与集合由 `seed` 经约定 PRNG 还原; +- 前 64 个包用系统码(原始分片本身),信道好时零解码开销; +- 接收端每块维护 64×64 的 GF(2) 矩阵,高斯消元求解; +- 冗余 15%(即平均收到 1.15×N 个包即可解出)。 + +Windows 端可直接用 `raptorq` crate;Android 端建议自研分组 XOR + 高斯消元, +两端算法必须逐位对齐(提供跨语言测试向量)。 + +### 3.6 采样解码器(替代 ZXing) + +比 RS 解码更简单,纯整数运算: + +``` +1. tear guard 检查(16 次采样) → 决定丢弃哪条带 +2. 模糊门控(陀螺仪) → 可能直接跳过整帧 +3. 从跟踪状态取单应矩阵 H +4. 读参考网格 → 插值阈值面 +5. 对每个模块:用 H 逆映射取中心点采样,与阈值比较 → 1 bit + (只取中心单点,不做邻域平均——3 px/模块下中心点信噪比已足够,速度快 3 倍) +6. 逐条带校验 CRC32 → 通过的送入喷泉解码器 +``` + +复杂度 O(模块数),@1080p 每帧 208 K 次采样。可用 NEON 向量化, +或直接在 `ImageProxy` 的 Y 平面上按行做(内存访问连续)。 +实测预算:60 FPS 下约 12.5 M 采样/s,中端 SoC 单核即可,不需要 GPU。 + +**并行结构**:`analyze()` 回调只做"按 H 计算 ROI 并 memcpy Y 平面"然后立即 +`image.close()` 返回;采样解码与喷泉解码交给 2~3 个 worker 线程。 +注意现有 `GrayFrameBuffer` 是单实例、非线程安全的,必须改成 per-worker 实例。 + +--- + +## 4. Windows 发送端 + +### 4.1 显示管线(必须先修) + +现状:`qr.rs` 生成 1024×1024 的 `ColorImage`(RGBA)= **4 MiB/帧**, +每帧 `texture.set()` 上传 GPU;`optical_cache.rs` 按 4 MiB/页 计算容量, +最多占用 **768 MiB** 内存。60 FPS 下这是 240 MB/s 的分配与上传。 + +改法:上传 **模块级纹理**(608×342 = 208 KB 灰度),用 `TextureOptions::NEAREST` +让 GPU 放大。绘制矩形边长取模块数的整数倍(608 × 3 = 1824 px),避免不均匀缩放。 + +- 纹理上传:4 MiB → 208 KB(**减少 95%**,且不随显示尺寸增长) +- 预编码缓存:768 MiB → < 20 MiB +- 60 FPS 变得毫无压力 + +### 4.2 换页时序 + +现有 `last_advance.elapsed() >= interval` 轮询会产生抖动。 +改为**按 vsync 计数换页**:60 Hz 屏每 1 个 vsync 换一页 = 精确 60 FPS; +每 2 个 vsync 换一页 = 精确 30 FPS。保证每帧显示时长完全一致。 + +### 4.3 显示器体检 + +启动光学模式时检测:刷新率、画布区可用逻辑像素宽度、DPI 缩放。 +不满足"≥60 Hz 且 ≥1824 px"时,明确提示目标 B 不可达并给出当前档位的预计耗时。 + +### 4.4 编码吞吐 + +60 FPS × 21 KB = 1.27 MB/s 的 XOR + 位阵列打包。Rayon 并行下可忽略。 + +--- + +## 5. 分阶段落地 + +| 阶段 | 内容 | 可验证指标 | 风险 | +|---|---|---|---| +| **P1** | Windows 模块级纹理 + vsync 换页 | 稳定 60.0 页/s,内存 < 50 MiB | 低 | +| **P2** | 相机帧率三级锁定 + 闭环验证 + 关 EIS/抗闪烁 + 锁 AF | p95/p50 < 1.30,实测帧率 = 标称 | 低 | +| **P3** | 手动曝光 2~4 ms + 陀螺仪前馈 + 模糊门控 | 10 °/s 晃动下不丢锁,模糊 < 1 px | 中 | +| **P4** | QFT5 画布格式 + 单应跟踪 + 采样解码器 | 单帧 208 K 模块解码 < 12 ms | **高** | +| **P5** | 条带喷泉码(两端对齐 + 跨语言测试向量) | 收包 1.15×N 即可还原 | 中 | +| **P6** | 1080p60 + tear guard + 参数调优 | 目标 A / B 达标 | 中 | + +P1、P2 可以立刻做且零协议风险;P4 是主要工程量(估计是全部工作量的一半)。 + +**建议在 P4 之前先做一个离线验证台**:Windows 端把画布导出成 PNG 序列, +Android 端加一个"从相册读图解码"的调试入口,先在无相机噪声的条件下 +把采样解码器和喷泉码调通,再接实时相机。这能省掉大量难以复现的现场调试。 + +--- + +## 5.1 P0 · 分辨率楔形标定(已实现) + +上表所有数字都建立在一个未经实测的假设上:**px/模块 的真实下限**。 +合成实验显示这个值仅因对焦质量不同就能在 3.1~5.7 之间摆动, +所以它必须先测出来,不能靠推算。工具已在 `scripts/` 下: + +```bash +# 1. 生成标定图(尺寸填显示器的设备像素) +python scripts/wedge_gen.py --width 1920 --height 1080 --out out/wedge + +# 2. 用浏览器打开 out/wedge.html,按 F11 全屏 +# 页面左上角必须显示「缩放 1.000 ✅」,否则测量无效 + +# 3. 手机拍照:大致正立,四个黑色角标全部入画并尽量填满画面 +# 建议在 2~4 个不同距离各拍一张 + +# 4. 分析 +python scripts/wedge_analyze.py --spec out/wedge.json --photo IMG_0001.jpg +``` + +输出每条带的 **实测 px/模块 → 对比度 → 误码率**,并给出 BER=1e-3 的临界点, +以及按该临界点换算的画布净载荷与各帧率下的预计传输耗时。 + +`--analysis-width` 默认 1920,即把 12MP 原片降采样到 1080p,模拟真实的 +ImageAnalysis 流;改成 1280 可直接对比 720p 分析流的能力差距。 + +自检(合成相机模型,无需硬件):`python scripts/wedge_selftest.py`。 + +### 标定结果如何反馈到本方案 + +| 实测临界 px/模块 | 结论 | +|---|---| +| ≤ 2.6 | 目标 B 有余量,可考虑 §5.2 的六边形点阵进一步加码 | +| 2.6 ~ 3.2 | 按本方案原样实施,目标 B 余量约 10% | +| 3.2 ~ 4.0 | 目标 B 不可达;目标 A 仍可达。需下调指标或提高分析分辨率 | +| > 4.0 | 光学链路能力远低于预期,应优先排查对焦/曝光(§1.2、§2.1) | + +### 一个必须修正的设计细节 + +标定工具的误码率输出暴露了 §3.5 的一个缺口:**条带只有 CRC,没有内码**。 +1750 B 的条带有约 14 000 bit,只要 1 bit 错就整条报废。 +若要求带错率 < 13%(喷泉码 15% 冗余能承受的上限), +原始 BER 必须低于 **1e-5**——这对光学信道是很苛刻的。 + +因此条带内部必须加**内码**,形成"内码纠错 + 外层喷泉码纠删"的级联结构 +(与 QR 内部用 RS 是同一思路)。粗估所需冗余 ≈ 48 × BER: + +| 实测原始 BER | 内码冗余 | +|---|---| +| 1e-5 | 可省略 | +| 1e-4 | ~0.5% | +| 1e-3 | ~4.8% | +| 1e-2 | ~48%(此工作点不可用) | + +`wedge_analyze.py` 已按此公式输出所需内码冗余,并计入净载荷估算。 + +--- + +## 6. 达标核算与回退 + +### 达标条件(目标 B) +``` +1080p ImageAnalysis @ 60 FPS × 21 209 B/画布 × 92% 撕裂效率 += 1 143 KB/s → 10 MB / 9.0 s ✅(余量 10%) +``` +余量只有 10%,任一环节退化都会掉出指标。必须全部满足: +手机支持 1080p60 分析、显示器 ≥60 Hz、3.0 px/模块下解码成功率 > 95%、使用支架。 + +### 达标条件(目标 A) +``` +1080p @ 24 FPS × 15 571 B/画布(3.5 px/模块) × 96% += 350 KB/s → 1 MB / 2.9 s ✅(余量 42%) +``` +余量充足,手持可行。**建议把 3.5 px/模块设为默认档。** + +### 回退阶梯 +App 应根据实测能力自动选档,并在 UI 明示当前档位与预计耗时: + +| 档位 | 分析分辨率 | px/模块 | 相机 FPS | 吞吐 | 适用 | +|---|---|---|---|---|---| +| 极速(支架) | 1080p | 3.0 | 60 | 1143 KB/s | 目标 B | +| 标准(手持) | 1080p | 3.5 | 24~30 | 350~438 KB/s | 目标 A | +| 保守 | 720p | 3.5 | 30 | 167 KB/s | 老设备 | +| 兼容 | 720p | 4.0 | 30 | 128 KB/s | 最低保障 | + +### 何时不该用光学 +仓库已有 `QFTSEND2` 扫码直传(`windows/src/sender.rs`:HTTP + Range 续传 + UDP 发现), +10 MB 在局域网下是亚秒级。光学链路应明确定位为**物理隔离场景专用**, +并在选择大文件时主动提示直传方案与两者的预计耗时对比。 diff --git a/scripts/run_all_selftests.py b/scripts/run_all_selftests.py index 2d6e220..a6ff795 100644 --- a/scripts/run_all_selftests.py +++ b/scripts/run_all_selftests.py @@ -13,6 +13,7 @@ scripts = [ 'android_compat_selftest.py', 'single_channel_guard_selftest.py', 'kotlin_host_smoke.py', + 'wedge_selftest.py', ] for name in scripts: print(f'== {name} ==', flush=True) diff --git a/scripts/wedge_analyze.py b/scripts/wedge_analyze.py new file mode 100644 index 0000000..fee4e8d --- /dev/null +++ b/scripts/wedge_analyze.py @@ -0,0 +1,446 @@ +#!/usr/bin/env python3 +"""分析楔形标定图的照片,输出「每模块相机像素数 → 误码率」曲线。 + + python scripts/wedge_analyze.py --spec out/wedge.json --photo IMG_0001.jpg + +流程与真实解码器完全一致,所以测出来的就是真实可用的下限: + 检测四角基准标 → 解单应矩阵 → 按模块中心单点采样 + → 局部均值阈值面 → 判决 → 与期望比特比对 + +--analysis-width 用来模拟手机 ImageAnalysis 流的分辨率(默认 1920,即 1080p)。 +照片本身通常是 12MP,直接分析会高估能力;先降采样到分析流分辨率才有意义。 +""" + +import argparse +import os +import sys + +import numpy as np + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from wedge_common import WedgeSpec, band_bits, module_centers_active # noqa: E402 + + +# ---------------------------------------------------------------- 图像载入 + +def load_gray(path, analysis_width): + from PIL import Image, ImageOps + + image = Image.open(path) + image = ImageOps.exif_transpose(image) + image = image.convert("L") + original = image.size + if analysis_width and image.width > analysis_width: + height = max(1, int(round(image.height * analysis_width / image.width))) + # BOX(面积平均)最接近相机 ISP 的降采样行为 + image = image.resize((analysis_width, height), Image.BOX) + return np.asarray(image, dtype=np.float32), original + + +# ---------------------------------------------------------------- 连通域 + +def otsu(gray): + hist, _ = np.histogram(gray, bins=256, range=(0, 256)) + total = hist.sum() + if total == 0: + return 128.0 + levels = np.arange(256, dtype=np.float64) + w0 = np.cumsum(hist).astype(np.float64) + w1 = total - w0 + s0 = np.cumsum(hist * levels) + total_sum = s0[-1] + valid = (w0 > 0) & (w1 > 0) + if not valid.any(): + return 128.0 + m0 = np.where(w0 > 0, s0 / np.maximum(w0, 1), 0.0) + m1 = np.where(w1 > 0, (total_sum - s0) / np.maximum(w1, 1), 0.0) + between = w0 * w1 * (m0 - m1) ** 2 + between[~valid] = -1.0 + return float(np.argmax(between)) + + +def label_components(mask): + """行程 + 并查集的连通域标记(4 连通)。返回 (labels, count)。""" + height, width = mask.shape + parent = [0] + + def find(a): + while parent[a] != a: + parent[a] = parent[parent[a]] + a = parent[a] + return a + + def union(a, b): + ra, rb = find(a), find(b) + if ra != rb: + parent[max(ra, rb)] = min(ra, rb) + + labels = np.zeros((height, width), dtype=np.int32) + prev_runs = [] + for y in range(height): + row = mask[y] + if not row.any(): + prev_runs = [] + continue + diff = np.diff(np.concatenate(([0], row.view(np.int8), [0]))) + starts = np.flatnonzero(diff == 1) + ends = np.flatnonzero(diff == -1) + runs = [] + for x0, x1 in zip(starts, ends): + parent.append(len(parent)) + current = len(parent) - 1 + for px0, px1, plabel in prev_runs: + if px0 < x1 and x0 < px1: + union(current, plabel) + labels[y, x0:x1] = current + runs.append((x0, x1, current)) + prev_runs = runs + + flat = labels.reshape(-1) + nonzero = flat > 0 + if nonzero.any(): + roots = np.array([find(i) for i in range(len(parent))], dtype=np.int32) + flat[nonzero] = roots[flat[nonzero]] + unique, remapped = np.unique(flat[nonzero], return_inverse=True) + flat[nonzero] = remapped + 1 + count = len(unique) + else: + count = 0 + return labels, count + + +def find_markers(gray, debug=None): + """返回四个基准标中心(照片像素),顺序 TL, TR, BR, BL。""" + height, width = gray.shape + scale = max(1.0, width / 1200.0) + if scale > 1.0: + from PIL import Image + small = np.asarray( + Image.fromarray(gray.astype(np.uint8)).resize( + (int(width / scale), int(height / scale)), Image.BOX), + dtype=np.float32) + else: + small = gray + + threshold = otsu(small) + mask = small < threshold + labels, count = label_components(mask) + if count == 0: + raise RuntimeError("照片里找不到任何暗色区域") + + area_image = small.shape[0] * small.shape[1] + candidates = [] + for index in range(1, count + 1): + ys, xs = np.nonzero(labels == index) + area = len(xs) + if area < 24 or area > area_image * 0.02: + continue + x0, x1 = xs.min(), xs.max() + 1 + y0, y1 = ys.min(), ys.max() + 1 + bw, bh = x1 - x0, y1 - y0 + aspect = bw / float(bh) + if not 0.55 < aspect < 1.8: + continue + if area / float(bw * bh) < 0.72: # 实心方块 + continue + # 外围一圈必须是白的(黑方块落在白底上),排除画面外的暗区与数据模块 + pad = int(max(bw, bh) * 0.6) + 2 + ry0, ry1 = max(0, y0 - pad), min(small.shape[0], y1 + pad) + rx0, rx1 = max(0, x0 - pad), min(small.shape[1], x1 + pad) + ring = small[ry0:ry1, rx0:rx1].copy() + inner = ring[y0 - ry0:y1 - ry0, x0 - rx0:x1 - rx0] + ring_sum = ring.sum() - inner.sum() + ring_n = ring.size - inner.size + if ring_n <= 0 or ring_sum / ring_n < threshold * 1.15: + continue + candidates.append((area, (xs.mean() + 0.5) * scale, (ys.mean() + 0.5) * scale, + bw * scale, bh * scale)) + + if len(candidates) < 4: + raise RuntimeError("只找到 %d 个候选基准标(需要 4 个)。" + "请让四个黑色角标全部进入画面,并保持画面明亮、对焦清晰。" + % len(candidates)) + + candidates.sort(key=lambda c: -c[0]) + pool = candidates[:24] + pts = np.array([[c[1], c[2]] for c in pool]) + sizes = np.array([max(c[3], c[4]) for c in pool]) + + def pick(score): + return int(np.argmax(score)) + + tl = pick(-(pts[:, 0] + pts[:, 1])) + br = pick(pts[:, 0] + pts[:, 1]) + tr = pick(pts[:, 0] - pts[:, 1]) + bl = pick(pts[:, 1] - pts[:, 0]) + chosen = [tl, tr, br, bl] + if len(set(chosen)) != 4: + raise RuntimeError("角标定位歧义,请正对屏幕重拍,避免过大的倾斜") + + refined = [] + for index in chosen: + cx, cy, size = pts[index, 0], pts[index, 1], sizes[index] + refined.append(refine_centroid(gray, cx, cy, size)) + if debug is not None: + debug["markers_raw"] = pts[chosen].tolist() + return refined + + +def refine_centroid(gray, cx, cy, size): + """在全分辨率图上做灰度加权质心,取得亚像素中心。""" + half = max(4.0, size * 0.9) + x0 = int(max(0, np.floor(cx - half))) + x1 = int(min(gray.shape[1], np.ceil(cx + half))) + y0 = int(max(0, np.floor(cy - half))) + y1 = int(min(gray.shape[0], np.ceil(cy + half))) + patch = gray[y0:y1, x0:x1] + if patch.size == 0: + return (float(cx), float(cy)) + level = otsu(patch) + weight = np.clip(level - patch, 0, None) + total = weight.sum() + if total <= 0: + return (float(cx), float(cy)) + ys, xs = np.mgrid[y0:y1, x0:x1] + return (float((weight * xs).sum() / total) + 0.5, + float((weight * ys).sum() / total) + 0.5) + + +# ---------------------------------------------------------------- 几何 + +def homography(src, dst): + """求解 src(4×2) → dst(4×2) 的 3×3 单应矩阵(h8 = 1)。""" + a = np.zeros((8, 8), dtype=np.float64) + b = np.zeros(8, dtype=np.float64) + for i in range(4): + x, y = src[i] + u, v = dst[i] + a[2 * i] = [x, y, 1, 0, 0, 0, -x * u, -y * u] + b[2 * i] = u + a[2 * i + 1] = [0, 0, 0, x, y, 1, -x * v, -y * v] + b[2 * i + 1] = v + h = np.linalg.solve(a, b) + return np.append(h, 1.0).reshape(3, 3) + + +def project(h, points): + """单应变换。逐分量展开而非 matmul:大点集下更省内存, + 也避开 BLAS 在大矩阵乘法上偶发的伪浮点警告。""" + pts = np.asarray(points, dtype=np.float64) + x = pts[..., 0] + y = pts[..., 1] + u = h[0, 0] * x + h[0, 1] * y + h[0, 2] + v = h[1, 0] * x + h[1, 1] * y + h[1, 2] + w = h[2, 0] * x + h[2, 1] * y + h[2, 2] + # w 趋近 0 表示该点被映射到无穷远(逆映射时落在画面之外), + # 夹住分母避免 inf/nan 污染后续采样。 + w = np.where(np.abs(w) < 1e-12, 1e-12, w) + return np.stack([u / w, v / w], axis=-1) + + +def local_scale(h, x, y): + """单应矩阵在 (x, y) 处的各向同性放大率:照片像素 / 显示像素。""" + u = h[0, 0] * x + h[0, 1] * y + h[0, 2] + v = h[1, 0] * x + h[1, 1] * y + h[1, 2] + w = h[2, 0] * x + h[2, 1] * y + h[2, 2] + dudx = (h[0, 0] * w - u * h[2, 0]) / w ** 2 + dudy = (h[0, 1] * w - u * h[2, 1]) / w ** 2 + dvdx = (h[1, 0] * w - v * h[2, 0]) / w ** 2 + dvdy = (h[1, 1] * w - v * h[2, 1]) / w ** 2 + return float(np.sqrt(abs(dudx * dvdy - dudy * dvdx))) + + +def bilinear(gray, points): + height, width = gray.shape + x = np.clip(points[..., 0], 0, width - 1.001) + y = np.clip(points[..., 1], 0, height - 1.001) + x0 = np.floor(x).astype(np.int32) + y0 = np.floor(y).astype(np.int32) + fx = x - x0 + fy = y - y0 + v00 = gray[y0, x0] + v01 = gray[y0, x0 + 1] + v10 = gray[y0 + 1, x0] + v11 = gray[y0 + 1, x0 + 1] + return (v00 * (1 - fx) * (1 - fy) + v01 * fx * (1 - fy) + + v10 * (1 - fx) * fy + v11 * fx * fy) + + +def box_mean(values, ky, kx): + """边界收缩的滑动平均,用作局部阈值面。""" + rows, cols = values.shape + ky = max(1, min(ky if ky % 2 == 1 else ky - 1, rows if rows % 2 == 1 else rows - 1)) + kx = max(1, min(kx if kx % 2 == 1 else kx - 1, cols if cols % 2 == 1 else cols - 1)) + ry, rx = ky // 2, kx // 2 + + padded = np.pad(values, ((ry, ry), (rx, rx)), mode="edge") + integral = np.zeros((padded.shape[0] + 1, padded.shape[1] + 1), dtype=np.float64) + integral[1:, 1:] = padded.cumsum(axis=0).cumsum(axis=1) + total = (integral[ky:ky + rows, kx:kx + cols] + - integral[0:rows, kx:kx + cols] + - integral[ky:ky + rows, 0:cols] + + integral[0:rows, 0:cols]) + return total / float(ky * kx) + + +# ---------------------------------------------------------------- 分析 + +def analyze_band(gray, spec, band, h, threshold_window): + centers = module_centers_active(band, spec) + photo = project(h, centers) + samples = bilinear(gray, photo) + + expected = band_bits(band) # 1 = 黑 + threshold = box_mean(samples, threshold_window, threshold_window) + decoded = (samples < threshold).astype(np.uint8) # 比阈值暗 → 判为黑(1) + + errors = int(np.count_nonzero(decoded != expected)) + total = expected.size + ber = errors / float(total) + + white = samples[expected == 0] + black = samples[expected == 1] + if white.size and black.size: + mw, mb = float(white.mean()), float(black.mean()) + contrast = (mw - mb) / (mw + mb) if (mw + mb) > 0 else 0.0 + else: + mw = mb = contrast = 0.0 + + cx = band.x + band.width_px / 2.0 + cy = band.y + band.height_px / 2.0 + px_per_module = local_scale(h, cx, cy) * band.pitch_px + + return { + "index": band.index, + "pitch_px": band.pitch_px, + "px_per_module": px_per_module, + "modules": total, + "errors": errors, + "ber": ber, + "contrast": contrast, + "white": mw, + "black": mb, + } + + +def inner_fec_overhead(ber): + """把给定原始误码率压到可忽略的带错率,所需的内码冗余(粗估)。 + + 条带级 CRC 下,1750 B 的条带只要有 1 bit 错就整条报废, + 因此必须用内码(RS/LDPC)先把原始 BER 吃掉,外层喷泉码只负责丢包。 + GF(256) 的 RS:字节错率 ≈ 8·BER,留 3 倍余量 → 冗余 ≈ 48·BER。 + """ + if ber <= 0: + return 0.0 + return min(1.0, 48.0 * ber) + + +def verdict(ber): + if ber == 0: + return "✅ 无误码" + if ber < 1e-3: + return "✅ 可用" + if ber < 1e-2: + return "⚠️ 勉强" + return "❌ 不可用" + + +def crossing(rows, limit): + """在 BER-px/模块 曲线上插值出 BER 恰好等于 limit 的位置。""" + ordered = sorted(rows, key=lambda r: r["px_per_module"]) + for a, b in zip(ordered, ordered[1:]): + if a["ber"] > limit >= b["ber"]: + ya, yb = np.log10(max(a["ber"], 1e-9)), np.log10(max(b["ber"], 1e-9)) + if abs(yb - ya) < 1e-12: + return b["px_per_module"] + t = (np.log10(limit) - ya) / (yb - ya) + return a["px_per_module"] + t * (b["px_per_module"] - a["px_per_module"]) + return None + + +def write_debug_image(path, gray, spec, h, markers): + from PIL import Image, ImageDraw + + image = Image.fromarray(gray.astype(np.uint8)).convert("RGB") + draw = ImageDraw.Draw(image) + for x, y in markers: + draw.ellipse([x - 9, y - 9, x + 9, y + 9], outline=(255, 40, 40), width=3) + corners = project(h, spec.active_corners()) + draw.polygon([tuple(p) for p in corners], outline=(40, 220, 255)) + for band in spec.bands: + rect = [(band.x, band.y), + (band.x + band.width_px, band.y), + (band.x + band.width_px, band.y + band.height_px), + (band.x, band.y + band.height_px)] + pts = project(h, rect) + draw.polygon([tuple(p) for p in pts], outline=(80, 255, 120)) + image.save(path) + + +def main() -> int: + parser = argparse.ArgumentParser(description="分析楔形标定图照片") + parser.add_argument("--spec", required=True, help="wedge_gen.py 产出的 .json") + parser.add_argument("--photo", required=True, help="手机拍摄的照片") + parser.add_argument("--analysis-width", type=int, default=1920, + help="模拟 ImageAnalysis 流宽度,0 表示不降采样") + parser.add_argument("--threshold-window", type=int, default=17, + help="局部阈值面的窗口边长(模块数)") + parser.add_argument("--debug-image", type=str, default=None, + help="写出一张叠加了定位结果的诊断图") + args = parser.parse_args() + + spec = WedgeSpec.load(args.spec) + gray, original = load_gray(args.photo, args.analysis_width) + + debug = {} + markers = find_markers(gray, debug) + h = homography(spec.active_corners(), markers) + + rows = [analyze_band(gray, spec, band, h, args.threshold_window) for band in spec.bands] + + if args.debug_image: + write_debug_image(args.debug_image, gray, spec, h, markers) + + width_px = float(np.hypot(markers[1][0] - markers[0][0], markers[1][1] - markers[0][1])) + print("照片:%s" % os.path.basename(args.photo)) + print("原始尺寸 %d×%d → 分析尺寸 %d×%d" % (original[0], original[1], gray.shape[1], gray.shape[0])) + print("标定图 active 宽 %d 显示像素 → 照片中 %.1f 像素(放大率 %.3f)" + % (spec.active_w, width_px, width_px / spec.active_w)) + print() + print("%-6s %-9s %-11s %-9s %-10s %-11s %s" + % ("条带", "显示pitch", "px/模块", "对比度", "模块数", "误码率", "判定")) + for row in rows: + print("%-6d %-9d %-11.2f %-9.3f %-10d %-11s %s" + % (row["index"], row["pitch_px"], row["px_per_module"], row["contrast"], + row["modules"], + "0" if row["ber"] == 0 else "%.2e" % row["ber"], + verdict(row["ber"]))) + + print() + limit = crossing(rows, 1e-3) + if limit is not None: + print("BER=1e-3 的临界点:约 %.2f px/模块" % limit) + usable = [r for r in rows if r["ber"] < 1e-3] + if usable: + best = min(usable, key=lambda r: r["px_per_module"]) + print("本次实测可用下限:%.2f px/模块(BER %s,内码冗余需 %.1f%%)" + % (best["px_per_module"], + "0" if best["ber"] == 0 else "%.1e" % best["ber"], + inner_fec_overhead(best["ber"]) * 100)) + area = gray.shape[0] * gray.shape[1] * 0.95 + modules = area / best["px_per_module"] ** 2 + payload = modules * (1 - 0.04) * (1 - 0.15 - inner_fec_overhead(best["ber"])) / 8 + print("→ 按此下限,%d×%d 分析流每画布净载荷约 %.0f B" + % (gray.shape[1], gray.shape[0], max(payload, 0))) + for fps in (24, 30, 60): + rate = payload * fps * 0.92 + if rate > 0: + print(" @%d FPS:%.0f KB/s 1MB %.2fs 10MB %.2fs" + % (fps, rate / 1024, 1048576 / rate, 10485760 / rate)) + else: + print("所有条带都超过 1e-3,请靠近屏幕重拍,或改用更大的 --pitches") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/wedge_common.py b/scripts/wedge_common.py new file mode 100644 index 0000000..781d67a --- /dev/null +++ b/scripts/wedge_common.py @@ -0,0 +1,229 @@ +#!/usr/bin/env python3 +"""QFT 分辨率楔形标定图 —— 共享规格、PRNG 与渲染。 + +用途:在屏幕上显示一张同时包含多种模块尺寸(pitch)的伪随机二值图案, +手机拍一张照片,由 wedge_analyze.py 反解出「每模块相机像素数 → 误码率」曲线, +从而实测出本套硬件真正的 px/模块 下限。这个下限直接决定 QFT5 位阵列的容量。 + +坐标系 +------ +canvas 坐标:整张标定图的像素坐标,原点左上。 +active 坐标:以左上角基准标**中心**为原点的坐标系;四个基准标中心构成 active 矩形。 + 分析端解出的单应矩阵就是 active → 照片像素 的映射,因此所有条带几何 + 都用 active 坐标描述,与画布边距无关。 + +约定 +---- +- 模块 bit == 1 → 黑 (0),bit == 0 → 白 (255)。 +- PRNG 为 SplitMix64,Rust / Kotlin 移植时必须逐位一致(见 splitmix64)。 +- 模块 (r, c) 的比特序号 k = r * cols + c;取第 k//64 个 64 位输出的第 k%64 位(LSB 起)。 +""" + +from dataclasses import dataclass, asdict +from typing import List, Optional +import json + +MASK64 = (1 << 64) - 1 +GOLDEN = 0x9E3779B97F4A7C15 + +SPEC_VERSION = 1 +DEFAULT_PITCHES = [10, 8, 6, 5, 4, 3, 2] +DEFAULT_SEED = 20260810 + +# 画布留白与基准标尺寸(canvas 像素) +MARGIN_PX = 40 +MARKER_PX = 56 +INSET_PX = 64 # 数据区相对 active 矩形的内缩,保证基准标周围留白 +GUTTER_PX = 8 # 条带间隔 + + +def splitmix64(state: int): + """SplitMix64 生成器。返回 (下一状态, 64 位输出)。""" + state = (state + GOLDEN) & MASK64 + z = state + z = ((z ^ (z >> 30)) * 0xBF58476D1CE4E5B9) & MASK64 + z = ((z ^ (z >> 27)) * 0x94D049BB133111EB) & MASK64 + return state, z ^ (z >> 31) + + +def band_seed(seed: int, index: int) -> int: + return (seed ^ ((GOLDEN * (index + 1)) & MASK64)) & MASK64 + + +@dataclass +class BandSpec: + index: int + pitch_px: int + cols: int + rows: int + x: int # active 坐标 + y: int + seed: int + + @property + def width_px(self) -> int: + return self.cols * self.pitch_px + + @property + def height_px(self) -> int: + return self.rows * self.pitch_px + + @property + def modules(self) -> int: + return self.cols * self.rows + + +@dataclass +class WedgeSpec: + version: int + canvas_w: int + canvas_h: int + margin_px: int + marker_px: int + inset_px: int + gutter_px: int + seed: int + active_w: int # active 矩形尺寸(= 基准标中心间距) + active_h: int + bands: List[BandSpec] + + def to_json(self, indent: Optional[int] = 2) -> str: + payload = asdict(self) + return json.dumps(payload, indent=indent, ensure_ascii=False) + + @staticmethod + def from_dict(payload: dict) -> "WedgeSpec": + bands = [BandSpec(**b) for b in payload["bands"]] + rest = {k: v for k, v in payload.items() if k != "bands"} + return WedgeSpec(bands=bands, **rest) + + @staticmethod + def load(path) -> "WedgeSpec": + with open(path, "r", encoding="utf-8") as fh: + return WedgeSpec.from_dict(json.load(fh)) + + def marker_centers_canvas(self): + """四个基准标中心在 canvas 坐标下的位置,顺序 TL, TR, BR, BL。""" + half = self.marker_px / 2.0 + x0 = self.margin_px + half + y0 = self.margin_px + half + x1 = self.canvas_w - self.margin_px - half + y1 = self.canvas_h - self.margin_px - half + return [(x0, y0), (x1, y0), (x1, y1), (x0, y1)] + + def active_corners(self): + """active 坐标下的四角,顺序与 marker_centers_canvas 一致。""" + return [(0.0, 0.0), (float(self.active_w), 0.0), + (float(self.active_w), float(self.active_h)), (0.0, float(self.active_h))] + + +def build_spec(canvas_w: int = 1920, + canvas_h: int = 1080, + pitches: Optional[List[int]] = None, + seed: int = DEFAULT_SEED, + margin_px: int = MARGIN_PX, + marker_px: int = MARKER_PX, + inset_px: int = INSET_PX, + gutter_px: int = GUTTER_PX) -> WedgeSpec: + pitches = list(pitches or DEFAULT_PITCHES) + if not pitches: + raise ValueError("至少需要一个 pitch") + if any(p < 1 for p in pitches): + raise ValueError("pitch 必须 >= 1 显示像素") + + active_w = canvas_w - 2 * margin_px - marker_px + active_h = canvas_h - 2 * margin_px - marker_px + data_w = active_w - 2 * inset_px + data_h = active_h - 2 * inset_px + if data_w < 64 or data_h < 64: + raise ValueError("画布太小,数据区不足") + + n = len(pitches) + band_h = (data_h - (n - 1) * gutter_px) // n + if band_h < max(pitches): + raise ValueError("画布高度不足以容纳全部条带") + + bands: List[BandSpec] = [] + for i, pitch in enumerate(pitches): + cols = data_w // pitch + rows = band_h // pitch + if cols < 8 or rows < 2: + raise ValueError("pitch %d 下条带尺寸过小" % pitch) + bands.append(BandSpec( + index=i, + pitch_px=pitch, + cols=cols, + rows=rows, + x=inset_px, + y=inset_px + i * (band_h + gutter_px), + seed=band_seed(seed, i), + )) + + return WedgeSpec( + version=SPEC_VERSION, + canvas_w=canvas_w, + canvas_h=canvas_h, + margin_px=margin_px, + marker_px=marker_px, + inset_px=inset_px, + gutter_px=gutter_px, + seed=seed, + active_w=active_w, + active_h=active_h, + bands=bands, + ) + + +def band_bits(band: BandSpec): + """返回形状 (rows, cols) 的 uint8 数组,1 = 黑模块。""" + import numpy as np + + total = band.modules + words = (total + 63) // 64 + state = band.seed + out = np.empty(words, dtype=np.uint64) + for i in range(words): + state, value = splitmix64(state) + out[i] = value + bits = np.unpackbits(out.view(np.uint8).reshape(words, 8), axis=1, bitorder="little") + # view(uint8) 在小端机器上给出 LSB->MSB 的字节序,配合 bitorder="little" + # 即得到 k 递增方向的比特流。 + bits = bits.reshape(-1)[:total] + return bits.reshape(band.rows, band.cols) + + +def render(spec: WedgeSpec): + """渲染整张标定图,返回 (H, W) 的 uint8 灰度数组。""" + import numpy as np + + canvas = np.full((spec.canvas_h, spec.canvas_w), 255, dtype=np.uint8) + + # active 原点在 canvas 中的位置 = 左上基准标中心 + ox = spec.margin_px + spec.marker_px / 2.0 + oy = spec.margin_px + spec.marker_px / 2.0 + + # 四个实心黑方块基准标,中心落在 active 四角 + half = spec.marker_px // 2 + for cx, cy in spec.marker_centers_canvas(): + x0, y0 = int(round(cx)) - half, int(round(cy)) - half + canvas[y0:y0 + spec.marker_px, x0:x0 + spec.marker_px] = 0 + + for band in spec.bands: + bits = band_bits(band) + block = np.repeat(np.repeat(bits, band.pitch_px, axis=0), band.pitch_px, axis=1) + px = int(round(ox + band.x)) + py = int(round(oy + band.y)) + canvas[py:py + block.shape[0], px:px + block.shape[1]] = np.where(block == 1, 0, 255) + + return canvas + + +def module_centers_active(band: BandSpec, spec: WedgeSpec): + """返回该条带全部模块中心的 active 坐标,形状 (rows, cols, 2)。""" + import numpy as np + + del spec # 条带 x/y 已是 active 坐标,无需画布信息 + cx = band.x + (np.arange(band.cols) + 0.5) * band.pitch_px + cy = band.y + (np.arange(band.rows) + 0.5) * band.pitch_px + gx, gy = np.meshgrid(cx, cy) + return np.stack([gx, gy], axis=-1) diff --git a/scripts/wedge_gen.py b/scripts/wedge_gen.py new file mode 100644 index 0000000..c639546 --- /dev/null +++ b/scripts/wedge_gen.py @@ -0,0 +1,132 @@ +#!/usr/bin/env python3 +"""生成 QFT 分辨率楔形标定图。 + + python scripts/wedge_gen.py --width 1920 --height 1080 --out out/wedge + +产出三个文件: + .png 标定图本体(必须 1:1 显示,任何缩放都会让测量失效) + .json 规格,wedge_analyze.py 用它反解几何与期望比特 + .html 全屏 1:1 查看器,自带缩放校验 + +显示方法(二选一): + A. 用浏览器打开 .html,按 F11 全屏。页面会显示「缩放 1.000 ✅」才算有效。 + B. 任何能保证 100% 原始像素显示的看图工具,且系统 DPI 缩放为 100%。 + +拍摄方法: + - 手机大致正立(旋转 < 45°),让四个黑色角标都在画面内且尽量填满画面; + - 关闭闪光灯,对焦到屏幕上; + - 建议在 2~4 个不同距离各拍一张,这样能把 px/模块 曲线的采样点连起来。 +""" + +import argparse +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from wedge_common import build_spec, render, DEFAULT_PITCHES, DEFAULT_SEED # noqa: E402 + +VIEWER_HTML = """ + +QFT 标定图 1:1 查看器 + +
+
测量中…(按 H 隐藏此框,F11 全屏)
+ +""" + + +def main() -> int: + parser = argparse.ArgumentParser(description="生成 QFT 分辨率楔形标定图") + parser.add_argument("--width", type=int, default=1920, help="画布宽(显示设备像素)") + parser.add_argument("--height", type=int, default=1080, help="画布高(显示设备像素)") + parser.add_argument("--pitches", type=str, default=",".join(str(p) for p in DEFAULT_PITCHES), + help="各条带的模块尺寸,单位显示像素,逗号分隔(必须为整数)") + parser.add_argument("--seed", type=int, default=DEFAULT_SEED) + parser.add_argument("--out", type=str, default="out/wedge", help="输出前缀,不带扩展名") + args = parser.parse_args() + + try: + pitches = [int(p) for p in args.pitches.split(",") if p.strip()] + except ValueError: + print("--pitches 必须是逗号分隔的整数", file=sys.stderr) + return 2 + + try: + spec = build_spec(args.width, args.height, pitches, args.seed) + except ValueError as exc: + print("规格无效:%s" % exc, file=sys.stderr) + return 2 + + from PIL import Image + + canvas = render(spec) + out_dir = os.path.dirname(os.path.abspath(args.out)) + if out_dir: + os.makedirs(out_dir, exist_ok=True) + + png_path = args.out + ".png" + json_path = args.out + ".json" + html_path = args.out + ".html" + + Image.fromarray(canvas).save(png_path, optimize=True) + with open(json_path, "w", encoding="utf-8") as fh: + fh.write(spec.to_json()) + with open(html_path, "w", encoding="utf-8") as fh: + fh.write(VIEWER_HTML.replace("__PNG__", os.path.basename(png_path))) + + print("已生成:") + print(" %s %d×%d" % (png_path, spec.canvas_w, spec.canvas_h)) + print(" %s" % json_path) + print(" %s ← 用浏览器打开并按 F11 全屏" % html_path) + print() + print("条带(模块尺寸以显示像素计):") + total = 0 + for band in spec.bands: + total += band.modules + print(" #%d pitch=%2d px %4d×%-3d = %6d 模块" + % (band.index, band.pitch_px, band.cols, band.rows, band.modules)) + print(" 合计 %d 模块" % total) + print() + print("拍摄后运行:python scripts/wedge_analyze.py --spec %s --photo <照片>" % json_path) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/wedge_selftest.py b/scripts/wedge_selftest.py new file mode 100644 index 0000000..9fbf4bf --- /dev/null +++ b/scripts/wedge_selftest.py @@ -0,0 +1,162 @@ +#!/usr/bin/env python3 +"""楔形标定工具自检:用合成相机模型端到端验证,无需真实硬件。 + +合成链路刻意模拟真实拍摄里会出问题的每一环: + 透视倾斜 → 镜头模糊 → 传感器面积平均降采样 → 亮度梯度 + 暗角 → 噪声 → JPEG + +通过判据: + 1. 四个基准标能在暗背景 + 亮度不均的场景里被找到; + 2. 单应矩阵反解出的放大率与合成时用的真值一致(误差 < 1%); + 3. 大 pitch 条带零误码,小 pitch 条带明显劣化(曲线单调); + 4. BER=1e-3 的临界点落在合理区间。 +""" + +import os +import subprocess +import sys +import tempfile + +import numpy as np + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from wedge_common import build_spec, render # noqa: E402 +import wedge_analyze as wa # noqa: E402 + + +def warp_into_scene(canvas, scene_size, corners_dst): + """把画布按给定四角透视贴进场景(逆映射 + 双线性)。""" + scene_w, scene_h = scene_size + src = [(0, 0), (canvas.shape[1], 0), (canvas.shape[1], canvas.shape[0]), (0, canvas.shape[0])] + inverse = wa.homography(corners_dst, src) + + ys, xs = np.mgrid[0:scene_h, 0:scene_w] + pts = np.stack([xs.ravel(), ys.ravel()], axis=-1).astype(np.float64) + mapped = wa.project(inverse, pts) + mx, my = mapped[:, 0], mapped[:, 1] + + inside = (mx >= 0) & (mx < canvas.shape[1] - 1) & (my >= 0) & (my < canvas.shape[0] - 1) + scene = np.full(scene_h * scene_w, 26.0, dtype=np.float32) # 暗背景 = 房间/边框 + if inside.any(): + sample = wa.bilinear(canvas.astype(np.float32), mapped[inside]) + scene[inside] = sample + return scene.reshape(scene_h, scene_w) + + +def synth_photo(canvas, tilt=0.018, blur=1.1, scene_scale=1.5, + analysis_width=1920, noise=1.6, seed=7): + rng = np.random.default_rng(seed) + scene_w = int(canvas.shape[1] * scene_scale) + scene_h = int(canvas.shape[0] * scene_scale) + + # 画布占场景约 92%,并带一点透视倾斜 + mx = scene_w * 0.04 + my = scene_h * 0.04 + dx = scene_w * tilt + dy = scene_h * tilt + corners = [ + (mx + dx, my + dy * 0.6), + (scene_w - mx, my), + (scene_w - mx - dx * 0.4, scene_h - my), + (mx, scene_h - my - dy * 0.5), + ] + scene = warp_into_scene(canvas, (scene_w, scene_h), corners) + + # 屏幕亮度梯度 + 镜头暗角 + ys, xs = np.mgrid[0:scene_h, 0:scene_w] + gradient = 1.0 - 0.16 * (xs / scene_w) - 0.10 * (ys / scene_h) + cx, cy = scene_w / 2.0, scene_h / 2.0 + radius = np.sqrt(((xs - cx) / cx) ** 2 + ((ys - cy) / cy) ** 2) + vignette = 1.0 - 0.18 * np.clip(radius, 0, 1.4) ** 2 + scene = scene * gradient * vignette + + from PIL import Image, ImageFilter + + image = Image.fromarray(np.clip(scene, 0, 255).astype(np.uint8)) + image = image.filter(ImageFilter.GaussianBlur(radius=blur)) # 镜头 PSF + 轻微失焦 + height = int(round(scene_h * analysis_width / scene_w)) + image = image.resize((analysis_width, height), Image.BOX) # 传感器面积平均 + + array = np.asarray(image, dtype=np.float32) + array = array + rng.normal(0.0, noise, array.shape) + photo = Image.fromarray(np.clip(array, 0, 255).astype(np.uint8)) + + # 合成时画布 active 宽在场景中的真值放大率 + active_dst = np.hypot(corners[1][0] - corners[0][0], corners[1][1] - corners[0][1]) + truth_scale = active_dst / canvas.shape[1] * (analysis_width / float(scene_w)) + return photo, truth_scale + + +def check(condition, message): + if not condition: + raise AssertionError(message) + print(" ok %s" % message) + + +def main() -> int: + print("== 生成标定图 ==") + spec = build_spec(1920, 1080) + canvas = render(spec) + check(canvas.shape == (1080, 1920), "画布尺寸 1920×1080") + check(set(np.unique(canvas).tolist()) == {0, 255}, "画布为纯二值") + + print("== 合成相机拍摄 ==") + photo, truth_scale = synth_photo(canvas) + with tempfile.TemporaryDirectory() as tmp: + spec_path = os.path.join(tmp, "wedge.json") + photo_path = os.path.join(tmp, "photo.jpg") + with open(spec_path, "w", encoding="utf-8") as fh: + fh.write(spec.to_json()) + photo.save(photo_path, quality=92) + + print("== 定位与解码 ==") + gray, _ = wa.load_gray(photo_path, 0) + markers = wa.find_markers(gray) + check(len(markers) == 4, "找到 4 个基准标") + + h = wa.homography(spec.active_corners(), markers) + measured = wa.local_scale(h, spec.active_w / 2.0, spec.active_h / 2.0) + expected = truth_scale + error = abs(measured - expected) / expected + print(" 放大率 真值 %.4f / 实测 %.4f / 偏差 %.2f%%" % (expected, measured, error * 100)) + check(error < 0.01, "单应矩阵放大率与真值一致(<1%%)") + + rows = [wa.analyze_band(gray, spec, band, h, 17) for band in spec.bands] + print() + print(" %-9s %-11s %-9s %-11s" % ("显示pitch", "px/模块", "对比度", "误码率")) + for row in rows: + print(" %-9d %-11.2f %-9.3f %-11s" + % (row["pitch_px"], row["px_per_module"], row["contrast"], + "0" if row["ber"] == 0 else "%.2e" % row["ber"])) + print() + + coarse = [r for r in rows if r["px_per_module"] >= 4.0] + fine = [r for r in rows if r["px_per_module"] <= 2.2] + check(bool(coarse) and all(r["ber"] == 0 for r in coarse), + "px/模块 >= 4.0 的条带零误码") + check(bool(fine) and max(r["ber"] for r in fine) > 1e-3, + "px/模块 <= 2.2 的条带出现明显误码") + + ordered = sorted(rows, key=lambda r: r["px_per_module"]) + check(ordered[0]["ber"] >= ordered[-1]["ber"], "误码率随 px/模块 增大而下降") + check(all(r["contrast"] > 0.05 for r in rows), "各条带对比度为正") + + limit = wa.crossing(rows, 1e-3) + check(limit is not None and 1.5 < limit < 5.0, + "BER=1e-3 临界点落在 1.5~5.0 区间(实测 %.2f)" % (limit or 0)) + + print() + print("== CLI 冒烟 ==") + result = subprocess.run( + [sys.executable, os.path.join(os.path.dirname(os.path.abspath(__file__)), "wedge_analyze.py"), + "--spec", spec_path, "--photo", photo_path, "--analysis-width", "0"], + capture_output=True, text=True) + check(result.returncode == 0, "wedge_analyze.py 正常退出") + check("px/模块" in result.stdout, "输出包含结果表格") + + print() + print("WEDGE SELFTEST PASSED") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main())