Files
QFT/scripts/optical_image_decode_selftest.py
T
2026-08-10 15:45:04 +08:00

56 lines
2.6 KiB
Python

#!/usr/bin/env python3
"""Synthetic visual-path smoke test for the 4-QR optical page and QFTPAIR2.
Requires: qrcode, numpy, opencv-python, pyzbar/libzbar.
This is intentionally not a substitute for a real display/camera test.
"""
import base64, json, os, time
import cv2
import numpy as np
import qrcode
from pyzbar.pyzbar import decode as zdecode, ZBarSymbol
from qrcode.constants import ERROR_CORRECT_L, ERROR_CORRECT_M
def make_qr(text: str, ec, target: int):
qr = qrcode.QRCode(version=None, error_correction=ec, box_size=1, border=4)
qr.add_data(text); qr.make(fit=True)
mat = np.asarray(qr.get_matrix(), dtype=np.uint8)
scale = max(1, target // mat.shape[0])
return ((1 - np.kron(mat, np.ones((scale, scale), np.uint8))) * 255).astype(np.uint8), qr.version
# Four data QR symbols at the same density used by v0.3 (about 1243 chars/frame).
texts = ["QFT1:" + base64.urlsafe_b64encode(os.urandom(928)).decode().rstrip("=") for _ in range(4)]
canvas = np.full((960, 960), 255, np.uint8)
gutter = 15
cell = (960 - gutter * 3) // 2
for idx, text in enumerate(texts):
img, version = make_qr(text, ERROR_CORRECT_L, cell)
row, col = divmod(idx, 2)
x = gutter + col * (cell + gutter) + (cell - img.shape[1]) // 2
y = gutter + row * (cell + gutter) + (cell - img.shape[0]) // 2
canvas[y:y+img.shape[0], x:x+img.shape[1]] = img
started = time.perf_counter()
found = {r.data.decode() for r in zdecode(canvas, symbols=[ZBarSymbol.QRCODE])}
elapsed = time.perf_counter() - started
assert found == set(texts), (len(found), len(texts))
# Pairing QR: downscale + rotate + slight blur to exercise acquisition margin.
v2 = {
"v":2,"s":"qft_test_session_128bit_XY","n":"DESKTOP-QFT","p":39393,
"e":["http://192.168.137.1:39393"],
"w":["QFT-DESKTOP-abc123","3xamplePassw0rd"],
}
raw = json.dumps(v2, separators=(",", ":"), ensure_ascii=False).encode()
pair_text = "QFTPAIR2:" + base64.urlsafe_b64encode(raw).decode().rstrip("=")
pair, pair_ver = make_qr(pair_text, ERROR_CORRECT_M, 520)
pair = cv2.resize(pair, (260, 260), interpolation=cv2.INTER_NEAREST)
rot = cv2.getRotationMatrix2D((130, 130), 7.0, 1.0)
pair = cv2.warpAffine(pair, rot, (300, 300), borderValue=255)
pair = cv2.GaussianBlur(pair, (3, 3), 0.5)
started2 = time.perf_counter()
pair_found = [r.data.decode() for r in zdecode(pair, symbols=[ZBarSymbol.QRCODE])]
elapsed2 = time.perf_counter() - started2
assert pair_text in pair_found
print(f"PASS synthetic QR decode: 4/4 optical QR v{version} decoded from 960px page in {elapsed*1000:.1f} ms; "
f"QFTPAIR2 QR-M v{pair_ver} decoded after 7deg rotate+blur in {elapsed2*1000:.1f} ms")