#!/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())