| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279 |
- # -*- coding: utf-8 -*-
- """engine 自检:不依赖 GUI,可在命令行直接跑
- 覆盖:全部对比度 pipeline、USM、黑点修复、引导滤波、选帧边界、
- 配准(合成已知位移)、以及用真实 rawv 小范围跑一遍完整链路。
- """
- from __future__ import annotations
- import os
- import sys
- import time
- import traceback
- import cv2
- import numpy as np
- BASE = os.path.dirname(os.path.abspath(__file__))
- if BASE not in sys.path:
- sys.path.insert(0, BASE)
- import engine as E
- FAIL = []
- def check(cond, msg):
- print((' PASS ' if cond else ' FAIL ') + msg)
- if not cond:
- FAIL.append(msg)
- def section(t):
- print('\n' + '=' * 70 + f'\n{t}\n' + '=' * 70)
- # ---------------------------------------------------------------- 合成图
- def make_scene(h=240, w=320):
- rng = np.random.RandomState(7)
- base = np.full((h, w, 3), 240, np.uint8)
- for _ in range(14):
- cx, cy = rng.randint(20, w - 20), rng.randint(20, h - 20)
- r = rng.randint(6, 16)
- cv2.circle(base, (cx, cy), r, (60, 70, 85), -1, cv2.LINE_AA)
- cv2.circle(base, (cx, cy), r, (35, 45, 60), 2, cv2.LINE_AA)
- base = cv2.GaussianBlur(base, (3, 3), 0.6)
- return base
- def test_contrast():
- section('1. 对比度 pipeline 全覆盖')
- img = make_scene()
- for pid in (-1, 0, 1, 2, 3, 4, 5, 6):
- try:
- out = E.enhance_contrast(img, pid, clahe_clip=2.0, clahe_tile=8)
- ok = (out is not None and out.shape == img.shape and out.dtype == np.uint8)
- check(ok, f'pipeline={pid:<2} {E.CONTRAST_PIPELINES[pid]} -> '
- f'{out.shape if out is not None else None}')
- except Exception:
- check(False, f'pipeline={pid} 抛异常\n{traceback.format_exc()}')
- def test_usm_and_repair():
- section('2. USM / repairDarkSpots')
- img = make_scene()
- for a, s in ((2.0, 3.0), (0.0, 3.0), (1.0, 1.2)):
- out = E.unsharp_mask(img, a, s)
- check(out.shape == img.shape and out.dtype == np.uint8,
- f'USM(amount={a}, sigma={s}) OK')
- # 手动植入纯黑点,确认黑点修复能把它们抬起来
- dirty = img.copy()
- dirty[50:53, 60:63] = (0, 0, 0)
- dirty[120, 200] = (0, 0, 0)
- fixed, n = E.repair_dark_spots(dirty)
- before = int(np.count_nonzero(cv2.cvtColor(dirty, cv2.COLOR_BGR2GRAY) <= 12))
- after = int(np.count_nonzero(cv2.cvtColor(fixed, cv2.COLOR_BGR2GRAY) <= 12))
- check(after <= before, f'纯黑像素 {before} -> {after}(修复 {n} px)')
- # 只抬亮:输出必须处处 >= 输入
- check(bool(np.all(fixed >= dirty)), '修复结果恒 >= 原图(只抬亮)')
- def test_guided_filter():
- section('3. 引导滤波与 GFF')
- guide = make_scene().astype(np.float32).mean(axis=2).astype(np.float32)
- src = (guide > 200).astype(np.float32)
- out = E.guided_filter(guide, src, 5, 0.065025)
- check(out.shape == src.shape and np.isfinite(out).all(), 'guidedFilter 输出有限值')
- imgs = [make_scene(), cv2.GaussianBlur(make_scene(), (7, 7), 2.0)]
- fus = E.guide_filter_fusion(imgs, 0.6, 5, 5, 0.065025)
- check(fus.shape == imgs[0].shape and fus.dtype == np.uint8, 'GFF 两帧融合 OK')
- one = E.guide_filter_fusion([imgs[0]], 0.6)
- check(np.array_equal(one, imgs[0]), 'GFF 单帧直通')
- def test_select():
- section('4. 选帧边界')
- # 主峰 + 末端孤立尖刺(本项目的真实曲线形态)
- s = [0.4] * 80
- for i in range(28, 38):
- s[i] = 0.9 + 0.02 * (i - 28)
- for i in range(18, 28):
- s[i] = 0.5 + 0.04 * (i - 18)
- s[-1] = s[33]
- arr = np.array(s)
- peak = int(arr.argmax())
- r = E.select_fuse_frames(arr, peak, 12, (0.97, 0.95, 0.92, 0.90, 0.85,
- 0.80, 0.72, 0.62, 0.50), 4, 6)
- ratio_min = min(arr[i] / arr.max() for i in r.indices)
- check(not r.fallback, f'选出主峰段(未回退):{r.indices}')
- check(ratio_min >= 0.90, f'段内最低评分/峰值 = {ratio_min:.3f} >= 0.90')
- check((len(arr) - 1) not in r.indices, '末端孤立尖刺未被选入')
- flat = np.full(40, 0.5)
- r2 = E.select_fuse_frames(flat, 20, 12)
- check(len(r2.indices) > 0, f'全平坦曲线仍产出结果:{len(r2.indices)} 帧')
- zero = np.zeros(30)
- r3 = E.select_fuse_frames(zero, 15, 8)
- check(r3.fallback and len(r3.indices) > 0, '全 0 曲线走兜底')
- wide = np.array([0.2] * 10 + [1.0] * 80 + [0.2] * 10)
- r4 = E.select_fuse_frames(wide, 50, 10)
- check(len(r4.indices) <= 10 and r4.indices[0] == 10 and r4.indices[-1] == 89,
- f'宽段等步长抽样含首尾:{r4.indices[0]}..{r4.indices[-1]}({len(r4.indices)} 帧)')
- def test_wide_mode():
- section('4b. 宽段景深扩展模式')
- # 造一条"一路缓降"的曲线:焦面附近的帧评分连续,宽段应纳入明显更多帧
- n = 120
- s = np.full(n, 0.15)
- for i in range(40, 80):
- x = (i - 60) / 12.0
- s[i] = 0.15 + 0.85 * np.exp(-x * x)
- arr = np.array(s)
- peak = int(arr.argmax())
- pn = E.FusionParams(select_mode=E.SELECT_MODE_NARROW, max_frames=18)
- sel_n = E.select_fuse_frames(arr, peak, pn.eff_max_frames(), pn.ratios(),
- pn.min_span, pn.eff_enough_span())
- pw = E.FusionParams(select_mode=E.SELECT_MODE_WIDE, wide_max_frames=18,
- wide_ratio_lo=0.60)
- sel_w = E.select_fuse_frames(arr, peak, pw.eff_max_frames(), pw.ratios(),
- pw.min_span, pw.eff_enough_span())
- lo_n = min(arr[i] / arr.max() for i in sel_n.indices)
- lo_w = min(arr[i] / arr.max() for i in sel_w.indices)
- print(f' 窄段:{len(sel_n.indices)} 帧 段={sel_n.segment} 最低占比={lo_n:.3f}')
- print(f' 宽段:{len(sel_w.indices)} 帧 段={sel_w.segment} 最低占比={lo_w:.3f}')
- check(len(sel_w.indices) > len(sel_n.indices), '宽段纳入帧数多于窄段')
- span_n = sel_n.segment[1] - sel_n.segment[0]
- span_w = sel_w.segment[1] - sel_w.segment[0]
- check(span_w > span_n, f'宽段焦面段更宽({span_n} -> {span_w})')
- check(lo_w < lo_n, '宽段确实纳入了更离焦的帧(最低占比更低)')
- check(lo_w >= 0.55, f'宽段仍受 ratio 下限约束(最低占比 {lo_w:.3f} >= 0.55)')
- check(pw.eff_enough_span() == 0, '宽段模式下「足够段长」自动失效')
- # 窄段不应被宽段参数影响
- pn2 = E.FusionParams(select_mode=E.SELECT_MODE_NARROW)
- check(pn2.eff_max_frames() == pn2.max_frames
- and pn2.eff_enough_span() == pn2.enough_span,
- '窄段模式仍用 max_frames / enough_span')
- def test_align():
- section('5. 平移配准(合成已知位移)')
- base = make_scene(300, 400)
- def shift(im, dx, dy):
- m = np.float32([[1, 0, dx], [0, 1, dy]])
- return cv2.warpAffine(im, m, (im.shape[1], im.shape[0]),
- flags=cv2.INTER_LINEAR | cv2.WARP_INVERSE_MAP,
- borderMode=cv2.BORDER_REFLECT_101)
- f0 = base
- f1 = shift(base, 3.0, -2.0)
- f2 = shift(base, -4.0, 1.5)
- def mad(a, b, m=40):
- ga = cv2.cvtColor(a, cv2.COLOR_BGR2GRAY)[m:-m, m:-m].astype(np.float32)
- gb = cv2.cvtColor(b, cv2.COLOR_BGR2GRAY)[m:-m, m:-m].astype(np.float32)
- return float(np.abs(ga - gb).mean())
- before = max(mad(f0, f1), mad(f0, f2))
- ar = E.align_translation([f0, f1, f2])
- # 参考帧可能是任意一帧,所以比较"两两之间"的最大残差
- fr = ar.frames
- after = max(mad(fr[0], fr[1]), mad(fr[0], fr[2]), mad(fr[1], fr[2]))
- check(after < before * 0.5, f'对齐后两两最大 MAD {before:.1f} -> {after:.1f}')
- check(ar.applied >= 1, f'重采样 {ar.applied} 帧:{ar.note}')
- same = [base.copy(), base.copy(), base.copy()]
- ar2 = E.align_translation(same)
- check(ar2.applied == 0, '全同帧不做无谓插值')
- ar3 = E.align_translation([base])
- check(ar3.applied == 0, '单帧直接跳过')
- def test_real_rawv():
- section('6. 真实 rawv 完整链路(取前 40 帧加速)')
- cands = [
- r'F:\QT_WorkSpace\qt6_iot_all\app_bzy_armhf_7\Test\record_20261110093317.rawv',
- ]
- path = next((p for p in cands if os.path.isfile(p)), None)
- if not path:
- print(' 跳过:找不到测试 rawv')
- return
- v = E.RawVideo(path)
- print(f' {v.info()}')
- check(v.usable_frames > 0, f'可读帧数 {v.usable_frames}')
- # 只取一段帧做分析,模拟真实曲线峰值附近
- lo, hi = 150, 180
- scores = np.zeros(v.frame_count, np.float64)
- t0 = time.time()
- for i in range(lo, hi):
- scores[i] = E.slview_focus_score(
- E._to_gray8(v.bgr_at_div(i, 4)), E.K_DEFAULT_CLARITY)
- print(f' 评分 {hi-lo} 帧耗时 {time.time()-t0:.1f}s')
- peak = lo + int(np.argmax(scores[lo:hi]))
- check(scores[peak] > 0, f'峰值帧 #{peak} 评分 {scores[peak]:.4f}')
- p = E.FusionParams(max_frames=6, post_enable=True)
- sel = E.select_fuse_frames(scores, peak, p.max_frames, p.ratios(),
- p.min_span, p.enough_span)
- print(f' 选帧 {sel.indices} 段={sel.segment}')
- # 用选中帧手工跑一遍(不依赖全量评分)
- frames = [v.bgr(i) for i in sel.indices]
- check(all(f.shape[2] == 3 for f in frames), '解码为 3 通道 BGR')
- # 检查颜色:孢子应为金褐色(R>B),若 R/B 颠倒说明解码口径错
- g = cv2.cvtColor(frames[0], cv2.COLOR_BGR2GRAY)
- m = cv2.erode((g < 170).astype(np.uint8),
- cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11, 11))).astype(bool)
- if m.sum() > 500:
- B = frames[0][:, :, 0][m].mean()
- R = frames[0][:, :, 2][m].mean()
- check(R > B, f'暗区核心 R={R:.1f} > B={B:.1f}(金褐色,解码口径正确)')
- ar = E.align_translation(frames, p.align_max_edge, p.align_min_apply_px,
- p.align_max_shift_px, p.align_min_response)
- print(f' 配准:{ar.note}')
- fus = E.guide_filter_fusion(ar.frames, E.compute_factor(v.width, v.height,
- p.max_pixels),
- p.clarity, p.guide_radius, p.guide_eps)
- fin, info = E.finish_fusion_classic(fus, p.usm_amount, p.usm_sigma, p.pipeline,
- p.clahe_clip, p.clahe_tile, p.auto_low,
- p.auto_high, p.gamma, p.gamma_auto,
- p.repair_dark)
- check(fin.shape == fus.shape, '后处理尺寸不变')
- mb, ma = E.quick_metrics(fus), E.quick_metrics(fin)
- print(f' 融合前 {mb}')
- print(f' 后处理后 {ma}')
- check(ma['pure_black'] == 0, f'纯黑像素归零(实际 {ma["pure_black"]})')
- check(ma['lapvar'] > mb['lapvar'] * 3, '锐化后细节能量显著提升')
- check(ma['bg245'] > 60, f'背景 ≥245 占比 {ma["bg245"]}% 合理')
- def main():
- print('RawvStudio engine 自检')
- test_contrast()
- test_usm_and_repair()
- test_guided_filter()
- test_select()
- test_wide_mode()
- test_align()
- test_real_rawv()
- print('\n' + '=' * 70)
- if FAIL:
- print(f'❌ 失败 {len(FAIL)} 项:')
- for m in FAIL:
- print(' -', m.splitlines()[0])
- sys.exit(1)
- print('✅ 全部通过')
- if __name__ == '__main__':
- main()
|