app.py 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141
  1. # -*- coding: utf-8 -*-
  2. """RawvStudio —— .rawv 录制文件分析 / 融合 / 锐化对比度增强 上位机
  3. 算法与 app 端 C++ 逐条对应,见 engine.py 的注释。
  4. 界面参数默认值 = app 2.8.39 的实际取值,改参数可现场比对效果。
  5. """
  6. from __future__ import annotations
  7. import json
  8. import os
  9. import sys
  10. import time
  11. import traceback
  12. from dataclasses import asdict
  13. import cv2
  14. import numpy as np
  15. BASE_DIR = os.path.dirname(os.path.abspath(__file__))
  16. if BASE_DIR not in sys.path:
  17. sys.path.insert(0, BASE_DIR)
  18. import engine as E # noqa: E402
  19. from widgets import CompareView, FocusCurve, ImageView # noqa: E402
  20. from PySide6.QtCore import (QObject, QRunnable, QSize, Qt, QThreadPool, QTimer,
  21. Signal)
  22. from PySide6.QtGui import QAction, QColor, QFont, QIcon, QKeySequence, QPixmap
  23. from PySide6.QtWidgets import (QApplication, QCheckBox, QComboBox, QDoubleSpinBox,
  24. QFileDialog, QFormLayout, QGroupBox, QHBoxLayout,
  25. QLabel, QMainWindow, QMessageBox, QPlainTextEdit,
  26. QProgressBar, QPushButton, QScrollArea,
  27. QSizePolicy, QSlider, QSpinBox, QSplitter,
  28. QTabWidget, QToolBar, QVBoxLayout, QWidget)
  29. APP_TITLE = 'RawvStudio — .rawv 融合与后处理工作台(app 2.8.39 同源算法)'
  30. # ===========================================================================
  31. # 后台任务
  32. # ===========================================================================
  33. class TaskSignals(QObject):
  34. progress = Signal(int, int, str)
  35. finished = Signal(object)
  36. failed = Signal(str)
  37. class Task(QRunnable):
  38. """线程池任务。
  39. 【为什么完成判定不用信号】
  40. 现场遇到过"进度条跑到 100%,但按钮永远不解锁、结果也刷不出来":
  41. finished 是跨线程队列信号,理论上应送达,但实测在个别时序下槽函数没被调用
  42. (用 autoDelete=True/False 各跑 40 轮对照,丢信号 0/40,无法稳定复现,
  43. 说明是 PySide6 绑定层的偶发问题,不是单一开关能规避的)。
  44. 既然不可靠,就不依赖它:run() 结束时把结果写进对象字段并置 done=True,
  45. 主线程用定时器轮询这些字段来"收割"结果。进度仍用信号(丢了也无所谓)。
  46. """
  47. def __init__(self, fn, *args, **kwargs):
  48. super().__init__()
  49. self.setAutoDelete(False) # 生命周期由 MainWindow 管理
  50. self.fn, self.args, self.kwargs = fn, args, kwargs
  51. self.signals = TaskSignals()
  52. self.cancelled = False
  53. self._last_done = -1
  54. # --- 供主线程轮询的状态 ---
  55. self.done = False
  56. self.result = None
  57. self.error = None
  58. def run(self):
  59. try:
  60. self.result = self.fn(*self.args, progress=self._emit_progress,
  61. **self.kwargs)
  62. except Exception:
  63. self.error = traceback.format_exc()
  64. finally:
  65. self.done = True # 必须在 finally 里置位,异常也要能解锁
  66. def _emit_progress(self, done, total, msg=''):
  67. """进度节流:逐帧上报会把主线程事件队列塞满,按 ~2% 步长上报即可"""
  68. if self.cancelled:
  69. return
  70. total = max(1, int(total))
  71. done = int(done)
  72. step = max(1, total // 50)
  73. if done >= total or done - self._last_done >= step or self._last_done < 0:
  74. self._last_done = done
  75. self.signals.progress.emit(done, total, str(msg))
  76. # ===========================================================================
  77. # 参数面板构建辅助
  78. # ===========================================================================
  79. def _dspin(lo, hi, step, val, dec=3, suffix=''):
  80. w = QDoubleSpinBox()
  81. w.setRange(lo, hi)
  82. w.setSingleStep(step)
  83. w.setDecimals(dec)
  84. w.setValue(val)
  85. if suffix:
  86. w.setSuffix(suffix)
  87. w.setKeyboardTracking(False)
  88. return w
  89. def _ispin(lo, hi, val, suffix=''):
  90. w = QSpinBox()
  91. w.setRange(lo, hi)
  92. w.setValue(val)
  93. if suffix:
  94. w.setSuffix(suffix)
  95. w.setKeyboardTracking(False)
  96. return w
  97. # ===========================================================================
  98. # 主窗口
  99. # ===========================================================================
  100. class MainWindow(QMainWindow):
  101. def __init__(self):
  102. super().__init__()
  103. self.setWindowTitle(APP_TITLE)
  104. self.resize(1680, 1000)
  105. self.video: E.RawVideo | None = None
  106. self.scores: np.ndarray | None = None
  107. self.result: E.FuseResult | None = None
  108. self.params = E.FusionParams()
  109. self.current_frame = 0
  110. self._preview_cache: dict = {}
  111. self._cmp_cache: dict = {}
  112. self._busy = False
  113. self.pool = QThreadPool.globalInstance()
  114. self.pool.setMaxThreadCount(2)
  115. self._tasks: set = set() # 持有 Task 强引用
  116. self._pending: dict = {} # Task -> on_done,主线程轮询用
  117. self._task_started = time.time()
  118. self._last_progress_ts = time.time()
  119. self._build_toolbar()
  120. self._build_body()
  121. self._build_statusbar()
  122. self._load_params_into_ui()
  123. # 播放
  124. self.timer = QTimer(self)
  125. self.timer.timeout.connect(self._play_tick)
  126. # 后处理即时预览的防抖
  127. self._post_timer = QTimer(self)
  128. self._post_timer.setSingleShot(True)
  129. self._post_timer.setInterval(320)
  130. self._post_timer.timeout.connect(self.apply_post_only)
  131. # 忙状态看门狗:任务已完成却没收割、或长时间毫无进展,就自动解锁并告警
  132. self._watchdog = QTimer(self)
  133. self._watchdog.setInterval(2000)
  134. self._watchdog.timeout.connect(self._check_stuck)
  135. self._watchdog.start()
  136. # 任务收割轮询(120ms,用户无感):完成判定不依赖跨线程信号
  137. self._poll = QTimer(self)
  138. self._poll.setInterval(120)
  139. self._poll.timeout.connect(self._poll_tasks)
  140. self._poll.start()
  141. self.log('就绪。先「打开 .rawv」,再「分析清晰度」→「开始融合」。')
  142. self.log('算法与 app 2.8.39 同源:选帧=积分最大连续高分段,融合=GFF,'
  143. '后处理=USM+CLAHE+repairDarkSpots。')
  144. # ------------------------------------------------------------------ UI
  145. def _build_toolbar(self):
  146. tb = QToolBar('main')
  147. tb.setMovable(False)
  148. tb.setIconSize(QSize(18, 18))
  149. self.addToolBar(tb)
  150. def act(text, slot, tip='', key=None):
  151. a = QAction(text, self)
  152. a.setToolTip(tip or text)
  153. if key:
  154. a.setShortcut(QKeySequence(key))
  155. a.triggered.connect(slot)
  156. tb.addAction(a)
  157. return a
  158. self.act_open = act('打开 .rawv', self.open_file, '选择录制文件', 'Ctrl+O')
  159. tb.addSeparator()
  160. self.act_analyze = act('① 分析清晰度', self.run_analyze,
  161. '逐帧评分(与 app 同一 slview::focusScore)', 'F5')
  162. self.act_fuse = act('② 开始融合', self.run_fuse,
  163. '选帧 → 配准 → GFF 融合 → 后处理', 'F6')
  164. self.act_post = act('仅重跑后处理', self.apply_post_only,
  165. '用已缓存的融合结果快速试参数', 'F7')
  166. tb.addSeparator()
  167. act('导出结果', self.export_result, '保存融合/后处理结果', 'Ctrl+S')
  168. act('保存参数', self.save_params, '导出当前参数为 JSON')
  169. act('载入参数', self.load_params, '从 JSON 恢复参数')
  170. tb.addSeparator()
  171. act('恢复默认参数', self.reset_params, '回到 app 2.8.39 的默认取值')
  172. tb.addSeparator()
  173. act('强制解锁', self.force_unlock,
  174. '任务卡住(按钮一直灰)时点这里恢复界面;正常情况不需要')
  175. spacer = QWidget()
  176. spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
  177. tb.addWidget(spacer)
  178. def _build_body(self):
  179. split = QSplitter(Qt.Horizontal)
  180. split.addWidget(self._build_left())
  181. split.addWidget(self._build_right())
  182. split.setStretchFactor(0, 0)
  183. split.setStretchFactor(1, 1)
  184. split.setSizes([430, 1250])
  185. self.setCentralWidget(split)
  186. def _build_left(self):
  187. panel = QWidget()
  188. outer = QVBoxLayout(panel)
  189. outer.setContentsMargins(6, 6, 6, 6)
  190. # 文件信息
  191. gb_info = QGroupBox('文件信息')
  192. f_info = QFormLayout(gb_info)
  193. f_info.setLabelAlignment(Qt.AlignRight)
  194. self.lb_file = QLabel('—')
  195. self.lb_file.setWordWrap(True)
  196. self.lb_geom = QLabel('—')
  197. self.lb_fmt = QLabel('—')
  198. self.lb_frames = QLabel('—')
  199. self.lb_size = QLabel('—')
  200. for k, w in [('文件', self.lb_file), ('分辨率', self.lb_geom),
  201. ('像素格式', self.lb_fmt), ('帧数', self.lb_frames),
  202. ('体积', self.lb_size)]:
  203. f_info.addRow(k + ':', w)
  204. outer.addWidget(gb_info)
  205. # 参数滚动区
  206. scroll = QScrollArea()
  207. scroll.setWidgetResizable(True)
  208. scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
  209. holder = QWidget()
  210. pv = QVBoxLayout(holder)
  211. pv.setContentsMargins(0, 0, 0, 0)
  212. pv.setSpacing(6)
  213. # --- 选帧 ---
  214. gb_sel = QGroupBox('① 选帧(selectFuseFrames)')
  215. fs = QFormLayout(gb_sel)
  216. self.cb_mode = QComboBox()
  217. self.cb_mode.addItem('窄段 · 单焦面(app 2.8.39 口径)', E.SELECT_MODE_NARROW)
  218. self.cb_mode.addItem('宽段 · 景深扩展', E.SELECT_MODE_WIDE)
  219. self.cb_mode.setToolTip(
  220. '窄段:段长到「足够段长」就收手,只挑最清晰的焦面(细节最锐)\n'
  221. '宽段:不提前收手,一路放宽到「宽段阈值下限」,把相邻焦面也拉进来 → 景深扩展')
  222. self.sp_max_frames = _ispin(1, 40, self.params.max_frames, ' 帧')
  223. self.sp_ratio_lo = _dspin(0.10, 0.99, 0.01, self.params.ratio_lo, 2)
  224. self.sp_min_span = _ispin(1, 20, self.params.min_span, ' 帧')
  225. self.sp_enough_span = _ispin(1, 20, self.params.enough_span, ' 帧')
  226. self.sp_wide_frames = _ispin(1, 40, self.params.wide_max_frames, ' 帧')
  227. self.sp_wide_ratio = _dspin(0.10, 0.99, 0.01, self.params.wide_ratio_lo, 2)
  228. fs.addRow('选帧模式:', self.cb_mode)
  229. fs.addRow('最多参与帧数:', self.sp_max_frames)
  230. fs.addRow('阈值下限 ratio:', self.sp_ratio_lo)
  231. fs.addRow('最小段长:', self.sp_min_span)
  232. fs.addRow('足够段长:', self.sp_enough_span)
  233. fs.addRow('宽段帧数上限:', self.sp_wide_frames)
  234. fs.addRow('宽段阈值下限:', self.sp_wide_ratio)
  235. tip = QLabel('阈值 = ratio × 评分峰值;取 Σscore 最大的连续段。\n'
  236. '宽段模式下「足够段长」自动失效(不提前收手)。')
  237. tip.setStyleSheet('color:#7a808a; font-size:11px;')
  238. tip.setWordWrap(True)
  239. fs.addRow(tip)
  240. pv.addWidget(gb_sel)
  241. # --- 配准 ---
  242. gb_align = QGroupBox('② 配准(alignTranslationSLView)')
  243. fa = QFormLayout(gb_align)
  244. self.ck_align = QCheckBox('启用相位相关平移配准')
  245. self.ck_align.setChecked(self.params.align_enable)
  246. self.sp_align_edge = _ispin(128, 2048, self.params.align_max_edge, ' px')
  247. self.sp_align_apply = _dspin(0.0, 5.0, 0.1, self.params.align_min_apply_px, 2, ' px')
  248. self.sp_align_max = _dspin(2.0, 200.0, 1.0, self.params.align_max_shift_px, 1, ' px')
  249. self.sp_align_resp = _dspin(0.0, 0.9, 0.01, self.params.align_min_response, 2)
  250. fa.addRow(self.ck_align)
  251. fa.addRow('配准图长边:', self.sp_align_edge)
  252. fa.addRow('小于此位移不重采样:', self.sp_align_apply)
  253. fa.addRow('位移上限:', self.sp_align_max)
  254. fa.addRow('响应下限:', self.sp_align_resp)
  255. pv.addWidget(gb_align)
  256. # --- 融合 ---
  257. gb_fus = QGroupBox('③ 融合(guideFilterFusion / GFF)')
  258. ff = QFormLayout(gb_fus)
  259. self.sp_max_pixels = _ispin(64, 4096, int(round(np.sqrt(self.params.max_pixels))),
  260. ' px(长边)')
  261. self.sp_max_pixels.setToolTip('焦点图计算用的最大像素数平方根;'
  262. '实际换算 factor = sqrt(maxPixels/(w*h))')
  263. self.sp_clarity = _ispin(0, 20, self.params.clarity, ' px')
  264. self.sp_guide_r = _ispin(1, 40, self.params.guide_radius, ' px')
  265. self.sp_guide_eps = _dspin(1e-6, 10.0, 0.001, self.params.guide_eps, 6)
  266. ff.addRow('焦点图长边:', self.sp_max_pixels)
  267. ff.addRow('clarity(dilate 半径):', self.sp_clarity)
  268. ff.addRow('引导滤波半径:', self.sp_guide_r)
  269. ff.addRow('引导滤波 eps:', self.sp_guide_eps)
  270. pv.addWidget(gb_fus)
  271. # --- 前置 ---
  272. gb_pre = QGroupBox('前置处理')
  273. fp = QFormLayout(gb_pre)
  274. self.ck_drop = QCheckBox('剔除异常暗帧')
  275. self.ck_drop.setChecked(self.params.drop_dark)
  276. self.sp_drop_ratio = _dspin(0.1, 0.95, 0.05, self.params.drop_dark_ratio, 2)
  277. self.ck_dead = QCheckBox('单帧坏点抑制')
  278. self.ck_dead.setChecked(self.params.dead_pixel)
  279. fp.addRow(self.ck_drop)
  280. fp.addRow('暗帧判定比例:', self.sp_drop_ratio)
  281. fp.addRow(self.ck_dead)
  282. pv.addWidget(gb_pre)
  283. # --- 后处理 ---
  284. gb_p = QGroupBox('④ 后处理(finishFusionImageClassic)')
  285. fpp = QFormLayout(gb_p)
  286. self.ck_post = QCheckBox('启用后处理')
  287. self.ck_post.setChecked(self.params.post_enable)
  288. self.sp_usm_a = _dspin(0.0, 6.0, 0.1, self.params.usm_amount, 2)
  289. self.sp_usm_s = _dspin(0.1, 12.0, 0.1, self.params.usm_sigma, 2)
  290. self.cb_pipeline = QComboBox()
  291. for k in (0, 1, 2, 3, 4, 5, 6, -1):
  292. self.cb_pipeline.addItem(f'{k} · {E.CONTRAST_PIPELINES[k]}', k)
  293. self.sp_clip = _dspin(0.1, 10.0, 0.1, self.params.clahe_clip, 2)
  294. self.sp_tile = _ispin(1, 64, self.params.clahe_tile)
  295. self.sp_auto_lo = _dspin(0.0, 20.0, 0.5, self.params.auto_low, 1, ' %')
  296. self.sp_auto_hi = _dspin(80.0, 100.0, 0.5, self.params.auto_high, 1, ' %')
  297. self.sp_gamma = _dspin(0.2, 5.0, 0.1, self.params.gamma, 2)
  298. self.ck_gamma_auto = QCheckBox('Gamma 自动')
  299. self.ck_gamma_auto.setChecked(self.params.gamma_auto)
  300. self.ck_repair = QCheckBox('黑点修复 repairDarkSpots')
  301. self.ck_repair.setChecked(self.params.repair_dark)
  302. fpp.addRow(self.ck_post)
  303. fpp.addRow('USM amount:', self.sp_usm_a)
  304. fpp.addRow('USM sigma:', self.sp_usm_s)
  305. fpp.addRow('对比度 pipeline:', self.cb_pipeline)
  306. fpp.addRow('CLAHE clip:', self.sp_clip)
  307. fpp.addRow('CLAHE tile:', self.sp_tile)
  308. fpp.addRow('Auto 低百分位:', self.sp_auto_lo)
  309. fpp.addRow('Auto 高百分位:', self.sp_auto_hi)
  310. fpp.addRow('Gamma:', self.sp_gamma)
  311. fpp.addRow(self.ck_gamma_auto)
  312. fpp.addRow(self.ck_repair)
  313. pv.addWidget(gb_p)
  314. # --- 指标 ---
  315. gb_m = QGroupBox('当前显示图指标')
  316. fm = QFormLayout(gb_m)
  317. self.lb_m_mean = QLabel('—')
  318. self.lb_m_lap = QLabel('—')
  319. self.lb_m_black = QLabel('—')
  320. self.lb_m_bg = QLabel('—')
  321. self.lb_m_bgstd = QLabel('—')
  322. self.lb_m_rb = QLabel('—')
  323. for k, w in [('灰度均值', self.lb_m_mean), ('细节能量 lapvar', self.lb_m_lap),
  324. ('纯黑像素', self.lb_m_black), ('背景≥245', self.lb_m_bg),
  325. ('背景标准差', self.lb_m_bgstd), ('色偏 R-B', self.lb_m_rb)]:
  326. fm.addRow(k + ':', w)
  327. pv.addWidget(gb_m)
  328. # --- 分析结果(常显,分析后自动填充)---
  329. gb_r = QGroupBox('清晰度分析结果')
  330. fr = QFormLayout(gb_r)
  331. self.lb_r_stat = QLabel('尚未分析')
  332. self.lb_r_stat.setStyleSheet('color:#8a9099;')
  333. self.lb_r_peak = QLabel('—')
  334. self.lb_r_range = QLabel('—')
  335. self.lb_r_mode = QLabel('—')
  336. self.lb_r_seg = QLabel('—')
  337. self.lb_r_count = QLabel('—')
  338. self.lb_r_ratio = QLabel('—')
  339. self.lb_r_frames = QLabel('—')
  340. self.lb_r_frames.setWordWrap(True)
  341. self.lb_r_frames.setStyleSheet('font-family: Consolas; font-size:11px;')
  342. self.lb_r_here = QLabel('—')
  343. for k, w in [('状态', self.lb_r_stat), ('峰值帧 / 峰值评分', self.lb_r_peak),
  344. ('评分 min / 中位 / max', self.lb_r_range),
  345. ('选帧模式', self.lb_r_mode), ('焦面段 / ratio', self.lb_r_seg),
  346. ('参与融合帧数', self.lb_r_count),
  347. ('段内评分占比', self.lb_r_ratio),
  348. ('当前帧评分', self.lb_r_here),
  349. ('选中帧', self.lb_r_frames)]:
  350. fr.addRow(k + ':', w)
  351. pv.addWidget(gb_r)
  352. # 供"分析完成后自动滚到结果面板"使用
  353. self.gb_result = gb_r
  354. self.scroll_params = scroll
  355. pv.addStretch(1)
  356. scroll.setWidget(holder)
  357. outer.addWidget(scroll, 1)
  358. # 按钮
  359. row = QHBoxLayout()
  360. self.btn_fuse = QPushButton('开始融合 (F6)')
  361. self.btn_fuse.clicked.connect(self.run_fuse)
  362. self.btn_post = QPushButton('仅重跑后处理 (F7)')
  363. self.btn_post.clicked.connect(self.apply_post_only)
  364. row.addWidget(self.btn_fuse)
  365. row.addWidget(self.btn_post)
  366. outer.addLayout(row)
  367. self.ck_auto_post = QCheckBox('后处理参数即时预览(改参数自动重算)')
  368. self.ck_auto_post.setChecked(True)
  369. outer.addWidget(self.ck_auto_post)
  370. self._connect_param_signals()
  371. return panel
  372. def _build_right(self):
  373. w = QWidget()
  374. lay = QVBoxLayout(w)
  375. lay.setContentsMargins(6, 6, 6, 6)
  376. lay.setSpacing(6)
  377. self.tabs = QTabWidget()
  378. self.view_frame = ImageView()
  379. self.view_raw = ImageView()
  380. self.view_final = ImageView()
  381. self.view_cmp = CompareView()
  382. self.tabs.addTab(self.view_frame, '原始帧')
  383. self.tabs.addTab(self.view_raw, '融合(未后处理)')
  384. self.tabs.addTab(self.view_final, '最终结果')
  385. self.tabs.addTab(self.view_cmp, '对比(原始 / 结果)')
  386. self.tabs.currentChanged.connect(self._on_tab_changed)
  387. lay.addWidget(self.tabs, 1)
  388. # 播放控制
  389. play = QHBoxLayout()
  390. self.btn_play = QPushButton('▶ 播放')
  391. self.btn_play.setCheckable(True)
  392. self.btn_play.toggled.connect(self._toggle_play)
  393. self.slider = QSlider(Qt.Horizontal)
  394. self.slider.setRange(0, 0)
  395. self.slider.valueChanged.connect(self._on_slider)
  396. self.sp_fps = _dspin(0.2, 30.0, 0.5, 4.0, 1, ' fps')
  397. self.sp_fps.valueChanged.connect(self._update_timer_interval)
  398. self.lb_pos = QLabel('— / —')
  399. self.lb_pos.setMinimumWidth(110)
  400. play.addWidget(self.btn_play)
  401. play.addWidget(self.slider, 1)
  402. play.addWidget(QLabel('速率'))
  403. play.addWidget(self.sp_fps)
  404. play.addWidget(self.lb_pos)
  405. lay.addLayout(play)
  406. # 曲线
  407. self.curve = FocusCurve()
  408. self.curve.frameClicked.connect(self.goto_frame)
  409. lay.addWidget(self.curve)
  410. self.lb_zoom = QLabel('滚轮缩放 · 拖拽平移 · 双击切换 适应窗口/1:1')
  411. self.lb_zoom.setStyleSheet('color:#7a808a;')
  412. lay.addWidget(self.lb_zoom)
  413. for v in (self.view_frame, self.view_raw, self.view_final):
  414. v.zoomChanged.connect(
  415. lambda z: self.lb_zoom.setText(
  416. f'缩放 {z*100:.0f}% · 滚轮缩放 · 拖拽平移 · 双击切换 1:1/适应窗口'))
  417. return w
  418. def _build_statusbar(self):
  419. self.progress = QProgressBar()
  420. self.progress.setRange(0, 100)
  421. self.progress.setValue(0)
  422. self.progress.setMaximumWidth(320)
  423. self.progress.setTextVisible(True)
  424. self.statusBar().addPermanentWidget(self.progress)
  425. self.statusBar().showMessage('就绪')
  426. from PySide6.QtWidgets import QDockWidget
  427. dock = QDockWidget('日志', self)
  428. dock.setAllowedAreas(Qt.BottomDockWidgetArea | Qt.TopDockWidgetArea)
  429. self.logview = QPlainTextEdit()
  430. self.logview.setReadOnly(True)
  431. self.logview.setMaximumBlockCount(4000)
  432. self.logview.setStyleSheet('font-family: Consolas, "Microsoft YaHei"; font-size:12px;')
  433. dock.setWidget(self.logview)
  434. self.addDockWidget(Qt.BottomDockWidgetArea, dock)
  435. dock.setMinimumHeight(140)
  436. self.log_dock = dock
  437. # ----------------------------------------------------------- 参数读取
  438. def _connect_param_signals(self):
  439. for w in (self.sp_max_frames, self.sp_ratio_lo, self.sp_min_span,
  440. self.sp_enough_span, self.sp_wide_frames, self.sp_wide_ratio,
  441. self.sp_align_edge, self.sp_align_apply,
  442. self.sp_align_max, self.sp_align_resp, self.sp_max_pixels,
  443. self.sp_clarity, self.sp_guide_r, self.sp_guide_eps,
  444. self.sp_drop_ratio, self.sp_usm_a, self.sp_usm_s,
  445. self.sp_clip, self.sp_tile, self.sp_auto_lo, self.sp_auto_hi,
  446. self.sp_gamma):
  447. w.valueChanged.connect(self._on_param_changed)
  448. for w in (self.ck_align, self.ck_drop, self.ck_dead, self.ck_post,
  449. self.ck_repair, self.ck_gamma_auto):
  450. w.toggled.connect(self._on_param_changed)
  451. self.cb_pipeline.currentIndexChanged.connect(self._on_param_changed)
  452. self.cb_mode.currentIndexChanged.connect(self._on_mode_changed)
  453. # 选帧相关参数改动时,实时刷新曲线绿带与结果面板(不必重跑融合)
  454. for w in (self.sp_max_frames, self.sp_ratio_lo, self.sp_min_span,
  455. self.sp_enough_span, self.sp_wide_frames, self.sp_wide_ratio):
  456. w.valueChanged.connect(self._refresh_selection_preview)
  457. def _on_mode_changed(self, *_):
  458. """切模式时同步控件的可用性,避免改了不生效的假象"""
  459. wide = self.cb_mode.currentData() == E.SELECT_MODE_WIDE
  460. self.sp_wide_frames.setEnabled(wide)
  461. self.sp_wide_ratio.setEnabled(wide)
  462. self.sp_max_frames.setEnabled(not wide)
  463. self.sp_ratio_lo.setEnabled(not wide)
  464. self.sp_enough_span.setEnabled(not wide)
  465. self._on_param_changed()
  466. # 模式变了,已算好的选帧结果要重算并刷新曲线绿带
  467. if self.scores is not None:
  468. self._refresh_selection_preview()
  469. def _refresh_selection_preview(self):
  470. """用当前参数重算选帧,只刷新曲线上的绿带与分析结果面板"""
  471. if self.scores is None or len(self.scores) == 0:
  472. return
  473. p = self.collect_params()
  474. self.params = p
  475. peak = int(np.argmax(self.scores))
  476. sel = E.select_fuse_frames(self.scores, peak, p.eff_max_frames(),
  477. p.ratios(), p.min_span, p.eff_enough_span())
  478. self.curve.set_selected(sel.indices)
  479. self._fill_analysis_panel(sel)
  480. def _on_param_changed(self, *_):
  481. self.params = self.collect_params()
  482. if self.ck_auto_post.isChecked() and self.result is not None \
  483. and self.result.fused_raw is not None and not self._busy:
  484. self._post_timer.start()
  485. def collect_params(self) -> E.FusionParams:
  486. side = int(self.sp_max_pixels.value())
  487. return E.FusionParams(
  488. select_mode=self.cb_mode.currentData(),
  489. max_frames=self.sp_max_frames.value(),
  490. ratio_lo=float(self.sp_ratio_lo.value()),
  491. min_span=self.sp_min_span.value(),
  492. enough_span=self.sp_enough_span.value(),
  493. wide_max_frames=self.sp_wide_frames.value(),
  494. wide_ratio_lo=float(self.sp_wide_ratio.value()),
  495. align_enable=self.ck_align.isChecked(),
  496. align_max_edge=self.sp_align_edge.value(),
  497. align_min_apply_px=float(self.sp_align_apply.value()),
  498. align_max_shift_px=float(self.sp_align_max.value()),
  499. align_min_response=float(self.sp_align_resp.value()),
  500. max_pixels=side * side,
  501. clarity=self.sp_clarity.value(),
  502. guide_radius=self.sp_guide_r.value(),
  503. guide_eps=float(self.sp_guide_eps.value()),
  504. drop_dark=self.ck_drop.isChecked(),
  505. drop_dark_ratio=float(self.sp_drop_ratio.value()),
  506. dead_pixel=self.ck_dead.isChecked(),
  507. post_enable=self.ck_post.isChecked(),
  508. usm_amount=float(self.sp_usm_a.value()),
  509. usm_sigma=float(self.sp_usm_s.value()),
  510. pipeline=int(self.cb_pipeline.currentData()),
  511. clahe_clip=float(self.sp_clip.value()),
  512. clahe_tile=self.sp_tile.value(),
  513. auto_low=float(self.sp_auto_lo.value()),
  514. auto_high=float(self.sp_auto_hi.value()),
  515. gamma=float(self.sp_gamma.value()),
  516. gamma_auto=self.ck_gamma_auto.isChecked(),
  517. repair_dark=self.ck_repair.isChecked(),
  518. )
  519. def _load_params_into_ui(self):
  520. p = self.params
  521. idx = self.cb_mode.findData(p.select_mode)
  522. self.cb_mode.setCurrentIndex(max(0, idx))
  523. self.sp_max_frames.setValue(p.max_frames)
  524. self.sp_ratio_lo.setValue(p.ratio_lo)
  525. self.sp_min_span.setValue(p.min_span)
  526. self.sp_enough_span.setValue(p.enough_span)
  527. self.sp_wide_frames.setValue(p.wide_max_frames)
  528. self.sp_wide_ratio.setValue(p.wide_ratio_lo)
  529. self.ck_align.setChecked(p.align_enable)
  530. self.sp_align_edge.setValue(p.align_max_edge)
  531. self.sp_align_apply.setValue(p.align_min_apply_px)
  532. self.sp_align_max.setValue(p.align_max_shift_px)
  533. self.sp_align_resp.setValue(p.align_min_response)
  534. self.sp_max_pixels.setValue(int(round(np.sqrt(p.max_pixels))))
  535. self.sp_clarity.setValue(p.clarity)
  536. self.sp_guide_r.setValue(p.guide_radius)
  537. self.sp_guide_eps.setValue(p.guide_eps)
  538. self.ck_drop.setChecked(p.drop_dark)
  539. self.sp_drop_ratio.setValue(p.drop_dark_ratio)
  540. self.ck_dead.setChecked(p.dead_pixel)
  541. self.ck_post.setChecked(p.post_enable)
  542. self.sp_usm_a.setValue(p.usm_amount)
  543. self.sp_usm_s.setValue(p.usm_sigma)
  544. idx = self.cb_pipeline.findData(p.pipeline)
  545. self.cb_pipeline.setCurrentIndex(max(0, idx))
  546. self.sp_clip.setValue(p.clahe_clip)
  547. self.sp_tile.setValue(p.clahe_tile)
  548. self.sp_auto_lo.setValue(p.auto_low)
  549. self.sp_auto_hi.setValue(p.auto_high)
  550. self.sp_gamma.setValue(p.gamma)
  551. self.ck_gamma_auto.setChecked(p.gamma_auto)
  552. self.ck_repair.setChecked(p.repair_dark)
  553. self._on_mode_changed()
  554. # ------------------------------------------------------------- 工具
  555. def log(self, msg: str):
  556. self.logview.appendPlainText(f'[{time.strftime("%H:%M:%S")}] {msg}')
  557. def _set_busy(self, busy: bool, msg: str = ''):
  558. self._busy = busy
  559. for a in (self.act_open, self.act_analyze, self.act_fuse, self.act_post):
  560. a.setEnabled(not busy)
  561. self.btn_fuse.setEnabled(not busy)
  562. self.btn_post.setEnabled(not busy)
  563. if msg:
  564. self.statusBar().showMessage(msg)
  565. if not busy:
  566. self.progress.setValue(self.progress.maximum())
  567. self.progress.setFormat('%p%')
  568. if not busy and self.progress.maximum() == 0:
  569. self.progress.setRange(0, 100)
  570. self.progress.setValue(100)
  571. def _run_task(self, fn, on_done, *args, **kwargs):
  572. if self._pending:
  573. # 已有任务在跑:直接忽略,避免两个任务互相覆盖进度/结果
  574. self.log('⚠ 已有任务正在执行,本次请求已忽略')
  575. return
  576. t = Task(fn, *args, **kwargs)
  577. t.signals.progress.connect(self._on_progress)
  578. # 完成/失败不依赖信号,交给 _poll_tasks 轮询 t.done(见 Task 类注释)
  579. self._pending[t] = on_done
  580. self._tasks.add(t)
  581. self._task_started = time.time()
  582. self._last_progress_ts = time.time()
  583. self._set_busy(True, '处理中...')
  584. self.progress.setRange(0, 100)
  585. self.progress.setValue(0)
  586. self.pool.start(t)
  587. def _poll_tasks(self):
  588. """主线程轮询收割任务结果 —— 不依赖跨线程信号,绝不会漏收"""
  589. for t in list(self._pending):
  590. if not t.done:
  591. continue
  592. on_done = self._pending.pop(t)
  593. self._tasks.discard(t)
  594. if t.cancelled:
  595. continue
  596. if t.error:
  597. self._on_failed(t.error)
  598. continue
  599. self._set_busy(False)
  600. try:
  601. on_done(t.result)
  602. except Exception:
  603. self.log('❌ 结果处理异常:\n' + traceback.format_exc())
  604. def _on_progress(self, done, total, msg):
  605. self._last_progress_ts = time.time()
  606. total = max(1, total)
  607. self.progress.setRange(0, total)
  608. self.progress.setValue(min(done, total))
  609. self.progress.setFormat(f'{msg} %p%')
  610. if msg:
  611. self.statusBar().showMessage(msg)
  612. def _on_failed(self, tb):
  613. self._set_busy(False, '失败')
  614. self.log('❌ 任务失败:\n' + tb)
  615. QMessageBox.critical(self, '出错', tb.splitlines()[-1] if tb else '未知错误')
  616. def _check_stuck(self):
  617. """忙状态看门狗:兜住"任务卡死"的极端情况
  618. 正常情况下 _poll_tasks 一定会收割到结果;这里只处理两种异常:
  619. · 进度已满却 8s 还在忙(理论上不会发生,收割轮询 120ms 一次)
  620. · 整体超过 15 分钟毫无进展
  621. """
  622. if not self._busy:
  623. return
  624. now = time.time()
  625. pct_done = (self.progress.value() >= self.progress.maximum()
  626. and self.progress.maximum() > 0)
  627. idle = now - self._last_progress_ts
  628. if (pct_done and idle > 8.0) or (now - self._task_started > 900):
  629. self.log('⚠ 任务长时间无响应,已自动解锁界面。若任务仍在后台运行,'
  630. '其结果会被丢弃,请重新执行。')
  631. for t in list(self._tasks):
  632. t.cancelled = True
  633. self._tasks.clear()
  634. self._pending.clear()
  635. self._set_busy(False, '已自动解锁(任务无响应)')
  636. self.progress.setRange(0, 100)
  637. self.progress.setValue(0)
  638. self.progress.setFormat('%p%')
  639. # ------------------------------------------------------------- 打开
  640. def open_file(self):
  641. path, _ = QFileDialog.getOpenFileName(
  642. self, '打开 .rawv 录制文件', self._default_dir(),
  643. 'RAW 视频 (*.rawv);;所有文件 (*.*)')
  644. if not path:
  645. return
  646. self.open_path(path)
  647. def open_path(self, path: str):
  648. """按路径打开(供命令行参数与文件对话框共用)"""
  649. try:
  650. v = E.RawVideo(path)
  651. except Exception as exc:
  652. QMessageBox.critical(self, '无法打开', str(exc))
  653. return
  654. self.video = v
  655. self.scores = None
  656. self.result = None
  657. self._preview_cache.clear()
  658. info = v.info()
  659. self.lb_file.setText(info['file'])
  660. self.lb_geom.setText(f"{info['width']} × {info['height']}(stride {info['stride']})")
  661. self.lb_fmt.setText(f"{info['pixfmt_name']}(pixfmt={info['pixfmt']})")
  662. n = info['usable']
  663. extra = '' if n == info['frames'] else f'(文件头写 {info["frames"]},实际可读 {n})'
  664. self.lb_frames.setText(f"{n} 帧 @ {info['fps']} fps{extra}")
  665. self.lb_size.setText(f"{info['size_real']/1048576:.1f} MB")
  666. self.curve.set_scores(None)
  667. self.curve.set_selected([])
  668. self.lb_r_stat.setText('尚未分析')
  669. self.lb_r_stat.setStyleSheet('color:#8a9099;')
  670. for lb in (self.lb_r_peak, self.lb_r_range, self.lb_r_mode, self.lb_r_seg,
  671. self.lb_r_count, self.lb_r_ratio, self.lb_r_frames,
  672. self.lb_r_here):
  673. lb.setText('—')
  674. self.view_raw.clear_image()
  675. self.view_final.clear_image()
  676. self.slider.setRange(0, max(0, n - 1))
  677. self.slider.setValue(0)
  678. self.log(f'已打开 {info["file"]}:{info["width"]}×{info["height"]} '
  679. f'{info["pixfmt_name"]} {n} 帧')
  680. if info['truncated']:
  681. self.log('⚠ 文件比文件头声明的小(可能录制中断),已按实际可读帧数处理')
  682. self.goto_frame(0)
  683. def _default_dir(self) -> str:
  684. for cand in (os.path.join(BASE_DIR, '..', '..', 'Test'),
  685. os.path.join(BASE_DIR, '..', '..')):
  686. if os.path.isdir(cand):
  687. return os.path.abspath(cand)
  688. return BASE_DIR
  689. # ------------------------------------------------------------- 分析
  690. def run_analyze(self):
  691. if not self._require_video():
  692. return
  693. # 忙状态统一由 _run_task 负责设置,这里不要再预置 —— 否则会被并发守卫拦掉
  694. self._run_task(E.analyze, self._on_analyzed, self.video,
  695. clarity=self.params.clarity)
  696. def _on_analyzed(self, scores):
  697. self.scores = np.asarray(scores, np.float64)
  698. self.curve.set_scores(self.scores)
  699. self.curve.set_selected([])
  700. if not len(self.scores):
  701. self.lb_r_stat.setText('分析无结果(可读帧数为 0)')
  702. self.lb_r_stat.setStyleSheet('color:#c0392b;')
  703. return
  704. peak = int(np.argmax(self.scores))
  705. self.curve.set_peak(peak)
  706. p = self.params
  707. sel = E.select_fuse_frames(self.scores, peak, p.eff_max_frames(),
  708. p.ratios(), p.min_span, p.eff_enough_span())
  709. self.curve.set_selected(sel.indices)
  710. self._fill_analysis_panel(sel)
  711. # 参数面板很长,分析完自动滚到结果区,避免用户以为"点了没反应"
  712. try:
  713. self.scroll_params.ensureWidgetVisible(self.gb_result, 0, 8)
  714. except Exception:
  715. pass
  716. self.log(f'分析完成:{len(self.scores)} 帧,峰值 #{peak} = '
  717. f'{self.scores[peak]:.4f}')
  718. self.log(f' 模式={E.SELECT_MODE_NAMES.get(p.select_mode)}')
  719. if sel.fallback:
  720. self.log(f' 选帧回退中心邻域({sel.note})')
  721. else:
  722. self.log(f' 焦面段 [{sel.segment[0]},{sel.segment[1]}] '
  723. f'ratio={sel.ratio} → {len(sel.indices)} 帧 {sel.indices}')
  724. # 分析完直接停在峰值帧,并把视图切到「原始帧」,否则用户会以为没反应
  725. self.tabs.setCurrentWidget(self.view_frame)
  726. self.goto_frame(peak)
  727. self._update_metrics()
  728. self.statusBar().showMessage(
  729. f'分析完成:峰值 #{peak},选帧 {len(sel.indices)} 帧'
  730. f'({E.SELECT_MODE_SHORT.get(p.select_mode, p.select_mode)})', 8000)
  731. def _fill_analysis_panel(self, sel):
  732. """把分析/选帧结果写进左侧「清晰度分析结果」面板"""
  733. if self.scores is None or len(self.scores) == 0:
  734. self.lb_r_stat.setText('尚未分析')
  735. self.lb_r_stat.setStyleSheet('color:#8a9099;')
  736. return
  737. d = E.summarize_scores(self.scores, sel)
  738. p = self.params
  739. mode_txt = E.SELECT_MODE_NAMES.get(p.select_mode, p.select_mode)
  740. self.lb_r_stat.setText('已完成')
  741. self.lb_r_stat.setStyleSheet('color:#1e8e4f; font-weight:600;')
  742. self.lb_r_peak.setText(f"#{d['peak_index']} {d['peak']:.4f}")
  743. self.lb_r_range.setText(f"{d['smin']:.3f} / {d['median']:.3f} / {d['peak']:.3f}")
  744. self.lb_r_mode.setText(mode_txt)
  745. if sel is None or not sel.indices:
  746. self.lb_r_seg.setText('—')
  747. self.lb_r_count.setText('—')
  748. self.lb_r_ratio.setText('—')
  749. self.lb_r_frames.setText('—')
  750. return
  751. if sel.fallback:
  752. self.lb_r_seg.setText(f'回退中心邻域({sel.note})')
  753. else:
  754. self.lb_r_seg.setText(f'[{sel.segment[0]}, {sel.segment[1]}] ratio={sel.ratio}')
  755. self.lb_r_count.setText(f'{len(sel.indices)} 帧'
  756. + (f'(剔除暗帧 {len(self.result.dropped)})'
  757. if self.result and self.result.dropped else ''))
  758. lo = d.get('span_ratio_min')
  759. hi = d.get('span_ratio_max')
  760. if lo is not None:
  761. color = '#1e8e4f' if lo >= 0.9 else ('#b7791f' if lo >= 0.6 else '#c0392b')
  762. self.lb_r_ratio.setText(f'{lo:.3f} ~ {hi:.3f}')
  763. self.lb_r_ratio.setStyleSheet(f'color:{color};')
  764. self.lb_r_ratio.setToolTip(
  765. '段内每帧评分 / 峰值。接近 1.0 说明都是同一焦面(窄段);\n'
  766. '低到 0.6 左右说明纳入了明显离焦的帧(宽段景深扩展)。')
  767. self.lb_r_frames.setText(', '.join(str(i) for i in sel.indices))
  768. # ------------------------------------------------------------- 融合
  769. def run_fuse(self):
  770. if not self._require_video():
  771. return
  772. if self.scores is None:
  773. QMessageBox.information(self, '请先分析', '融合需要逐帧评分,先执行「① 分析清晰度」。')
  774. return
  775. params = self.collect_params()
  776. self.params = params
  777. self._run_task(E.fuse, self._on_fused, self.video, self.scores, params)
  778. def _on_fused(self, res: E.FuseResult):
  779. self.result = res
  780. for line in res.log:
  781. self.log(' ' + line)
  782. if res.fused_raw is not None:
  783. self.view_raw.set_image(res.fused_raw, keep_view=False)
  784. if res.fused_final is not None:
  785. self.view_final.set_image(res.fused_final, keep_view=False)
  786. self.curve.set_selected(res.selected)
  787. if res.select is not None:
  788. self._fill_analysis_panel(res.select)
  789. self._refresh_compare()
  790. self.tabs.setCurrentWidget(self.view_final)
  791. self._update_metrics()
  792. n = len(res.selected)
  793. mode = E.SELECT_MODE_SHORT.get(res.mode, res.mode)
  794. self.statusBar().showMessage(f'融合完成:{n} 帧({mode})', 8000)
  795. self.log(f'融合完成:{n} 帧({E.SELECT_MODE_NAMES.get(res.mode, res.mode)})。'
  796. f'切「最终结果」看成品,「对比」可同屏比原始与结果。')
  797. def apply_post_only(self):
  798. if self.result is None or self.result.fused_raw is None:
  799. return
  800. params = self.collect_params()
  801. self.params = params
  802. raw = self.result.fused_raw
  803. t0 = time.time()
  804. def work(progress=None):
  805. if progress:
  806. progress(0, 2, '后处理中...')
  807. img, info = E.reprocess(raw, params)
  808. if progress:
  809. progress(2, 2, '完成')
  810. return img, info
  811. def done(out):
  812. img, info = out
  813. self.result.fused_final = img
  814. self.result.post_info = info
  815. self.result.repaired = info.get('repaired', 0)
  816. self.view_final.set_image(img, keep_view=True)
  817. self._refresh_compare()
  818. if self.tabs.currentWidget() is self.view_final or \
  819. self.tabs.currentWidget() is self.view_cmp:
  820. pass
  821. self._update_metrics()
  822. self.log(f'后处理重算 {time.time()-t0:.2f}s:USM({params.usm_amount},'
  823. f'{params.usm_sigma}) + '
  824. f'{E.CONTRAST_PIPELINES.get(params.pipeline, params.pipeline)}'
  825. + (f',修复黑点 {info.get("repaired",0)} px'
  826. if info.get('repaired') else ''))
  827. self.statusBar().showMessage('后处理已更新', 2500)
  828. self._run_task(work, done)
  829. # ------------------------------------------------------------- 帧显示
  830. def goto_frame(self, idx: int):
  831. if self.video is None:
  832. return
  833. n = self.video.usable_frames
  834. if n <= 0:
  835. return
  836. idx = int(max(0, min(n - 1, idx)))
  837. self.current_frame = idx
  838. if self.slider.value() != idx:
  839. self.slider.blockSignals(True)
  840. self.slider.setValue(idx)
  841. self.slider.blockSignals(False)
  842. self.lb_pos.setText(f'{idx} / {n - 1}')
  843. self.curve.set_current(idx)
  844. img = self._preview_cache.get(idx)
  845. if img is None:
  846. img = self.video.bgr_small(idx, max_edge=1100)
  847. if len(self._preview_cache) > 80:
  848. self._preview_cache.clear()
  849. self._preview_cache[idx] = img
  850. self.view_frame.set_image(img, keep_view=True)
  851. # 当前帧评分 + 是否被选入融合
  852. if self.scores is not None and 0 <= idx < len(self.scores):
  853. peak = float(self.scores.max()) or 1.0
  854. v = float(self.scores[idx])
  855. picked = self.curve.selected
  856. mark = ' ✔已选入融合' if idx in picked else ''
  857. self.lb_r_here.setText(f'#{idx} {v:.4f} (占峰值 {v/peak*100:.1f}%){mark}')
  858. self.lb_r_here.setStyleSheet(
  859. 'color:#1e8e4f;' if idx in picked else 'color:#8a9099;')
  860. else:
  861. self.lb_r_here.setText('—')
  862. if self.tabs.currentWidget() is self.view_cmp:
  863. self._refresh_compare()
  864. def _on_slider(self, v):
  865. self.goto_frame(v)
  866. def _on_tab_changed(self, _i):
  867. if self.tabs.currentWidget() is self.view_cmp:
  868. self._refresh_compare()
  869. self._update_metrics()
  870. def _refresh_compare(self):
  871. """对比页:左=当前帧原图(全分辨率,保证与结果同尺寸),右=最终结果"""
  872. left = None
  873. if self.video is not None:
  874. left = self._cmp_cache.get(self.current_frame)
  875. if left is None:
  876. left = self.video.bgr(self.current_frame) # 全分辨率,与结果同尺寸
  877. if len(self._cmp_cache) > 12:
  878. self._cmp_cache.clear()
  879. self._cmp_cache[self.current_frame] = left
  880. right = self.result.fused_final if self.result is not None else None
  881. self.view_cmp.set_pair(left, right)
  882. # ------------------------------------------------------------- 播放
  883. def _toggle_play(self, on):
  884. if on:
  885. if self.video is None:
  886. self.btn_play.setChecked(False)
  887. return
  888. self.btn_play.setText('⏸ 暂停')
  889. self._update_timer_interval()
  890. self.timer.start()
  891. else:
  892. self.btn_play.setText('▶ 播放')
  893. self.timer.stop()
  894. def _update_timer_interval(self, *_):
  895. self.timer.setInterval(max(30, int(1000.0 / max(0.2, self.sp_fps.value()))))
  896. def _play_tick(self):
  897. if self.video is None:
  898. return
  899. n = self.video.usable_frames
  900. if n <= 0:
  901. return
  902. self.goto_frame((self.current_frame + 1) % n)
  903. # ------------------------------------------------------------- 指标
  904. def _current_image(self):
  905. w = self.tabs.currentWidget()
  906. if w is self.view_frame:
  907. return self._preview_cache.get(self.current_frame)
  908. if w is self.view_raw:
  909. return self.result.fused_raw if self.result else None
  910. if w is self.view_final:
  911. return self.result.fused_final if self.result else None
  912. if w is self.view_cmp:
  913. return self.result.fused_final if self.result else None
  914. return None
  915. def _update_metrics(self):
  916. img = self._current_image()
  917. if img is None:
  918. for lb in (self.lb_m_mean, self.lb_m_lap, self.lb_m_black,
  919. self.lb_m_bg, self.lb_m_bgstd, self.lb_m_rb):
  920. lb.setText('—')
  921. return
  922. m = E.quick_metrics(img)
  923. self.lb_m_mean.setText(f'{m.get("mean", 0):.2f}')
  924. self.lb_m_lap.setText(f'{m.get("lapvar", 0):.1f}')
  925. self.lb_m_black.setText(f'{m.get("pure_black", 0)}')
  926. self.lb_m_bg.setText(f'{m.get("bg245", 0):.1f}%')
  927. self.lb_m_bgstd.setText(f'{m.get("bg_std", 0):.2f}')
  928. self.lb_m_rb.setText(f'{m.get("rb", 0):+.1f}')
  929. # ------------------------------------------------------------- 导出
  930. def export_result(self):
  931. if self.result is None or self.result.fused_final is None:
  932. QMessageBox.information(self, '没有结果', '先执行融合。')
  933. return
  934. w = self.tabs.currentWidget()
  935. if w is self.view_raw and self.result.fused_raw is not None:
  936. img, suffix = self.result.fused_raw, '_fused'
  937. else:
  938. img, suffix = self.result.fused_final, '_final'
  939. base = os.path.splitext(os.path.basename(self.video.path))[0] if self.video else 'result'
  940. path, _ = QFileDialog.getSaveFileName(
  941. self, '导出图片', os.path.join(self._default_dir(), base + suffix + '.png'),
  942. 'PNG (*.png);;JPEG (*.jpg)')
  943. if not path:
  944. return
  945. ext = os.path.splitext(path)[1].lower()
  946. params = [cv2.IMWRITE_JPEG_QUALITY, 96] if ext in ('.jpg', '.jpeg') \
  947. else [cv2.IMWRITE_PNG_COMPRESSION, 3]
  948. ok, buf = cv2.imencode(ext, img, params)
  949. if not ok:
  950. QMessageBox.critical(self, '导出失败', '编码失败')
  951. return
  952. buf.tofile(path)
  953. self.log(f'已导出 {path}')
  954. def save_params(self):
  955. path, _ = QFileDialog.getSaveFileName(
  956. self, '保存参数', os.path.join(BASE_DIR, 'params.json'), 'JSON (*.json)')
  957. if not path:
  958. return
  959. with open(path, 'w', encoding='utf-8') as f:
  960. json.dump(self.collect_params().as_dict(), f, ensure_ascii=False, indent=2)
  961. self.log(f'参数已保存 {path}')
  962. def load_params(self):
  963. path, _ = QFileDialog.getOpenFileName(
  964. self, '载入参数', BASE_DIR, 'JSON (*.json)')
  965. if not path:
  966. return
  967. try:
  968. with open(path, encoding='utf-8') as f:
  969. d = json.load(f)
  970. p = E.FusionParams(**{k: v for k, v in d.items()
  971. if k in E.FusionParams.__dataclass_fields__})
  972. except Exception as exc:
  973. QMessageBox.critical(self, '载入失败', str(exc))
  974. return
  975. self.params = p
  976. self._load_params_into_ui()
  977. self.log(f'参数已载入 {path}')
  978. def reset_params(self):
  979. self.params = E.FusionParams()
  980. self._load_params_into_ui()
  981. self.log('已恢复 app 2.8.39 默认参数')
  982. def force_unlock(self):
  983. """手动解除忙状态(任务真卡住时的逃生口)"""
  984. if not self._busy:
  985. self.statusBar().showMessage('当前不忙,无需解锁', 3000)
  986. return
  987. for t in list(self._tasks):
  988. t.cancelled = True
  989. self._tasks.clear()
  990. self._pending.clear()
  991. self._set_busy(False, '已手动解锁')
  992. self.progress.setRange(0, 100)
  993. self.progress.setValue(0)
  994. self.progress.setFormat('%p%')
  995. self.log('已手动解除忙状态。若是任务仍在后台运行,其结果会被丢弃。')
  996. # ------------------------------------------------------------- 校验
  997. def _require_video(self) -> bool:
  998. if self.video is None:
  999. QMessageBox.information(self, '请先打开文件', '先用「打开 .rawv」选择录制文件。')
  1000. return False
  1001. return True
  1002. def _install_excepthook():
  1003. """把未捕获异常写进日志文件。
  1004. 用 pythonw 启动时没有控制台,stderr 会被丢弃,槽函数里的异常会静默消失
  1005. (表现为"点了没反应")。这里统一落盘,便于现场排查。
  1006. """
  1007. log_path = os.path.join(BASE_DIR, 'rawv_studio.err.log')
  1008. def hook(exc_type, exc, tb):
  1009. text = ''.join(traceback.format_exception(exc_type, exc, tb))
  1010. try:
  1011. with open(log_path, 'a', encoding='utf-8') as f:
  1012. f.write(f'\n===== {time.strftime("%Y-%m-%d %H:%M:%S")} =====\n{text}')
  1013. except Exception:
  1014. pass
  1015. sys.__excepthook__(exc_type, exc, tb)
  1016. sys.excepthook = hook
  1017. def main():
  1018. _install_excepthook()
  1019. app = QApplication(sys.argv)
  1020. app.setStyle('Fusion')
  1021. f = QFont('Microsoft YaHei', 9)
  1022. app.setFont(f)
  1023. win = MainWindow()
  1024. win.show()
  1025. # 支持命令行直接带文件
  1026. if len(sys.argv) > 1 and os.path.isfile(sys.argv[1]):
  1027. try:
  1028. win.open_path(sys.argv[1])
  1029. except Exception:
  1030. pass
  1031. sys.exit(app.exec())
  1032. if __name__ == '__main__':
  1033. main()