| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141 |
- # -*- coding: utf-8 -*-
- """RawvStudio —— .rawv 录制文件分析 / 融合 / 锐化对比度增强 上位机
- 算法与 app 端 C++ 逐条对应,见 engine.py 的注释。
- 界面参数默认值 = app 2.8.39 的实际取值,改参数可现场比对效果。
- """
- from __future__ import annotations
- import json
- import os
- import sys
- import time
- import traceback
- from dataclasses import asdict
- import cv2
- import numpy as np
- BASE_DIR = os.path.dirname(os.path.abspath(__file__))
- if BASE_DIR not in sys.path:
- sys.path.insert(0, BASE_DIR)
- import engine as E # noqa: E402
- from widgets import CompareView, FocusCurve, ImageView # noqa: E402
- from PySide6.QtCore import (QObject, QRunnable, QSize, Qt, QThreadPool, QTimer,
- Signal)
- from PySide6.QtGui import QAction, QColor, QFont, QIcon, QKeySequence, QPixmap
- from PySide6.QtWidgets import (QApplication, QCheckBox, QComboBox, QDoubleSpinBox,
- QFileDialog, QFormLayout, QGroupBox, QHBoxLayout,
- QLabel, QMainWindow, QMessageBox, QPlainTextEdit,
- QProgressBar, QPushButton, QScrollArea,
- QSizePolicy, QSlider, QSpinBox, QSplitter,
- QTabWidget, QToolBar, QVBoxLayout, QWidget)
- APP_TITLE = 'RawvStudio — .rawv 融合与后处理工作台(app 2.8.39 同源算法)'
- # ===========================================================================
- # 后台任务
- # ===========================================================================
- class TaskSignals(QObject):
- progress = Signal(int, int, str)
- finished = Signal(object)
- failed = Signal(str)
- class Task(QRunnable):
- """线程池任务。
- 【为什么完成判定不用信号】
- 现场遇到过"进度条跑到 100%,但按钮永远不解锁、结果也刷不出来":
- finished 是跨线程队列信号,理论上应送达,但实测在个别时序下槽函数没被调用
- (用 autoDelete=True/False 各跑 40 轮对照,丢信号 0/40,无法稳定复现,
- 说明是 PySide6 绑定层的偶发问题,不是单一开关能规避的)。
- 既然不可靠,就不依赖它:run() 结束时把结果写进对象字段并置 done=True,
- 主线程用定时器轮询这些字段来"收割"结果。进度仍用信号(丢了也无所谓)。
- """
- def __init__(self, fn, *args, **kwargs):
- super().__init__()
- self.setAutoDelete(False) # 生命周期由 MainWindow 管理
- self.fn, self.args, self.kwargs = fn, args, kwargs
- self.signals = TaskSignals()
- self.cancelled = False
- self._last_done = -1
- # --- 供主线程轮询的状态 ---
- self.done = False
- self.result = None
- self.error = None
- def run(self):
- try:
- self.result = self.fn(*self.args, progress=self._emit_progress,
- **self.kwargs)
- except Exception:
- self.error = traceback.format_exc()
- finally:
- self.done = True # 必须在 finally 里置位,异常也要能解锁
- def _emit_progress(self, done, total, msg=''):
- """进度节流:逐帧上报会把主线程事件队列塞满,按 ~2% 步长上报即可"""
- if self.cancelled:
- return
- total = max(1, int(total))
- done = int(done)
- step = max(1, total // 50)
- if done >= total or done - self._last_done >= step or self._last_done < 0:
- self._last_done = done
- self.signals.progress.emit(done, total, str(msg))
- # ===========================================================================
- # 参数面板构建辅助
- # ===========================================================================
- def _dspin(lo, hi, step, val, dec=3, suffix=''):
- w = QDoubleSpinBox()
- w.setRange(lo, hi)
- w.setSingleStep(step)
- w.setDecimals(dec)
- w.setValue(val)
- if suffix:
- w.setSuffix(suffix)
- w.setKeyboardTracking(False)
- return w
- def _ispin(lo, hi, val, suffix=''):
- w = QSpinBox()
- w.setRange(lo, hi)
- w.setValue(val)
- if suffix:
- w.setSuffix(suffix)
- w.setKeyboardTracking(False)
- return w
- # ===========================================================================
- # 主窗口
- # ===========================================================================
- class MainWindow(QMainWindow):
- def __init__(self):
- super().__init__()
- self.setWindowTitle(APP_TITLE)
- self.resize(1680, 1000)
- self.video: E.RawVideo | None = None
- self.scores: np.ndarray | None = None
- self.result: E.FuseResult | None = None
- self.params = E.FusionParams()
- self.current_frame = 0
- self._preview_cache: dict = {}
- self._cmp_cache: dict = {}
- self._busy = False
- self.pool = QThreadPool.globalInstance()
- self.pool.setMaxThreadCount(2)
- self._tasks: set = set() # 持有 Task 强引用
- self._pending: dict = {} # Task -> on_done,主线程轮询用
- self._task_started = time.time()
- self._last_progress_ts = time.time()
- self._build_toolbar()
- self._build_body()
- self._build_statusbar()
- self._load_params_into_ui()
- # 播放
- self.timer = QTimer(self)
- self.timer.timeout.connect(self._play_tick)
- # 后处理即时预览的防抖
- self._post_timer = QTimer(self)
- self._post_timer.setSingleShot(True)
- self._post_timer.setInterval(320)
- self._post_timer.timeout.connect(self.apply_post_only)
- # 忙状态看门狗:任务已完成却没收割、或长时间毫无进展,就自动解锁并告警
- self._watchdog = QTimer(self)
- self._watchdog.setInterval(2000)
- self._watchdog.timeout.connect(self._check_stuck)
- self._watchdog.start()
- # 任务收割轮询(120ms,用户无感):完成判定不依赖跨线程信号
- self._poll = QTimer(self)
- self._poll.setInterval(120)
- self._poll.timeout.connect(self._poll_tasks)
- self._poll.start()
- self.log('就绪。先「打开 .rawv」,再「分析清晰度」→「开始融合」。')
- self.log('算法与 app 2.8.39 同源:选帧=积分最大连续高分段,融合=GFF,'
- '后处理=USM+CLAHE+repairDarkSpots。')
- # ------------------------------------------------------------------ UI
- def _build_toolbar(self):
- tb = QToolBar('main')
- tb.setMovable(False)
- tb.setIconSize(QSize(18, 18))
- self.addToolBar(tb)
- def act(text, slot, tip='', key=None):
- a = QAction(text, self)
- a.setToolTip(tip or text)
- if key:
- a.setShortcut(QKeySequence(key))
- a.triggered.connect(slot)
- tb.addAction(a)
- return a
- self.act_open = act('打开 .rawv', self.open_file, '选择录制文件', 'Ctrl+O')
- tb.addSeparator()
- self.act_analyze = act('① 分析清晰度', self.run_analyze,
- '逐帧评分(与 app 同一 slview::focusScore)', 'F5')
- self.act_fuse = act('② 开始融合', self.run_fuse,
- '选帧 → 配准 → GFF 融合 → 后处理', 'F6')
- self.act_post = act('仅重跑后处理', self.apply_post_only,
- '用已缓存的融合结果快速试参数', 'F7')
- tb.addSeparator()
- act('导出结果', self.export_result, '保存融合/后处理结果', 'Ctrl+S')
- act('保存参数', self.save_params, '导出当前参数为 JSON')
- act('载入参数', self.load_params, '从 JSON 恢复参数')
- tb.addSeparator()
- act('恢复默认参数', self.reset_params, '回到 app 2.8.39 的默认取值')
- tb.addSeparator()
- act('强制解锁', self.force_unlock,
- '任务卡住(按钮一直灰)时点这里恢复界面;正常情况不需要')
- spacer = QWidget()
- spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
- tb.addWidget(spacer)
- def _build_body(self):
- split = QSplitter(Qt.Horizontal)
- split.addWidget(self._build_left())
- split.addWidget(self._build_right())
- split.setStretchFactor(0, 0)
- split.setStretchFactor(1, 1)
- split.setSizes([430, 1250])
- self.setCentralWidget(split)
- def _build_left(self):
- panel = QWidget()
- outer = QVBoxLayout(panel)
- outer.setContentsMargins(6, 6, 6, 6)
- # 文件信息
- gb_info = QGroupBox('文件信息')
- f_info = QFormLayout(gb_info)
- f_info.setLabelAlignment(Qt.AlignRight)
- self.lb_file = QLabel('—')
- self.lb_file.setWordWrap(True)
- self.lb_geom = QLabel('—')
- self.lb_fmt = QLabel('—')
- self.lb_frames = QLabel('—')
- self.lb_size = QLabel('—')
- for k, w in [('文件', self.lb_file), ('分辨率', self.lb_geom),
- ('像素格式', self.lb_fmt), ('帧数', self.lb_frames),
- ('体积', self.lb_size)]:
- f_info.addRow(k + ':', w)
- outer.addWidget(gb_info)
- # 参数滚动区
- scroll = QScrollArea()
- scroll.setWidgetResizable(True)
- scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
- holder = QWidget()
- pv = QVBoxLayout(holder)
- pv.setContentsMargins(0, 0, 0, 0)
- pv.setSpacing(6)
- # --- 选帧 ---
- gb_sel = QGroupBox('① 选帧(selectFuseFrames)')
- fs = QFormLayout(gb_sel)
- self.cb_mode = QComboBox()
- self.cb_mode.addItem('窄段 · 单焦面(app 2.8.39 口径)', E.SELECT_MODE_NARROW)
- self.cb_mode.addItem('宽段 · 景深扩展', E.SELECT_MODE_WIDE)
- self.cb_mode.setToolTip(
- '窄段:段长到「足够段长」就收手,只挑最清晰的焦面(细节最锐)\n'
- '宽段:不提前收手,一路放宽到「宽段阈值下限」,把相邻焦面也拉进来 → 景深扩展')
- self.sp_max_frames = _ispin(1, 40, self.params.max_frames, ' 帧')
- self.sp_ratio_lo = _dspin(0.10, 0.99, 0.01, self.params.ratio_lo, 2)
- self.sp_min_span = _ispin(1, 20, self.params.min_span, ' 帧')
- self.sp_enough_span = _ispin(1, 20, self.params.enough_span, ' 帧')
- self.sp_wide_frames = _ispin(1, 40, self.params.wide_max_frames, ' 帧')
- self.sp_wide_ratio = _dspin(0.10, 0.99, 0.01, self.params.wide_ratio_lo, 2)
- fs.addRow('选帧模式:', self.cb_mode)
- fs.addRow('最多参与帧数:', self.sp_max_frames)
- fs.addRow('阈值下限 ratio:', self.sp_ratio_lo)
- fs.addRow('最小段长:', self.sp_min_span)
- fs.addRow('足够段长:', self.sp_enough_span)
- fs.addRow('宽段帧数上限:', self.sp_wide_frames)
- fs.addRow('宽段阈值下限:', self.sp_wide_ratio)
- tip = QLabel('阈值 = ratio × 评分峰值;取 Σscore 最大的连续段。\n'
- '宽段模式下「足够段长」自动失效(不提前收手)。')
- tip.setStyleSheet('color:#7a808a; font-size:11px;')
- tip.setWordWrap(True)
- fs.addRow(tip)
- pv.addWidget(gb_sel)
- # --- 配准 ---
- gb_align = QGroupBox('② 配准(alignTranslationSLView)')
- fa = QFormLayout(gb_align)
- self.ck_align = QCheckBox('启用相位相关平移配准')
- self.ck_align.setChecked(self.params.align_enable)
- self.sp_align_edge = _ispin(128, 2048, self.params.align_max_edge, ' px')
- self.sp_align_apply = _dspin(0.0, 5.0, 0.1, self.params.align_min_apply_px, 2, ' px')
- self.sp_align_max = _dspin(2.0, 200.0, 1.0, self.params.align_max_shift_px, 1, ' px')
- self.sp_align_resp = _dspin(0.0, 0.9, 0.01, self.params.align_min_response, 2)
- fa.addRow(self.ck_align)
- fa.addRow('配准图长边:', self.sp_align_edge)
- fa.addRow('小于此位移不重采样:', self.sp_align_apply)
- fa.addRow('位移上限:', self.sp_align_max)
- fa.addRow('响应下限:', self.sp_align_resp)
- pv.addWidget(gb_align)
- # --- 融合 ---
- gb_fus = QGroupBox('③ 融合(guideFilterFusion / GFF)')
- ff = QFormLayout(gb_fus)
- self.sp_max_pixels = _ispin(64, 4096, int(round(np.sqrt(self.params.max_pixels))),
- ' px(长边)')
- self.sp_max_pixels.setToolTip('焦点图计算用的最大像素数平方根;'
- '实际换算 factor = sqrt(maxPixels/(w*h))')
- self.sp_clarity = _ispin(0, 20, self.params.clarity, ' px')
- self.sp_guide_r = _ispin(1, 40, self.params.guide_radius, ' px')
- self.sp_guide_eps = _dspin(1e-6, 10.0, 0.001, self.params.guide_eps, 6)
- ff.addRow('焦点图长边:', self.sp_max_pixels)
- ff.addRow('clarity(dilate 半径):', self.sp_clarity)
- ff.addRow('引导滤波半径:', self.sp_guide_r)
- ff.addRow('引导滤波 eps:', self.sp_guide_eps)
- pv.addWidget(gb_fus)
- # --- 前置 ---
- gb_pre = QGroupBox('前置处理')
- fp = QFormLayout(gb_pre)
- self.ck_drop = QCheckBox('剔除异常暗帧')
- self.ck_drop.setChecked(self.params.drop_dark)
- self.sp_drop_ratio = _dspin(0.1, 0.95, 0.05, self.params.drop_dark_ratio, 2)
- self.ck_dead = QCheckBox('单帧坏点抑制')
- self.ck_dead.setChecked(self.params.dead_pixel)
- fp.addRow(self.ck_drop)
- fp.addRow('暗帧判定比例:', self.sp_drop_ratio)
- fp.addRow(self.ck_dead)
- pv.addWidget(gb_pre)
- # --- 后处理 ---
- gb_p = QGroupBox('④ 后处理(finishFusionImageClassic)')
- fpp = QFormLayout(gb_p)
- self.ck_post = QCheckBox('启用后处理')
- self.ck_post.setChecked(self.params.post_enable)
- self.sp_usm_a = _dspin(0.0, 6.0, 0.1, self.params.usm_amount, 2)
- self.sp_usm_s = _dspin(0.1, 12.0, 0.1, self.params.usm_sigma, 2)
- self.cb_pipeline = QComboBox()
- for k in (0, 1, 2, 3, 4, 5, 6, -1):
- self.cb_pipeline.addItem(f'{k} · {E.CONTRAST_PIPELINES[k]}', k)
- self.sp_clip = _dspin(0.1, 10.0, 0.1, self.params.clahe_clip, 2)
- self.sp_tile = _ispin(1, 64, self.params.clahe_tile)
- self.sp_auto_lo = _dspin(0.0, 20.0, 0.5, self.params.auto_low, 1, ' %')
- self.sp_auto_hi = _dspin(80.0, 100.0, 0.5, self.params.auto_high, 1, ' %')
- self.sp_gamma = _dspin(0.2, 5.0, 0.1, self.params.gamma, 2)
- self.ck_gamma_auto = QCheckBox('Gamma 自动')
- self.ck_gamma_auto.setChecked(self.params.gamma_auto)
- self.ck_repair = QCheckBox('黑点修复 repairDarkSpots')
- self.ck_repair.setChecked(self.params.repair_dark)
- fpp.addRow(self.ck_post)
- fpp.addRow('USM amount:', self.sp_usm_a)
- fpp.addRow('USM sigma:', self.sp_usm_s)
- fpp.addRow('对比度 pipeline:', self.cb_pipeline)
- fpp.addRow('CLAHE clip:', self.sp_clip)
- fpp.addRow('CLAHE tile:', self.sp_tile)
- fpp.addRow('Auto 低百分位:', self.sp_auto_lo)
- fpp.addRow('Auto 高百分位:', self.sp_auto_hi)
- fpp.addRow('Gamma:', self.sp_gamma)
- fpp.addRow(self.ck_gamma_auto)
- fpp.addRow(self.ck_repair)
- pv.addWidget(gb_p)
- # --- 指标 ---
- gb_m = QGroupBox('当前显示图指标')
- fm = QFormLayout(gb_m)
- self.lb_m_mean = QLabel('—')
- self.lb_m_lap = QLabel('—')
- self.lb_m_black = QLabel('—')
- self.lb_m_bg = QLabel('—')
- self.lb_m_bgstd = QLabel('—')
- self.lb_m_rb = QLabel('—')
- for k, w in [('灰度均值', self.lb_m_mean), ('细节能量 lapvar', self.lb_m_lap),
- ('纯黑像素', self.lb_m_black), ('背景≥245', self.lb_m_bg),
- ('背景标准差', self.lb_m_bgstd), ('色偏 R-B', self.lb_m_rb)]:
- fm.addRow(k + ':', w)
- pv.addWidget(gb_m)
- # --- 分析结果(常显,分析后自动填充)---
- gb_r = QGroupBox('清晰度分析结果')
- fr = QFormLayout(gb_r)
- self.lb_r_stat = QLabel('尚未分析')
- self.lb_r_stat.setStyleSheet('color:#8a9099;')
- self.lb_r_peak = QLabel('—')
- self.lb_r_range = QLabel('—')
- self.lb_r_mode = QLabel('—')
- self.lb_r_seg = QLabel('—')
- self.lb_r_count = QLabel('—')
- self.lb_r_ratio = QLabel('—')
- self.lb_r_frames = QLabel('—')
- self.lb_r_frames.setWordWrap(True)
- self.lb_r_frames.setStyleSheet('font-family: Consolas; font-size:11px;')
- self.lb_r_here = QLabel('—')
- for k, w in [('状态', self.lb_r_stat), ('峰值帧 / 峰值评分', self.lb_r_peak),
- ('评分 min / 中位 / max', self.lb_r_range),
- ('选帧模式', self.lb_r_mode), ('焦面段 / ratio', self.lb_r_seg),
- ('参与融合帧数', self.lb_r_count),
- ('段内评分占比', self.lb_r_ratio),
- ('当前帧评分', self.lb_r_here),
- ('选中帧', self.lb_r_frames)]:
- fr.addRow(k + ':', w)
- pv.addWidget(gb_r)
- # 供"分析完成后自动滚到结果面板"使用
- self.gb_result = gb_r
- self.scroll_params = scroll
- pv.addStretch(1)
- scroll.setWidget(holder)
- outer.addWidget(scroll, 1)
- # 按钮
- row = QHBoxLayout()
- self.btn_fuse = QPushButton('开始融合 (F6)')
- self.btn_fuse.clicked.connect(self.run_fuse)
- self.btn_post = QPushButton('仅重跑后处理 (F7)')
- self.btn_post.clicked.connect(self.apply_post_only)
- row.addWidget(self.btn_fuse)
- row.addWidget(self.btn_post)
- outer.addLayout(row)
- self.ck_auto_post = QCheckBox('后处理参数即时预览(改参数自动重算)')
- self.ck_auto_post.setChecked(True)
- outer.addWidget(self.ck_auto_post)
- self._connect_param_signals()
- return panel
- def _build_right(self):
- w = QWidget()
- lay = QVBoxLayout(w)
- lay.setContentsMargins(6, 6, 6, 6)
- lay.setSpacing(6)
- self.tabs = QTabWidget()
- self.view_frame = ImageView()
- self.view_raw = ImageView()
- self.view_final = ImageView()
- self.view_cmp = CompareView()
- self.tabs.addTab(self.view_frame, '原始帧')
- self.tabs.addTab(self.view_raw, '融合(未后处理)')
- self.tabs.addTab(self.view_final, '最终结果')
- self.tabs.addTab(self.view_cmp, '对比(原始 / 结果)')
- self.tabs.currentChanged.connect(self._on_tab_changed)
- lay.addWidget(self.tabs, 1)
- # 播放控制
- play = QHBoxLayout()
- self.btn_play = QPushButton('▶ 播放')
- self.btn_play.setCheckable(True)
- self.btn_play.toggled.connect(self._toggle_play)
- self.slider = QSlider(Qt.Horizontal)
- self.slider.setRange(0, 0)
- self.slider.valueChanged.connect(self._on_slider)
- self.sp_fps = _dspin(0.2, 30.0, 0.5, 4.0, 1, ' fps')
- self.sp_fps.valueChanged.connect(self._update_timer_interval)
- self.lb_pos = QLabel('— / —')
- self.lb_pos.setMinimumWidth(110)
- play.addWidget(self.btn_play)
- play.addWidget(self.slider, 1)
- play.addWidget(QLabel('速率'))
- play.addWidget(self.sp_fps)
- play.addWidget(self.lb_pos)
- lay.addLayout(play)
- # 曲线
- self.curve = FocusCurve()
- self.curve.frameClicked.connect(self.goto_frame)
- lay.addWidget(self.curve)
- self.lb_zoom = QLabel('滚轮缩放 · 拖拽平移 · 双击切换 适应窗口/1:1')
- self.lb_zoom.setStyleSheet('color:#7a808a;')
- lay.addWidget(self.lb_zoom)
- for v in (self.view_frame, self.view_raw, self.view_final):
- v.zoomChanged.connect(
- lambda z: self.lb_zoom.setText(
- f'缩放 {z*100:.0f}% · 滚轮缩放 · 拖拽平移 · 双击切换 1:1/适应窗口'))
- return w
- def _build_statusbar(self):
- self.progress = QProgressBar()
- self.progress.setRange(0, 100)
- self.progress.setValue(0)
- self.progress.setMaximumWidth(320)
- self.progress.setTextVisible(True)
- self.statusBar().addPermanentWidget(self.progress)
- self.statusBar().showMessage('就绪')
- from PySide6.QtWidgets import QDockWidget
- dock = QDockWidget('日志', self)
- dock.setAllowedAreas(Qt.BottomDockWidgetArea | Qt.TopDockWidgetArea)
- self.logview = QPlainTextEdit()
- self.logview.setReadOnly(True)
- self.logview.setMaximumBlockCount(4000)
- self.logview.setStyleSheet('font-family: Consolas, "Microsoft YaHei"; font-size:12px;')
- dock.setWidget(self.logview)
- self.addDockWidget(Qt.BottomDockWidgetArea, dock)
- dock.setMinimumHeight(140)
- self.log_dock = dock
- # ----------------------------------------------------------- 参数读取
- def _connect_param_signals(self):
- for w in (self.sp_max_frames, self.sp_ratio_lo, self.sp_min_span,
- self.sp_enough_span, self.sp_wide_frames, self.sp_wide_ratio,
- self.sp_align_edge, self.sp_align_apply,
- self.sp_align_max, self.sp_align_resp, self.sp_max_pixels,
- self.sp_clarity, self.sp_guide_r, self.sp_guide_eps,
- self.sp_drop_ratio, self.sp_usm_a, self.sp_usm_s,
- self.sp_clip, self.sp_tile, self.sp_auto_lo, self.sp_auto_hi,
- self.sp_gamma):
- w.valueChanged.connect(self._on_param_changed)
- for w in (self.ck_align, self.ck_drop, self.ck_dead, self.ck_post,
- self.ck_repair, self.ck_gamma_auto):
- w.toggled.connect(self._on_param_changed)
- self.cb_pipeline.currentIndexChanged.connect(self._on_param_changed)
- self.cb_mode.currentIndexChanged.connect(self._on_mode_changed)
- # 选帧相关参数改动时,实时刷新曲线绿带与结果面板(不必重跑融合)
- for w in (self.sp_max_frames, self.sp_ratio_lo, self.sp_min_span,
- self.sp_enough_span, self.sp_wide_frames, self.sp_wide_ratio):
- w.valueChanged.connect(self._refresh_selection_preview)
- def _on_mode_changed(self, *_):
- """切模式时同步控件的可用性,避免改了不生效的假象"""
- wide = self.cb_mode.currentData() == E.SELECT_MODE_WIDE
- self.sp_wide_frames.setEnabled(wide)
- self.sp_wide_ratio.setEnabled(wide)
- self.sp_max_frames.setEnabled(not wide)
- self.sp_ratio_lo.setEnabled(not wide)
- self.sp_enough_span.setEnabled(not wide)
- self._on_param_changed()
- # 模式变了,已算好的选帧结果要重算并刷新曲线绿带
- if self.scores is not None:
- self._refresh_selection_preview()
- def _refresh_selection_preview(self):
- """用当前参数重算选帧,只刷新曲线上的绿带与分析结果面板"""
- if self.scores is None or len(self.scores) == 0:
- return
- p = self.collect_params()
- self.params = p
- peak = int(np.argmax(self.scores))
- sel = E.select_fuse_frames(self.scores, peak, p.eff_max_frames(),
- p.ratios(), p.min_span, p.eff_enough_span())
- self.curve.set_selected(sel.indices)
- self._fill_analysis_panel(sel)
- def _on_param_changed(self, *_):
- self.params = self.collect_params()
- if self.ck_auto_post.isChecked() and self.result is not None \
- and self.result.fused_raw is not None and not self._busy:
- self._post_timer.start()
- def collect_params(self) -> E.FusionParams:
- side = int(self.sp_max_pixels.value())
- return E.FusionParams(
- select_mode=self.cb_mode.currentData(),
- max_frames=self.sp_max_frames.value(),
- ratio_lo=float(self.sp_ratio_lo.value()),
- min_span=self.sp_min_span.value(),
- enough_span=self.sp_enough_span.value(),
- wide_max_frames=self.sp_wide_frames.value(),
- wide_ratio_lo=float(self.sp_wide_ratio.value()),
- align_enable=self.ck_align.isChecked(),
- align_max_edge=self.sp_align_edge.value(),
- align_min_apply_px=float(self.sp_align_apply.value()),
- align_max_shift_px=float(self.sp_align_max.value()),
- align_min_response=float(self.sp_align_resp.value()),
- max_pixels=side * side,
- clarity=self.sp_clarity.value(),
- guide_radius=self.sp_guide_r.value(),
- guide_eps=float(self.sp_guide_eps.value()),
- drop_dark=self.ck_drop.isChecked(),
- drop_dark_ratio=float(self.sp_drop_ratio.value()),
- dead_pixel=self.ck_dead.isChecked(),
- post_enable=self.ck_post.isChecked(),
- usm_amount=float(self.sp_usm_a.value()),
- usm_sigma=float(self.sp_usm_s.value()),
- pipeline=int(self.cb_pipeline.currentData()),
- clahe_clip=float(self.sp_clip.value()),
- clahe_tile=self.sp_tile.value(),
- auto_low=float(self.sp_auto_lo.value()),
- auto_high=float(self.sp_auto_hi.value()),
- gamma=float(self.sp_gamma.value()),
- gamma_auto=self.ck_gamma_auto.isChecked(),
- repair_dark=self.ck_repair.isChecked(),
- )
- def _load_params_into_ui(self):
- p = self.params
- idx = self.cb_mode.findData(p.select_mode)
- self.cb_mode.setCurrentIndex(max(0, idx))
- self.sp_max_frames.setValue(p.max_frames)
- self.sp_ratio_lo.setValue(p.ratio_lo)
- self.sp_min_span.setValue(p.min_span)
- self.sp_enough_span.setValue(p.enough_span)
- self.sp_wide_frames.setValue(p.wide_max_frames)
- self.sp_wide_ratio.setValue(p.wide_ratio_lo)
- self.ck_align.setChecked(p.align_enable)
- self.sp_align_edge.setValue(p.align_max_edge)
- self.sp_align_apply.setValue(p.align_min_apply_px)
- self.sp_align_max.setValue(p.align_max_shift_px)
- self.sp_align_resp.setValue(p.align_min_response)
- self.sp_max_pixels.setValue(int(round(np.sqrt(p.max_pixels))))
- self.sp_clarity.setValue(p.clarity)
- self.sp_guide_r.setValue(p.guide_radius)
- self.sp_guide_eps.setValue(p.guide_eps)
- self.ck_drop.setChecked(p.drop_dark)
- self.sp_drop_ratio.setValue(p.drop_dark_ratio)
- self.ck_dead.setChecked(p.dead_pixel)
- self.ck_post.setChecked(p.post_enable)
- self.sp_usm_a.setValue(p.usm_amount)
- self.sp_usm_s.setValue(p.usm_sigma)
- idx = self.cb_pipeline.findData(p.pipeline)
- self.cb_pipeline.setCurrentIndex(max(0, idx))
- self.sp_clip.setValue(p.clahe_clip)
- self.sp_tile.setValue(p.clahe_tile)
- self.sp_auto_lo.setValue(p.auto_low)
- self.sp_auto_hi.setValue(p.auto_high)
- self.sp_gamma.setValue(p.gamma)
- self.ck_gamma_auto.setChecked(p.gamma_auto)
- self.ck_repair.setChecked(p.repair_dark)
- self._on_mode_changed()
- # ------------------------------------------------------------- 工具
- def log(self, msg: str):
- self.logview.appendPlainText(f'[{time.strftime("%H:%M:%S")}] {msg}')
- def _set_busy(self, busy: bool, msg: str = ''):
- self._busy = busy
- for a in (self.act_open, self.act_analyze, self.act_fuse, self.act_post):
- a.setEnabled(not busy)
- self.btn_fuse.setEnabled(not busy)
- self.btn_post.setEnabled(not busy)
- if msg:
- self.statusBar().showMessage(msg)
- if not busy:
- self.progress.setValue(self.progress.maximum())
- self.progress.setFormat('%p%')
- if not busy and self.progress.maximum() == 0:
- self.progress.setRange(0, 100)
- self.progress.setValue(100)
- def _run_task(self, fn, on_done, *args, **kwargs):
- if self._pending:
- # 已有任务在跑:直接忽略,避免两个任务互相覆盖进度/结果
- self.log('⚠ 已有任务正在执行,本次请求已忽略')
- return
- t = Task(fn, *args, **kwargs)
- t.signals.progress.connect(self._on_progress)
- # 完成/失败不依赖信号,交给 _poll_tasks 轮询 t.done(见 Task 类注释)
- self._pending[t] = on_done
- self._tasks.add(t)
- self._task_started = time.time()
- self._last_progress_ts = time.time()
- self._set_busy(True, '处理中...')
- self.progress.setRange(0, 100)
- self.progress.setValue(0)
- self.pool.start(t)
- def _poll_tasks(self):
- """主线程轮询收割任务结果 —— 不依赖跨线程信号,绝不会漏收"""
- for t in list(self._pending):
- if not t.done:
- continue
- on_done = self._pending.pop(t)
- self._tasks.discard(t)
- if t.cancelled:
- continue
- if t.error:
- self._on_failed(t.error)
- continue
- self._set_busy(False)
- try:
- on_done(t.result)
- except Exception:
- self.log('❌ 结果处理异常:\n' + traceback.format_exc())
- def _on_progress(self, done, total, msg):
- self._last_progress_ts = time.time()
- total = max(1, total)
- self.progress.setRange(0, total)
- self.progress.setValue(min(done, total))
- self.progress.setFormat(f'{msg} %p%')
- if msg:
- self.statusBar().showMessage(msg)
- def _on_failed(self, tb):
- self._set_busy(False, '失败')
- self.log('❌ 任务失败:\n' + tb)
- QMessageBox.critical(self, '出错', tb.splitlines()[-1] if tb else '未知错误')
- def _check_stuck(self):
- """忙状态看门狗:兜住"任务卡死"的极端情况
- 正常情况下 _poll_tasks 一定会收割到结果;这里只处理两种异常:
- · 进度已满却 8s 还在忙(理论上不会发生,收割轮询 120ms 一次)
- · 整体超过 15 分钟毫无进展
- """
- if not self._busy:
- return
- now = time.time()
- pct_done = (self.progress.value() >= self.progress.maximum()
- and self.progress.maximum() > 0)
- idle = now - self._last_progress_ts
- if (pct_done and idle > 8.0) or (now - self._task_started > 900):
- self.log('⚠ 任务长时间无响应,已自动解锁界面。若任务仍在后台运行,'
- '其结果会被丢弃,请重新执行。')
- for t in list(self._tasks):
- t.cancelled = True
- self._tasks.clear()
- self._pending.clear()
- self._set_busy(False, '已自动解锁(任务无响应)')
- self.progress.setRange(0, 100)
- self.progress.setValue(0)
- self.progress.setFormat('%p%')
- # ------------------------------------------------------------- 打开
- def open_file(self):
- path, _ = QFileDialog.getOpenFileName(
- self, '打开 .rawv 录制文件', self._default_dir(),
- 'RAW 视频 (*.rawv);;所有文件 (*.*)')
- if not path:
- return
- self.open_path(path)
- def open_path(self, path: str):
- """按路径打开(供命令行参数与文件对话框共用)"""
- try:
- v = E.RawVideo(path)
- except Exception as exc:
- QMessageBox.critical(self, '无法打开', str(exc))
- return
- self.video = v
- self.scores = None
- self.result = None
- self._preview_cache.clear()
- info = v.info()
- self.lb_file.setText(info['file'])
- self.lb_geom.setText(f"{info['width']} × {info['height']}(stride {info['stride']})")
- self.lb_fmt.setText(f"{info['pixfmt_name']}(pixfmt={info['pixfmt']})")
- n = info['usable']
- extra = '' if n == info['frames'] else f'(文件头写 {info["frames"]},实际可读 {n})'
- self.lb_frames.setText(f"{n} 帧 @ {info['fps']} fps{extra}")
- self.lb_size.setText(f"{info['size_real']/1048576:.1f} MB")
- self.curve.set_scores(None)
- self.curve.set_selected([])
- self.lb_r_stat.setText('尚未分析')
- self.lb_r_stat.setStyleSheet('color:#8a9099;')
- for lb in (self.lb_r_peak, self.lb_r_range, self.lb_r_mode, self.lb_r_seg,
- self.lb_r_count, self.lb_r_ratio, self.lb_r_frames,
- self.lb_r_here):
- lb.setText('—')
- self.view_raw.clear_image()
- self.view_final.clear_image()
- self.slider.setRange(0, max(0, n - 1))
- self.slider.setValue(0)
- self.log(f'已打开 {info["file"]}:{info["width"]}×{info["height"]} '
- f'{info["pixfmt_name"]} {n} 帧')
- if info['truncated']:
- self.log('⚠ 文件比文件头声明的小(可能录制中断),已按实际可读帧数处理')
- self.goto_frame(0)
- def _default_dir(self) -> str:
- for cand in (os.path.join(BASE_DIR, '..', '..', 'Test'),
- os.path.join(BASE_DIR, '..', '..')):
- if os.path.isdir(cand):
- return os.path.abspath(cand)
- return BASE_DIR
- # ------------------------------------------------------------- 分析
- def run_analyze(self):
- if not self._require_video():
- return
- # 忙状态统一由 _run_task 负责设置,这里不要再预置 —— 否则会被并发守卫拦掉
- self._run_task(E.analyze, self._on_analyzed, self.video,
- clarity=self.params.clarity)
- def _on_analyzed(self, scores):
- self.scores = np.asarray(scores, np.float64)
- self.curve.set_scores(self.scores)
- self.curve.set_selected([])
- if not len(self.scores):
- self.lb_r_stat.setText('分析无结果(可读帧数为 0)')
- self.lb_r_stat.setStyleSheet('color:#c0392b;')
- return
- peak = int(np.argmax(self.scores))
- self.curve.set_peak(peak)
- p = self.params
- sel = E.select_fuse_frames(self.scores, peak, p.eff_max_frames(),
- p.ratios(), p.min_span, p.eff_enough_span())
- self.curve.set_selected(sel.indices)
- self._fill_analysis_panel(sel)
- # 参数面板很长,分析完自动滚到结果区,避免用户以为"点了没反应"
- try:
- self.scroll_params.ensureWidgetVisible(self.gb_result, 0, 8)
- except Exception:
- pass
- self.log(f'分析完成:{len(self.scores)} 帧,峰值 #{peak} = '
- f'{self.scores[peak]:.4f}')
- self.log(f' 模式={E.SELECT_MODE_NAMES.get(p.select_mode)}')
- if sel.fallback:
- self.log(f' 选帧回退中心邻域({sel.note})')
- else:
- self.log(f' 焦面段 [{sel.segment[0]},{sel.segment[1]}] '
- f'ratio={sel.ratio} → {len(sel.indices)} 帧 {sel.indices}')
- # 分析完直接停在峰值帧,并把视图切到「原始帧」,否则用户会以为没反应
- self.tabs.setCurrentWidget(self.view_frame)
- self.goto_frame(peak)
- self._update_metrics()
- self.statusBar().showMessage(
- f'分析完成:峰值 #{peak},选帧 {len(sel.indices)} 帧'
- f'({E.SELECT_MODE_SHORT.get(p.select_mode, p.select_mode)})', 8000)
- def _fill_analysis_panel(self, sel):
- """把分析/选帧结果写进左侧「清晰度分析结果」面板"""
- if self.scores is None or len(self.scores) == 0:
- self.lb_r_stat.setText('尚未分析')
- self.lb_r_stat.setStyleSheet('color:#8a9099;')
- return
- d = E.summarize_scores(self.scores, sel)
- p = self.params
- mode_txt = E.SELECT_MODE_NAMES.get(p.select_mode, p.select_mode)
- self.lb_r_stat.setText('已完成')
- self.lb_r_stat.setStyleSheet('color:#1e8e4f; font-weight:600;')
- self.lb_r_peak.setText(f"#{d['peak_index']} {d['peak']:.4f}")
- self.lb_r_range.setText(f"{d['smin']:.3f} / {d['median']:.3f} / {d['peak']:.3f}")
- self.lb_r_mode.setText(mode_txt)
- if sel is None or not sel.indices:
- self.lb_r_seg.setText('—')
- self.lb_r_count.setText('—')
- self.lb_r_ratio.setText('—')
- self.lb_r_frames.setText('—')
- return
- if sel.fallback:
- self.lb_r_seg.setText(f'回退中心邻域({sel.note})')
- else:
- self.lb_r_seg.setText(f'[{sel.segment[0]}, {sel.segment[1]}] ratio={sel.ratio}')
- self.lb_r_count.setText(f'{len(sel.indices)} 帧'
- + (f'(剔除暗帧 {len(self.result.dropped)})'
- if self.result and self.result.dropped else ''))
- lo = d.get('span_ratio_min')
- hi = d.get('span_ratio_max')
- if lo is not None:
- color = '#1e8e4f' if lo >= 0.9 else ('#b7791f' if lo >= 0.6 else '#c0392b')
- self.lb_r_ratio.setText(f'{lo:.3f} ~ {hi:.3f}')
- self.lb_r_ratio.setStyleSheet(f'color:{color};')
- self.lb_r_ratio.setToolTip(
- '段内每帧评分 / 峰值。接近 1.0 说明都是同一焦面(窄段);\n'
- '低到 0.6 左右说明纳入了明显离焦的帧(宽段景深扩展)。')
- self.lb_r_frames.setText(', '.join(str(i) for i in sel.indices))
- # ------------------------------------------------------------- 融合
- def run_fuse(self):
- if not self._require_video():
- return
- if self.scores is None:
- QMessageBox.information(self, '请先分析', '融合需要逐帧评分,先执行「① 分析清晰度」。')
- return
- params = self.collect_params()
- self.params = params
- self._run_task(E.fuse, self._on_fused, self.video, self.scores, params)
- def _on_fused(self, res: E.FuseResult):
- self.result = res
- for line in res.log:
- self.log(' ' + line)
- if res.fused_raw is not None:
- self.view_raw.set_image(res.fused_raw, keep_view=False)
- if res.fused_final is not None:
- self.view_final.set_image(res.fused_final, keep_view=False)
- self.curve.set_selected(res.selected)
- if res.select is not None:
- self._fill_analysis_panel(res.select)
- self._refresh_compare()
- self.tabs.setCurrentWidget(self.view_final)
- self._update_metrics()
- n = len(res.selected)
- mode = E.SELECT_MODE_SHORT.get(res.mode, res.mode)
- self.statusBar().showMessage(f'融合完成:{n} 帧({mode})', 8000)
- self.log(f'融合完成:{n} 帧({E.SELECT_MODE_NAMES.get(res.mode, res.mode)})。'
- f'切「最终结果」看成品,「对比」可同屏比原始与结果。')
- def apply_post_only(self):
- if self.result is None or self.result.fused_raw is None:
- return
- params = self.collect_params()
- self.params = params
- raw = self.result.fused_raw
- t0 = time.time()
- def work(progress=None):
- if progress:
- progress(0, 2, '后处理中...')
- img, info = E.reprocess(raw, params)
- if progress:
- progress(2, 2, '完成')
- return img, info
- def done(out):
- img, info = out
- self.result.fused_final = img
- self.result.post_info = info
- self.result.repaired = info.get('repaired', 0)
- self.view_final.set_image(img, keep_view=True)
- self._refresh_compare()
- if self.tabs.currentWidget() is self.view_final or \
- self.tabs.currentWidget() is self.view_cmp:
- pass
- self._update_metrics()
- self.log(f'后处理重算 {time.time()-t0:.2f}s:USM({params.usm_amount},'
- f'{params.usm_sigma}) + '
- f'{E.CONTRAST_PIPELINES.get(params.pipeline, params.pipeline)}'
- + (f',修复黑点 {info.get("repaired",0)} px'
- if info.get('repaired') else ''))
- self.statusBar().showMessage('后处理已更新', 2500)
- self._run_task(work, done)
- # ------------------------------------------------------------- 帧显示
- def goto_frame(self, idx: int):
- if self.video is None:
- return
- n = self.video.usable_frames
- if n <= 0:
- return
- idx = int(max(0, min(n - 1, idx)))
- self.current_frame = idx
- if self.slider.value() != idx:
- self.slider.blockSignals(True)
- self.slider.setValue(idx)
- self.slider.blockSignals(False)
- self.lb_pos.setText(f'{idx} / {n - 1}')
- self.curve.set_current(idx)
- img = self._preview_cache.get(idx)
- if img is None:
- img = self.video.bgr_small(idx, max_edge=1100)
- if len(self._preview_cache) > 80:
- self._preview_cache.clear()
- self._preview_cache[idx] = img
- self.view_frame.set_image(img, keep_view=True)
- # 当前帧评分 + 是否被选入融合
- if self.scores is not None and 0 <= idx < len(self.scores):
- peak = float(self.scores.max()) or 1.0
- v = float(self.scores[idx])
- picked = self.curve.selected
- mark = ' ✔已选入融合' if idx in picked else ''
- self.lb_r_here.setText(f'#{idx} {v:.4f} (占峰值 {v/peak*100:.1f}%){mark}')
- self.lb_r_here.setStyleSheet(
- 'color:#1e8e4f;' if idx in picked else 'color:#8a9099;')
- else:
- self.lb_r_here.setText('—')
- if self.tabs.currentWidget() is self.view_cmp:
- self._refresh_compare()
- def _on_slider(self, v):
- self.goto_frame(v)
- def _on_tab_changed(self, _i):
- if self.tabs.currentWidget() is self.view_cmp:
- self._refresh_compare()
- self._update_metrics()
- def _refresh_compare(self):
- """对比页:左=当前帧原图(全分辨率,保证与结果同尺寸),右=最终结果"""
- left = None
- if self.video is not None:
- left = self._cmp_cache.get(self.current_frame)
- if left is None:
- left = self.video.bgr(self.current_frame) # 全分辨率,与结果同尺寸
- if len(self._cmp_cache) > 12:
- self._cmp_cache.clear()
- self._cmp_cache[self.current_frame] = left
- right = self.result.fused_final if self.result is not None else None
- self.view_cmp.set_pair(left, right)
- # ------------------------------------------------------------- 播放
- def _toggle_play(self, on):
- if on:
- if self.video is None:
- self.btn_play.setChecked(False)
- return
- self.btn_play.setText('⏸ 暂停')
- self._update_timer_interval()
- self.timer.start()
- else:
- self.btn_play.setText('▶ 播放')
- self.timer.stop()
- def _update_timer_interval(self, *_):
- self.timer.setInterval(max(30, int(1000.0 / max(0.2, self.sp_fps.value()))))
- def _play_tick(self):
- if self.video is None:
- return
- n = self.video.usable_frames
- if n <= 0:
- return
- self.goto_frame((self.current_frame + 1) % n)
- # ------------------------------------------------------------- 指标
- def _current_image(self):
- w = self.tabs.currentWidget()
- if w is self.view_frame:
- return self._preview_cache.get(self.current_frame)
- if w is self.view_raw:
- return self.result.fused_raw if self.result else None
- if w is self.view_final:
- return self.result.fused_final if self.result else None
- if w is self.view_cmp:
- return self.result.fused_final if self.result else None
- return None
- def _update_metrics(self):
- img = self._current_image()
- if img is None:
- for lb in (self.lb_m_mean, self.lb_m_lap, self.lb_m_black,
- self.lb_m_bg, self.lb_m_bgstd, self.lb_m_rb):
- lb.setText('—')
- return
- m = E.quick_metrics(img)
- self.lb_m_mean.setText(f'{m.get("mean", 0):.2f}')
- self.lb_m_lap.setText(f'{m.get("lapvar", 0):.1f}')
- self.lb_m_black.setText(f'{m.get("pure_black", 0)}')
- self.lb_m_bg.setText(f'{m.get("bg245", 0):.1f}%')
- self.lb_m_bgstd.setText(f'{m.get("bg_std", 0):.2f}')
- self.lb_m_rb.setText(f'{m.get("rb", 0):+.1f}')
- # ------------------------------------------------------------- 导出
- def export_result(self):
- if self.result is None or self.result.fused_final is None:
- QMessageBox.information(self, '没有结果', '先执行融合。')
- return
- w = self.tabs.currentWidget()
- if w is self.view_raw and self.result.fused_raw is not None:
- img, suffix = self.result.fused_raw, '_fused'
- else:
- img, suffix = self.result.fused_final, '_final'
- base = os.path.splitext(os.path.basename(self.video.path))[0] if self.video else 'result'
- path, _ = QFileDialog.getSaveFileName(
- self, '导出图片', os.path.join(self._default_dir(), base + suffix + '.png'),
- 'PNG (*.png);;JPEG (*.jpg)')
- if not path:
- return
- ext = os.path.splitext(path)[1].lower()
- params = [cv2.IMWRITE_JPEG_QUALITY, 96] if ext in ('.jpg', '.jpeg') \
- else [cv2.IMWRITE_PNG_COMPRESSION, 3]
- ok, buf = cv2.imencode(ext, img, params)
- if not ok:
- QMessageBox.critical(self, '导出失败', '编码失败')
- return
- buf.tofile(path)
- self.log(f'已导出 {path}')
- def save_params(self):
- path, _ = QFileDialog.getSaveFileName(
- self, '保存参数', os.path.join(BASE_DIR, 'params.json'), 'JSON (*.json)')
- if not path:
- return
- with open(path, 'w', encoding='utf-8') as f:
- json.dump(self.collect_params().as_dict(), f, ensure_ascii=False, indent=2)
- self.log(f'参数已保存 {path}')
- def load_params(self):
- path, _ = QFileDialog.getOpenFileName(
- self, '载入参数', BASE_DIR, 'JSON (*.json)')
- if not path:
- return
- try:
- with open(path, encoding='utf-8') as f:
- d = json.load(f)
- p = E.FusionParams(**{k: v for k, v in d.items()
- if k in E.FusionParams.__dataclass_fields__})
- except Exception as exc:
- QMessageBox.critical(self, '载入失败', str(exc))
- return
- self.params = p
- self._load_params_into_ui()
- self.log(f'参数已载入 {path}')
- def reset_params(self):
- self.params = E.FusionParams()
- self._load_params_into_ui()
- self.log('已恢复 app 2.8.39 默认参数')
- def force_unlock(self):
- """手动解除忙状态(任务真卡住时的逃生口)"""
- if not self._busy:
- self.statusBar().showMessage('当前不忙,无需解锁', 3000)
- return
- for t in list(self._tasks):
- t.cancelled = True
- self._tasks.clear()
- self._pending.clear()
- self._set_busy(False, '已手动解锁')
- self.progress.setRange(0, 100)
- self.progress.setValue(0)
- self.progress.setFormat('%p%')
- self.log('已手动解除忙状态。若是任务仍在后台运行,其结果会被丢弃。')
- # ------------------------------------------------------------- 校验
- def _require_video(self) -> bool:
- if self.video is None:
- QMessageBox.information(self, '请先打开文件', '先用「打开 .rawv」选择录制文件。')
- return False
- return True
- def _install_excepthook():
- """把未捕获异常写进日志文件。
- 用 pythonw 启动时没有控制台,stderr 会被丢弃,槽函数里的异常会静默消失
- (表现为"点了没反应")。这里统一落盘,便于现场排查。
- """
- log_path = os.path.join(BASE_DIR, 'rawv_studio.err.log')
- def hook(exc_type, exc, tb):
- text = ''.join(traceback.format_exception(exc_type, exc, tb))
- try:
- with open(log_path, 'a', encoding='utf-8') as f:
- f.write(f'\n===== {time.strftime("%Y-%m-%d %H:%M:%S")} =====\n{text}')
- except Exception:
- pass
- sys.__excepthook__(exc_type, exc, tb)
- sys.excepthook = hook
- def main():
- _install_excepthook()
- app = QApplication(sys.argv)
- app.setStyle('Fusion')
- f = QFont('Microsoft YaHei', 9)
- app.setFont(f)
- win = MainWindow()
- win.show()
- # 支持命令行直接带文件
- if len(sys.argv) > 1 and os.path.isfile(sys.argv[1]):
- try:
- win.open_path(sys.argv[1])
- except Exception:
- pass
- sys.exit(app.exec())
- if __name__ == '__main__':
- main()
|