feat: 新增 QFT5 光学链路方案与分辨率楔形标定工具

当前光学链路传 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。
故需改为「内码纠错 + 外层喷泉码纠删」的级联结构,已记入文档。
This commit is contained in:
zhy200308
2026-08-11 09:08:04 +08:00
parent 0b7ffd2dab
commit ea7b678b37
7 changed files with 1405 additions and 0 deletions
+1
View File
@@ -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)
+446
View File
@@ -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())
+229
View File
@@ -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)
+132
View File
@@ -0,0 +1,132 @@
#!/usr/bin/env python3
"""生成 QFT 分辨率楔形标定图。
python scripts/wedge_gen.py --width 1920 --height 1080 --out out/wedge
产出三个文件:
<out>.png 标定图本体(必须 1:1 显示,任何缩放都会让测量失效)
<out>.json 规格,wedge_analyze.py 用它反解几何与期望比特
<out>.html 全屏 1:1 查看器,自带缩放校验
显示方法(二选一):
A. 用浏览器打开 <out>.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 = """<!doctype html>
<meta charset="utf-8">
<title>QFT 标定图 1:1 查看器</title>
<style>
html,body{margin:0;padding:0;background:#fff;overflow:hidden}
#wrap{position:absolute;inset:0;display:flex;align-items:center;justify-content:center}
img{image-rendering:pixelated;image-rendering:crisp-edges}
#hud{position:fixed;left:8px;top:8px;font:13px/1.5 ui-monospace,Consolas,monospace;
background:rgba(0,0,0,.82);color:#fff;padding:8px 12px;border-radius:6px;z-index:9}
#hud.bad{background:rgba(150,20,20,.92)}
#hud b{color:#8f8}
#hud.bad b{color:#fbb}
</style>
<div id="wrap"><img id="img" src="__PNG__" alt=""></div>
<div id="hud">测量中…(按 H 隐藏此框,F11 全屏)</div>
<script>
const img = document.getElementById('img'), hud = document.getElementById('hud');
function check(){
const dpr = window.devicePixelRatio || 1;
// 让 1 个图像像素 == 1 个设备像素
img.style.width = (img.naturalWidth / dpr) + 'px';
img.style.height = (img.naturalHeight / dpr) + 'px';
const rect = img.getBoundingClientRect();
const shownDevicePx = rect.width * dpr;
const scale = shownDevicePx / img.naturalWidth;
const screenW = Math.round(window.screen.width * dpr);
const screenH = Math.round(window.screen.height * dpr);
const fits = img.naturalWidth <= screenW && img.naturalHeight <= screenH;
const ok = Math.abs(scale - 1) < 0.002 && fits;
hud.className = ok ? '' : 'bad';
hud.innerHTML =
'图像 ' + img.naturalWidth + '×' + img.naturalHeight +
' · 屏幕设备像素 ' + screenW + '×' + screenH +
' · DPR ' + dpr.toFixed(3) +
' · 缩放 <b>' + scale.toFixed(3) + (ok ? ' ✅</b>' : ' ❌</b>') +
(fits ? '' : '<br>标定图大于屏幕,请用 --width/--height 重新生成为屏幕设备像素尺寸') +
(Math.abs(scale-1) < 0.002 ? '' : '<br>浏览器缩放不是 100%,请按 Ctrl+0 复位');
}
img.complete ? check() : img.addEventListener('load', check);
addEventListener('resize', check);
addEventListener('keydown', e => {
if (e.key === 'h' || e.key === 'H') hud.style.display = hud.style.display === 'none' ? '' : 'none';
});
</script>
"""
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())
+162
View File
@@ -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())