selftest.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. # -*- coding: utf-8 -*-
  2. """engine 自检:不依赖 GUI,可在命令行直接跑
  3. 覆盖:全部对比度 pipeline、USM、黑点修复、引导滤波、选帧边界、
  4. 配准(合成已知位移)、以及用真实 rawv 小范围跑一遍完整链路。
  5. """
  6. from __future__ import annotations
  7. import os
  8. import sys
  9. import time
  10. import traceback
  11. import cv2
  12. import numpy as np
  13. BASE = os.path.dirname(os.path.abspath(__file__))
  14. if BASE not in sys.path:
  15. sys.path.insert(0, BASE)
  16. import engine as E
  17. FAIL = []
  18. def check(cond, msg):
  19. print((' PASS ' if cond else ' FAIL ') + msg)
  20. if not cond:
  21. FAIL.append(msg)
  22. def section(t):
  23. print('\n' + '=' * 70 + f'\n{t}\n' + '=' * 70)
  24. # ---------------------------------------------------------------- 合成图
  25. def make_scene(h=240, w=320):
  26. rng = np.random.RandomState(7)
  27. base = np.full((h, w, 3), 240, np.uint8)
  28. for _ in range(14):
  29. cx, cy = rng.randint(20, w - 20), rng.randint(20, h - 20)
  30. r = rng.randint(6, 16)
  31. cv2.circle(base, (cx, cy), r, (60, 70, 85), -1, cv2.LINE_AA)
  32. cv2.circle(base, (cx, cy), r, (35, 45, 60), 2, cv2.LINE_AA)
  33. base = cv2.GaussianBlur(base, (3, 3), 0.6)
  34. return base
  35. def test_contrast():
  36. section('1. 对比度 pipeline 全覆盖')
  37. img = make_scene()
  38. for pid in (-1, 0, 1, 2, 3, 4, 5, 6):
  39. try:
  40. out = E.enhance_contrast(img, pid, clahe_clip=2.0, clahe_tile=8)
  41. ok = (out is not None and out.shape == img.shape and out.dtype == np.uint8)
  42. check(ok, f'pipeline={pid:<2} {E.CONTRAST_PIPELINES[pid]} -> '
  43. f'{out.shape if out is not None else None}')
  44. except Exception:
  45. check(False, f'pipeline={pid} 抛异常\n{traceback.format_exc()}')
  46. def test_usm_and_repair():
  47. section('2. USM / repairDarkSpots')
  48. img = make_scene()
  49. for a, s in ((2.0, 3.0), (0.0, 3.0), (1.0, 1.2)):
  50. out = E.unsharp_mask(img, a, s)
  51. check(out.shape == img.shape and out.dtype == np.uint8,
  52. f'USM(amount={a}, sigma={s}) OK')
  53. # 手动植入纯黑点,确认黑点修复能把它们抬起来
  54. dirty = img.copy()
  55. dirty[50:53, 60:63] = (0, 0, 0)
  56. dirty[120, 200] = (0, 0, 0)
  57. fixed, n = E.repair_dark_spots(dirty)
  58. before = int(np.count_nonzero(cv2.cvtColor(dirty, cv2.COLOR_BGR2GRAY) <= 12))
  59. after = int(np.count_nonzero(cv2.cvtColor(fixed, cv2.COLOR_BGR2GRAY) <= 12))
  60. check(after <= before, f'纯黑像素 {before} -> {after}(修复 {n} px)')
  61. # 只抬亮:输出必须处处 >= 输入
  62. check(bool(np.all(fixed >= dirty)), '修复结果恒 >= 原图(只抬亮)')
  63. def test_guided_filter():
  64. section('3. 引导滤波与 GFF')
  65. guide = make_scene().astype(np.float32).mean(axis=2).astype(np.float32)
  66. src = (guide > 200).astype(np.float32)
  67. out = E.guided_filter(guide, src, 5, 0.065025)
  68. check(out.shape == src.shape and np.isfinite(out).all(), 'guidedFilter 输出有限值')
  69. imgs = [make_scene(), cv2.GaussianBlur(make_scene(), (7, 7), 2.0)]
  70. fus = E.guide_filter_fusion(imgs, 0.6, 5, 5, 0.065025)
  71. check(fus.shape == imgs[0].shape and fus.dtype == np.uint8, 'GFF 两帧融合 OK')
  72. one = E.guide_filter_fusion([imgs[0]], 0.6)
  73. check(np.array_equal(one, imgs[0]), 'GFF 单帧直通')
  74. def test_select():
  75. section('4. 选帧边界')
  76. # 主峰 + 末端孤立尖刺(本项目的真实曲线形态)
  77. s = [0.4] * 80
  78. for i in range(28, 38):
  79. s[i] = 0.9 + 0.02 * (i - 28)
  80. for i in range(18, 28):
  81. s[i] = 0.5 + 0.04 * (i - 18)
  82. s[-1] = s[33]
  83. arr = np.array(s)
  84. peak = int(arr.argmax())
  85. r = E.select_fuse_frames(arr, peak, 12, (0.97, 0.95, 0.92, 0.90, 0.85,
  86. 0.80, 0.72, 0.62, 0.50), 4, 6)
  87. ratio_min = min(arr[i] / arr.max() for i in r.indices)
  88. check(not r.fallback, f'选出主峰段(未回退):{r.indices}')
  89. check(ratio_min >= 0.90, f'段内最低评分/峰值 = {ratio_min:.3f} >= 0.90')
  90. check((len(arr) - 1) not in r.indices, '末端孤立尖刺未被选入')
  91. flat = np.full(40, 0.5)
  92. r2 = E.select_fuse_frames(flat, 20, 12)
  93. check(len(r2.indices) > 0, f'全平坦曲线仍产出结果:{len(r2.indices)} 帧')
  94. zero = np.zeros(30)
  95. r3 = E.select_fuse_frames(zero, 15, 8)
  96. check(r3.fallback and len(r3.indices) > 0, '全 0 曲线走兜底')
  97. wide = np.array([0.2] * 10 + [1.0] * 80 + [0.2] * 10)
  98. r4 = E.select_fuse_frames(wide, 50, 10)
  99. check(len(r4.indices) <= 10 and r4.indices[0] == 10 and r4.indices[-1] == 89,
  100. f'宽段等步长抽样含首尾:{r4.indices[0]}..{r4.indices[-1]}({len(r4.indices)} 帧)')
  101. def test_wide_mode():
  102. section('4b. 宽段景深扩展模式')
  103. # 造一条"一路缓降"的曲线:焦面附近的帧评分连续,宽段应纳入明显更多帧
  104. n = 120
  105. s = np.full(n, 0.15)
  106. for i in range(40, 80):
  107. x = (i - 60) / 12.0
  108. s[i] = 0.15 + 0.85 * np.exp(-x * x)
  109. arr = np.array(s)
  110. peak = int(arr.argmax())
  111. pn = E.FusionParams(select_mode=E.SELECT_MODE_NARROW, max_frames=18)
  112. sel_n = E.select_fuse_frames(arr, peak, pn.eff_max_frames(), pn.ratios(),
  113. pn.min_span, pn.eff_enough_span())
  114. pw = E.FusionParams(select_mode=E.SELECT_MODE_WIDE, wide_max_frames=18,
  115. wide_ratio_lo=0.60)
  116. sel_w = E.select_fuse_frames(arr, peak, pw.eff_max_frames(), pw.ratios(),
  117. pw.min_span, pw.eff_enough_span())
  118. lo_n = min(arr[i] / arr.max() for i in sel_n.indices)
  119. lo_w = min(arr[i] / arr.max() for i in sel_w.indices)
  120. print(f' 窄段:{len(sel_n.indices)} 帧 段={sel_n.segment} 最低占比={lo_n:.3f}')
  121. print(f' 宽段:{len(sel_w.indices)} 帧 段={sel_w.segment} 最低占比={lo_w:.3f}')
  122. check(len(sel_w.indices) > len(sel_n.indices), '宽段纳入帧数多于窄段')
  123. span_n = sel_n.segment[1] - sel_n.segment[0]
  124. span_w = sel_w.segment[1] - sel_w.segment[0]
  125. check(span_w > span_n, f'宽段焦面段更宽({span_n} -> {span_w})')
  126. check(lo_w < lo_n, '宽段确实纳入了更离焦的帧(最低占比更低)')
  127. check(lo_w >= 0.55, f'宽段仍受 ratio 下限约束(最低占比 {lo_w:.3f} >= 0.55)')
  128. check(pw.eff_enough_span() == 0, '宽段模式下「足够段长」自动失效')
  129. # 窄段不应被宽段参数影响
  130. pn2 = E.FusionParams(select_mode=E.SELECT_MODE_NARROW)
  131. check(pn2.eff_max_frames() == pn2.max_frames
  132. and pn2.eff_enough_span() == pn2.enough_span,
  133. '窄段模式仍用 max_frames / enough_span')
  134. def test_align():
  135. section('5. 平移配准(合成已知位移)')
  136. base = make_scene(300, 400)
  137. def shift(im, dx, dy):
  138. m = np.float32([[1, 0, dx], [0, 1, dy]])
  139. return cv2.warpAffine(im, m, (im.shape[1], im.shape[0]),
  140. flags=cv2.INTER_LINEAR | cv2.WARP_INVERSE_MAP,
  141. borderMode=cv2.BORDER_REFLECT_101)
  142. f0 = base
  143. f1 = shift(base, 3.0, -2.0)
  144. f2 = shift(base, -4.0, 1.5)
  145. def mad(a, b, m=40):
  146. ga = cv2.cvtColor(a, cv2.COLOR_BGR2GRAY)[m:-m, m:-m].astype(np.float32)
  147. gb = cv2.cvtColor(b, cv2.COLOR_BGR2GRAY)[m:-m, m:-m].astype(np.float32)
  148. return float(np.abs(ga - gb).mean())
  149. before = max(mad(f0, f1), mad(f0, f2))
  150. ar = E.align_translation([f0, f1, f2])
  151. # 参考帧可能是任意一帧,所以比较"两两之间"的最大残差
  152. fr = ar.frames
  153. after = max(mad(fr[0], fr[1]), mad(fr[0], fr[2]), mad(fr[1], fr[2]))
  154. check(after < before * 0.5, f'对齐后两两最大 MAD {before:.1f} -> {after:.1f}')
  155. check(ar.applied >= 1, f'重采样 {ar.applied} 帧:{ar.note}')
  156. same = [base.copy(), base.copy(), base.copy()]
  157. ar2 = E.align_translation(same)
  158. check(ar2.applied == 0, '全同帧不做无谓插值')
  159. ar3 = E.align_translation([base])
  160. check(ar3.applied == 0, '单帧直接跳过')
  161. def test_real_rawv():
  162. section('6. 真实 rawv 完整链路(取前 40 帧加速)')
  163. cands = [
  164. r'F:\QT_WorkSpace\qt6_iot_all\app_bzy_armhf_7\Test\record_20261110093317.rawv',
  165. ]
  166. path = next((p for p in cands if os.path.isfile(p)), None)
  167. if not path:
  168. print(' 跳过:找不到测试 rawv')
  169. return
  170. v = E.RawVideo(path)
  171. print(f' {v.info()}')
  172. check(v.usable_frames > 0, f'可读帧数 {v.usable_frames}')
  173. # 只取一段帧做分析,模拟真实曲线峰值附近
  174. lo, hi = 150, 180
  175. scores = np.zeros(v.frame_count, np.float64)
  176. t0 = time.time()
  177. for i in range(lo, hi):
  178. scores[i] = E.slview_focus_score(
  179. E._to_gray8(v.bgr_at_div(i, 4)), E.K_DEFAULT_CLARITY)
  180. print(f' 评分 {hi-lo} 帧耗时 {time.time()-t0:.1f}s')
  181. peak = lo + int(np.argmax(scores[lo:hi]))
  182. check(scores[peak] > 0, f'峰值帧 #{peak} 评分 {scores[peak]:.4f}')
  183. p = E.FusionParams(max_frames=6, post_enable=True)
  184. sel = E.select_fuse_frames(scores, peak, p.max_frames, p.ratios(),
  185. p.min_span, p.enough_span)
  186. print(f' 选帧 {sel.indices} 段={sel.segment}')
  187. # 用选中帧手工跑一遍(不依赖全量评分)
  188. frames = [v.bgr(i) for i in sel.indices]
  189. check(all(f.shape[2] == 3 for f in frames), '解码为 3 通道 BGR')
  190. # 检查颜色:孢子应为金褐色(R>B),若 R/B 颠倒说明解码口径错
  191. g = cv2.cvtColor(frames[0], cv2.COLOR_BGR2GRAY)
  192. m = cv2.erode((g < 170).astype(np.uint8),
  193. cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11, 11))).astype(bool)
  194. if m.sum() > 500:
  195. B = frames[0][:, :, 0][m].mean()
  196. R = frames[0][:, :, 2][m].mean()
  197. check(R > B, f'暗区核心 R={R:.1f} > B={B:.1f}(金褐色,解码口径正确)')
  198. ar = E.align_translation(frames, p.align_max_edge, p.align_min_apply_px,
  199. p.align_max_shift_px, p.align_min_response)
  200. print(f' 配准:{ar.note}')
  201. fus = E.guide_filter_fusion(ar.frames, E.compute_factor(v.width, v.height,
  202. p.max_pixels),
  203. p.clarity, p.guide_radius, p.guide_eps)
  204. fin, info = E.finish_fusion_classic(fus, p.usm_amount, p.usm_sigma, p.pipeline,
  205. p.clahe_clip, p.clahe_tile, p.auto_low,
  206. p.auto_high, p.gamma, p.gamma_auto,
  207. p.repair_dark)
  208. check(fin.shape == fus.shape, '后处理尺寸不变')
  209. mb, ma = E.quick_metrics(fus), E.quick_metrics(fin)
  210. print(f' 融合前 {mb}')
  211. print(f' 后处理后 {ma}')
  212. check(ma['pure_black'] == 0, f'纯黑像素归零(实际 {ma["pure_black"]})')
  213. check(ma['lapvar'] > mb['lapvar'] * 3, '锐化后细节能量显著提升')
  214. check(ma['bg245'] > 60, f'背景 ≥245 占比 {ma["bg245"]}% 合理')
  215. def main():
  216. print('RawvStudio engine 自检')
  217. test_contrast()
  218. test_usm_and_repair()
  219. test_guided_filter()
  220. test_select()
  221. test_wide_mode()
  222. test_align()
  223. test_real_rawv()
  224. print('\n' + '=' * 70)
  225. if FAIL:
  226. print(f'❌ 失败 {len(FAIL)} 项:')
  227. for m in FAIL:
  228. print(' -', m.splitlines()[0])
  229. sys.exit(1)
  230. print('✅ 全部通过')
  231. if __name__ == '__main__':
  232. main()