engine.py 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105
  1. # -*- coding: utf-8 -*-
  2. """RawvStudio 算法核心 —— 与 app 端 C++ 逐条对应
  3. 本模块是 app 侧成像链路的 Python 等价实现,供 Windows 上位机(app.py)调用。
  4. 所有函数的注释都标了对应的 C++ 文件与函数名,便于逐条核对。
  5. 对应关系:
  6. RawVideo ← src/cameramanager.cpp readRawVideoMeta / readRawVideoFrameBgr
  7. decodeRawBufferToBgr
  8. slview_get_edge ← src/slview_focus.cpp getEdge
  9. slview_focus_score ← src/slview_focus.cpp focusScore
  10. select_fuse_frames ← src/cameramanager.cpp selectFuseFrames (2.8.39)
  11. align_translation ← src/m_opencv.cpp alignTranslationSLView (2.8.39)
  12. guided_filter ← src/slview_focus.cpp guidedFilter
  13. guide_filter_fusion ← src/slview_focus.cpp guideFilterFusion
  14. suppress_dead_pixels ← src/m_opencv.cpp suppressDeadPixels
  15. unsharp_mask ← src/m_opencv.cpp unsharpMask
  16. enhance_contrast ← src/m_opencv.cpp enhanceContrast (+CLAHE/Auto/Gamma/Retinex)
  17. repair_dark_spots ← src/m_opencv.cpp repairDarkSpots
  18. finish_fusion_classic ← src/m_opencv.cpp finishFusionImageClassic
  19. 【通道顺序铁律】本项目 Bayer 必须用 COLOR_BayerXX2RGB 解码、然后当 BGR 用。
  20. app 侧 decodeRawBufferToBgr 就是这么做的(OpenCV 的 Bayer 命名与海康相差一个 R/B)。
  21. 若误用 XX2BGR,孢子会由金褐色变成青蓝色。
  22. """
  23. from __future__ import annotations
  24. import os
  25. import struct
  26. from dataclasses import dataclass, field, asdict
  27. from typing import Callable, List, Optional, Sequence, Tuple
  28. import cv2
  29. import numpy as np
  30. # ============================================================================
  31. # 一、.rawv 读取(对应 src/cameramanager.cpp)
  32. # ============================================================================
  33. RAW_HEADER_SIZE = 32 # kRawHeaderSize
  34. RAW_MAGIC = b'RAWV' # kRawVersion=1
  35. RAW_VERSION = 1
  36. # RawPixelFormat 枚举(cameramanager.cpp:82-89)
  37. PIXFMT_BGRA8 = 0
  38. PIXFMT_BAYER_RG8 = 1
  39. PIXFMT_BAYER_GR8 = 2
  40. PIXFMT_BAYER_GB8 = 3
  41. PIXFMT_BAYER_BG8 = 4
  42. PIXFMT_YUYV = 5
  43. PIXFMT_NAMES = {
  44. PIXFMT_BGRA8: 'BGRA8(旧格式)',
  45. PIXFMT_BAYER_RG8: 'BayerRG8',
  46. PIXFMT_BAYER_GR8: 'BayerGR8',
  47. PIXFMT_BAYER_GB8: 'BayerGB8',
  48. PIXFMT_BAYER_BG8: 'BayerBG8',
  49. PIXFMT_YUYV: 'YUYV',
  50. }
  51. # 与 decodeRawBufferToBgr 完全一致的转换码:XX2RGB 后当 BGR 用
  52. _BAYER_CODES = {
  53. PIXFMT_BAYER_RG8: cv2.COLOR_BayerRG2RGB,
  54. PIXFMT_BAYER_GR8: cv2.COLOR_BayerGR2RGB,
  55. PIXFMT_BAYER_GB8: cv2.COLOR_BayerGB2RGB,
  56. PIXFMT_BAYER_BG8: cv2.COLOR_BayerBG2RGB,
  57. }
  58. class RawVideo:
  59. """读取 .rawv 录制文件。
  60. 文件头 32 字节(writeRawHeader,大端序无关,统一小端):
  61. magic[4]='RAWV' | ver u32 | w u32 | h u32 | stride u32
  62. | fps u32 | frames u32 | pixfmt u32
  63. """
  64. def __init__(self, path: str):
  65. self.path = path
  66. with open(path, 'rb') as f:
  67. head = f.read(RAW_HEADER_SIZE)
  68. if len(head) < RAW_HEADER_SIZE or head[:4] != RAW_MAGIC:
  69. raise ValueError('不是有效的 .rawv 文件(magic 不匹配)')
  70. (self.version, self.width, self.height, self.stride,
  71. self.fps, self.frame_count, self.pixfmt) = struct.unpack('<7I', head[4:32])
  72. self.frame_bytes = self.stride * self.height
  73. self.expected_size = RAW_HEADER_SIZE + self.frame_bytes * self.frame_count
  74. self.real_size = os.path.getsize(path)
  75. self._cache: dict = {}
  76. # ---------- 元信息 ----------
  77. @property
  78. def pixfmt_name(self) -> str:
  79. return PIXFMT_NAMES.get(self.pixfmt, f'未知({self.pixfmt})')
  80. @property
  81. def truncated(self) -> bool:
  82. return self.real_size < self.expected_size
  83. @property
  84. def usable_frames(self) -> int:
  85. """实际可读帧数:文件被截断时按实际大小算,避免读到半帧"""
  86. if self.frame_bytes <= 0:
  87. return 0
  88. avail = max(0, self.real_size - RAW_HEADER_SIZE)
  89. return min(self.frame_count, avail // self.frame_bytes)
  90. def info(self) -> dict:
  91. return dict(file=os.path.basename(self.path), path=self.path,
  92. width=self.width, height=self.height, stride=self.stride,
  93. fps=self.fps, frames=self.frame_count,
  94. usable=self.usable_frames, pixfmt=self.pixfmt,
  95. pixfmt_name=self.pixfmt_name,
  96. size_real=self.real_size, size_expect=self.expected_size,
  97. truncated=self.truncated)
  98. # ---------- 帧读取 ----------
  99. def raw(self, index: int) -> np.ndarray:
  100. """读单通道原始帧(Bayer 或 BGRA 字节流),返回 (h, stride) 的 uint8"""
  101. if index < 0 or index >= self.usable_frames:
  102. raise IndexError(f'帧号 {index} 超出范围 [0, {self.usable_frames})')
  103. with open(self.path, 'rb') as f:
  104. f.seek(RAW_HEADER_SIZE + index * self.frame_bytes)
  105. buf = f.read(self.frame_bytes)
  106. arr = np.frombuffer(buf, np.uint8)
  107. return arr.reshape(self.height, self.stride)[:, :self.width]
  108. def bgr(self, index: int) -> np.ndarray:
  109. """解码为 BGR 顺序的图(与 app 同一口径,见文件头注释)"""
  110. if index in self._cache:
  111. return self._cache[index]
  112. raw = self.raw(index)
  113. if self.pixfmt == PIXFMT_BGRA8:
  114. # 旧格式:BGRA 交织,stride 为字节数
  115. rows = self.stride // 4
  116. rgba = raw.reshape(self.height, rows, 4)[:, :self.width // 4, :]
  117. img = cv2.cvtColor(rgba, cv2.COLOR_BGRA2BGR)
  118. elif self.pixfmt == PIXFMT_YUYV:
  119. yuyv = raw.reshape(self.height, self.width // 2, 2)
  120. img = cv2.cvtColor(yuyv, cv2.COLOR_YUV2BGR_YUYV)
  121. elif self.pixfmt in _BAYER_CODES:
  122. img = cv2.cvtColor(raw, _BAYER_CODES[self.pixfmt])
  123. else:
  124. raise ValueError(f'不支持的像素格式 pixfmt={self.pixfmt}')
  125. if len(self._cache) > 64: # 只缓存少量,避免 5MP×N 吃满内存
  126. self._cache.clear()
  127. self._cache[index] = img
  128. return img
  129. def bgr_at_div(self, index: int, div: int = 4) -> np.ndarray:
  130. """对应 decodeRawBufferToBgrSmall:先在单通道域 INTER_AREA 降采样,再解马赛克。
  131. 为什么这样做:Bayer 的 2x2 相位只有在"整块平均"下才能保持;
  132. 先把原图按整数倍缩小再解马赛克,等价于对 R/G/G/B 各自降采样,
  133. 结果与"全量解马赛克再缩小"几乎一致,但插值计算量降到 1/div²。
  134. div 必须是 2 的倍数(否则相位被破坏,会出现彩色摩尔纹)。
  135. """
  136. div = max(2, int(div) // 2 * 2)
  137. raw = self.raw(index)
  138. if self.pixfmt in _BAYER_CODES:
  139. h, w = raw.shape
  140. sw = max(2, (w // div) & ~1)
  141. sh = max(2, (h // div) & ~1)
  142. small = cv2.resize(raw, (sw, sh), interpolation=cv2.INTER_AREA)
  143. return cv2.cvtColor(small, _BAYER_CODES[self.pixfmt])
  144. img = self.bgr(index)
  145. h, w = img.shape[:2]
  146. return cv2.resize(img, (max(1, w // div), max(1, h // div)),
  147. interpolation=cv2.INTER_AREA)
  148. def score_size(self) -> Tuple[int, int]:
  149. """app 评分用的分辨率:宽高各 1/4(findSharpestFrameIndex 的 smallSize)"""
  150. return max(1, self.width // 4), max(1, self.height // 4)
  151. def bgr_small(self, index: int, max_edge: int = 900) -> np.ndarray:
  152. """缩小预览(播放用):解码后按长边缩放。
  153. 不用"Bayer 2x2 块抽样":那只对 GR 图案成立,其余图案会错相位产生彩色摩尔纹。
  154. 解码本身是主要开销(5MP 约 25ms),缩放只在缩略图上做,代价可忽略。
  155. """
  156. img = self.bgr(index)
  157. h, w = img.shape[:2]
  158. sc = min(1.0, max_edge / float(max(h, w)))
  159. if sc < 1.0:
  160. img = cv2.resize(img, None, fx=sc, fy=sc, interpolation=cv2.INTER_AREA)
  161. return img
  162. # ============================================================================
  163. # 二、SLView 焦点度量(对应 src/slview_focus.cpp)
  164. # ============================================================================
  165. K_LOG_SCALE = 150.0 / np.log(256.0) # kLogScale ≈ 27.0505
  166. K_GUIDE_EPS = 0.065025 # kGuideEps = (0.001*255)^2
  167. K_GUIDE_RADIUS = 5 # kGuideRadius
  168. K_FOCUS_BLUR = 9 # kFocusBlur
  169. K_SOBEL_KSIZE = 1 # kSobelKsize
  170. K_DEFAULT_CLARITY = 5 # kDefaultClarity
  171. K_DEFAULT_MAX_PIXELS = 1280 * 720 # kDefaultMaxPixels
  172. def _to_gray8(src: np.ndarray) -> np.ndarray:
  173. if src.ndim == 2:
  174. return src
  175. if src.shape[2] == 3:
  176. return cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
  177. if src.shape[2] == 4:
  178. return cv2.cvtColor(src, cv2.COLOR_BGRA2GRAY)
  179. raise ValueError('slview::getEdge: 不支持的通道数')
  180. def slview_get_edge(src: np.ndarray, radius: int = K_DEFAULT_CLARITY
  181. ) -> Tuple[np.ndarray, np.ndarray]:
  182. """slview::getEdge —— 返回 (mag, focus)
  183. gray → log(I+1)*150/ln256 → Sobel(ksize=1) 的 L1 幅值
  184. → dilate((2r+1)²) 局部最大 → GaussianBlur(9x9)
  185. """
  186. gray = _to_gray8(src).astype(np.float32)
  187. mag = np.log(gray + 1.0, dtype=np.float32) * np.float32(K_LOG_SCALE)
  188. # ksize=1 的 Sobel 就是无平滑的 [-1,0,1]。用 filter2D 显式构造,
  189. # 与 C++ 的 cv::Sobel(..., ksize=1) 完全等价(避免 OpenCV 对 float 输入的限制)。
  190. kx = np.array([[-1.0, 0.0, 1.0]], np.float32) # 1x3 水平差分
  191. ky = kx.T.copy() # 3x1 垂直差分
  192. gx = cv2.filter2D(mag, -1, kx, borderType=cv2.BORDER_REFLECT_101)
  193. gy = cv2.filter2D(mag, -1, ky, borderType=cv2.BORDER_REFLECT_101)
  194. mag = np.abs(gx) + np.abs(gy)
  195. r = max(0, int(radius))
  196. if r > 0:
  197. k = 2 * r + 1
  198. kern = cv2.getStructuringElement(cv2.MORPH_RECT, (k, k))
  199. focus = cv2.dilate(mag, kern, borderType=cv2.BORDER_CONSTANT,
  200. borderValue=0)
  201. else:
  202. focus = mag.copy()
  203. focus = cv2.GaussianBlur(focus, (K_FOCUS_BLUR, K_FOCUS_BLUR), 0, 0,
  204. borderType=cv2.BORDER_REFLECT_101)
  205. return mag, focus
  206. def slview_focus_score(src: np.ndarray, radius: int = K_DEFAULT_CLARITY) -> float:
  207. """slview::focusScore —— 焦点图均值(用它圈定焦面区间)"""
  208. if src is None or src.size == 0:
  209. return 0.0
  210. _, focus = slview_get_edge(src, radius)
  211. return float(focus.mean())
  212. # ============================================================================
  213. # 三、选帧(对应 src/cameramanager.cpp selectFuseFrames,2.8.39 新实现)
  214. # ============================================================================
  215. @dataclass
  216. class SelectResult:
  217. indices: List[int]
  218. peak: float
  219. peak_index: int
  220. segment: Tuple[int, int]
  221. ratio: float
  222. fallback: bool
  223. note: str = ''
  224. def select_fuse_frames(scores: Sequence[float],
  225. center: int,
  226. max_frames: int = 12,
  227. ratios: Sequence[float] = (0.97, 0.95, 0.92, 0.90,
  228. 0.85, 0.80, 0.72, 0.62, 0.50),
  229. min_span: int = 4,
  230. enough_span: int = 6) -> SelectResult:
  231. """选帧:在"评分 ≥ ratio×峰值"的连续段里取 Σscore 最大的一段。
  232. 为什么不用"围绕 argmax 取邻域":录制末端常有同焦面的重复帧,
  233. 它会把评分峰值顶到末尾,导致"清晰帧 + 一堆离焦帧"被一起融合。
  234. 段积分天然抑制这种孤立尖刺。
  235. """
  236. n = len(scores)
  237. if n == 0 or center < 0 or center >= n or max_frames <= 0:
  238. return SelectResult([], 0.0, center, (-1, -1), 0.0, True, '参数非法')
  239. peak = float(max(scores))
  240. peak_idx = int(np.argmax(np.asarray(scores)))
  241. def _fallback(reason: str) -> SelectResult:
  242. idx, d = [center], 1
  243. while len(idx) < max_frames:
  244. if center - d >= 0:
  245. idx.append(center - d)
  246. if len(idx) >= max_frames:
  247. break
  248. if center + d < n:
  249. idx.append(center + d)
  250. if center - d < 0 and center + d >= n:
  251. break
  252. d += 1
  253. return SelectResult(idx, peak, peak_idx, (-1, -1), 0.0, True, reason)
  254. if not peak > 0.0:
  255. return _fallback('评分峰值非正,回退中心帧邻域')
  256. k_min = min(max(1, min_span), max_frames)
  257. # enough_span <= 0 表示"不提前收手":一路放宽到 ratios 的最低档,
  258. # 让连续段尽可能宽 —— 这是宽段景深扩展模式的关键。
  259. k_enough = 0 if enough_span <= 0 else min(max(1, enough_span), max_frames)
  260. best_lo, best_hi, best_area, hit_ratio = -1, -1, -1.0, 0.0
  261. for ratio in ratios:
  262. thr = ratio * peak
  263. i = 0
  264. while i < n:
  265. if not scores[i] >= thr:
  266. i += 1
  267. continue
  268. j = i
  269. area = float(scores[i])
  270. while j + 1 < n and scores[j + 1] >= thr:
  271. j += 1
  272. area += float(scores[j])
  273. span = j - i + 1
  274. if span >= k_min and area > best_area:
  275. best_area, best_lo, best_hi, hit_ratio = area, i, j, ratio
  276. i = j + 1
  277. if k_enough > 0 and best_lo >= 0 and (best_hi - best_lo + 1) >= k_enough:
  278. break
  279. if best_lo < 0:
  280. return _fallback('未找到有效对焦段')
  281. count = best_hi - best_lo + 1
  282. if count <= max_frames:
  283. idx = list(range(best_lo, best_hi + 1))
  284. else:
  285. step = (count - 1) / float(max_frames - 1) if max_frames > 1 else 0.0
  286. idx = sorted(set(best_lo + int(round(k * step)) for k in range(max_frames)))
  287. return SelectResult(idx, peak, peak_idx, (best_lo, best_hi), hit_ratio, False)
  288. def summarize_scores(scores: Sequence[float],
  289. sel: Optional['SelectResult'] = None) -> dict:
  290. """分析结果摘要(供界面展示,不参与算法)"""
  291. s = np.asarray(scores, np.float64)
  292. if s.size == 0:
  293. return {}
  294. peak = float(s.max())
  295. peak_idx = int(s.argmax())
  296. out = dict(frames=int(s.size), peak=round(peak, 4), peak_index=peak_idx,
  297. smin=round(float(s.min()), 4),
  298. median=round(float(np.median(s)), 4),
  299. mean=round(float(s.mean()), 4),
  300. std=round(float(s.std()), 4))
  301. if sel is not None and sel.indices:
  302. ratios = [float(s[i] / peak) if peak > 0 else 0.0 for i in sel.indices]
  303. out.update(count=len(sel.indices), segment=sel.segment,
  304. ratio=round(float(sel.ratio), 3), fallback=sel.fallback,
  305. span_ratio_min=round(min(ratios), 3),
  306. span_ratio_max=round(max(ratios), 3),
  307. indices=list(sel.indices))
  308. return out
  309. # ============================================================================
  310. # 四、平移配准(对应 src/m_opencv.cpp alignTranslationSLView,2.8.39 新增)
  311. # ============================================================================
  312. @dataclass
  313. class AlignResult:
  314. frames: List[np.ndarray]
  315. shifts: List[Tuple[float, float]]
  316. applied: int
  317. ref_index: int
  318. max_abs: float
  319. note: str = ''
  320. def align_translation(frames: List[np.ndarray],
  321. max_edge: int = 512,
  322. min_apply_px: float = 0.6,
  323. max_shift_px: float = 24.0,
  324. min_response: float = 0.05) -> AlignResult:
  325. """亚像素平移配准(相位相关),只解 2 自由度。
  326. 位移符号(已在合成图上验证):phaseCorrelate(ref, mov) 返回 d,
  327. 使 mov(x) ≈ ref(x - d);贴回用 M=[[1,0,dx],[0,1,dy]] + WARP_INVERSE_MAP。
  328. 参考帧 = 清晰度最高的一帧,保证观感锚点不变。
  329. """
  330. n = len(frames)
  331. shifts = [(0.0, 0.0)] * n
  332. if n < 2:
  333. return AlignResult(list(frames), shifts, 0, 0, 0.0, '帧数不足,跳过')
  334. h, w = frames[0].shape[:2]
  335. sc = max_edge / float(max(h, w)) if max(h, w) > max_edge else 1.0
  336. grays, smalls, sharp = [], [], []
  337. ref_i, best = 0, -1.0
  338. for i, f in enumerate(frames):
  339. g = _to_gray8(f)
  340. grays.append(g)
  341. s = cv2.resize(g, None, fx=sc, fy=sc, interpolation=cv2.INTER_AREA) \
  342. if sc < 0.999 else g
  343. smalls.append(s)
  344. lap = cv2.Laplacian(s, cv2.CV_32F, ksize=3)
  345. v = float(lap.std()) ** 2
  346. sharp.append(v)
  347. if v > best:
  348. best, ref_i = v, i
  349. rh, rw = smalls[ref_i].shape
  350. hann = (np.hanning(max(2, rh))[:rh, None] * np.hanning(max(2, rw))[:rw][None, :]
  351. ).astype(np.float32)
  352. ref_f = smalls[ref_i].astype(np.float32) * hann
  353. out = list(frames)
  354. applied, max_abs = 0, 0.0
  355. skipped = []
  356. for i in range(n):
  357. if i == ref_i:
  358. continue
  359. mov_f = smalls[i].astype(np.float32) * hann
  360. try:
  361. (dx_r, dy_r), resp = cv2.phaseCorrelate(ref_f, mov_f)
  362. except cv2.error:
  363. skipped.append(i)
  364. continue
  365. if not (np.isfinite(dx_r) and np.isfinite(dy_r)) or resp < min_response:
  366. skipped.append(i)
  367. continue
  368. dx, dy = dx_r / sc, dy_r / sc
  369. if abs(dx) > max_shift_px or abs(dy) > max_shift_px:
  370. skipped.append(i)
  371. continue
  372. shifts[i] = (float(dx), float(dy))
  373. max_abs = max(max_abs, abs(dx), abs(dy))
  374. if abs(dx) < min_apply_px and abs(dy) < min_apply_px:
  375. continue
  376. m = np.float32([[1, 0, dx], [0, 1, dy]])
  377. warped = cv2.warpAffine(frames[i], m, (w, h),
  378. flags=cv2.INTER_LINEAR | cv2.WARP_INVERSE_MAP,
  379. borderMode=cv2.BORDER_REFLECT_101)
  380. if warped.shape[:2] == (h, w):
  381. out[i] = warped
  382. applied += 1
  383. note = f'参考帧 idx{ref_i},重采样 {applied}/{n} 帧,最大位移 {max_abs:.2f}px'
  384. if skipped:
  385. note += f',跳过 {len(skipped)} 帧'
  386. return AlignResult(out, shifts, applied, ref_i, max_abs, note)
  387. # ============================================================================
  388. # 五、引导滤波 + GFF 融合(对应 src/slview_focus.cpp)
  389. # ============================================================================
  390. def _box(img: np.ndarray, r: int) -> np.ndarray:
  391. k = 2 * r + 1
  392. return cv2.blur(img, (k, k), borderType=cv2.BORDER_REFLECT_101)
  393. def guided_filter(guide: np.ndarray, src: np.ndarray,
  394. r: int = K_GUIDE_RADIUS, eps: float = K_GUIDE_EPS) -> np.ndarray:
  395. """slview::guidedFilter(无 ximgproc 时的等价实现)"""
  396. rr = max(1, int(r))
  397. g = guide.astype(np.float32)
  398. p = src.astype(np.float32)
  399. mean_g, mean_p = _box(g, rr), _box(p, rr)
  400. corr_gg = _box(g * g, rr)
  401. corr_gp = _box(g * p, rr)
  402. var_g = corr_gg - mean_g * mean_g
  403. cov_gp = corr_gp - mean_g * mean_p
  404. a = cov_gp / (var_g + np.float32(eps))
  405. b = mean_p - a * mean_g
  406. return _box(a, rr) * g + _box(b, rr)
  407. def compute_factor(width: int, height: int, max_pixels: int = K_DEFAULT_MAX_PIXELS) -> float:
  408. """slview::computeFactor —— 缩图比例,焦点图在缩图上算"""
  409. if width <= 0 or height <= 0:
  410. return 1.0
  411. return float(min(1.0, np.sqrt(max_pixels / float(width * height))))
  412. def guide_filter_fusion(images: List[np.ndarray], factor: float,
  413. clarity: int = K_DEFAULT_CLARITY,
  414. guide_radius: int = K_GUIDE_RADIUS,
  415. guide_eps: float = K_GUIDE_EPS,
  416. progress: Optional[Callable] = None) -> np.ndarray:
  417. """slview::guideFilterFusion —— 逐像素 one-hot 选最清晰帧 + 引导滤波平滑权重 + 归一化加权"""
  418. n = len(images)
  419. if n == 0:
  420. raise ValueError('融合输入为空')
  421. if n == 1:
  422. return images[0].copy()
  423. full = (images[0].shape[1], images[0].shape[0])
  424. cn = 1 if images[0].ndim == 2 else images[0].shape[2]
  425. if not (factor > 0.0) or factor > 1.0:
  426. factor = min(1.0, max(1e-3, factor))
  427. r = max(1, int(clarity))
  428. # stage1: 缩图 + 焦点度量
  429. mags, focals = [], []
  430. for k, im in enumerate(images):
  431. small = cv2.resize(im, None, fx=factor, fy=factor,
  432. interpolation=cv2.INTER_LINEAR) if factor < 0.999 else im
  433. m, f_ = slview_get_edge(small, r)
  434. mags.append(m)
  435. focals.append(f_)
  436. if progress:
  437. progress(k + 1, n * 3, f'焦点图 {k+1}/{n}')
  438. # stage2: 逐像素 argmax → one-hot(并列取小索引,与 cv::compare CMP_GT 一致)
  439. stack = np.stack(focals)
  440. best_idx = stack.argmax(axis=0)
  441. del stack, focals
  442. # stage3~5: 引导滤波权重 → 放大回原图 → 累加
  443. sum_s = np.zeros((full[1], full[0]), np.float32)
  444. acc = np.zeros((full[1], full[0], cn), np.float32)
  445. for k in range(n):
  446. w0 = (best_idx == k).astype(np.float32)
  447. w1 = guided_filter(mags[k], w0, guide_radius, guide_eps)
  448. mags[k] = None
  449. wf = cv2.resize(w1, full, interpolation=cv2.INTER_LINEAR)
  450. # 负权重不参与(与 C++ 的 max(0,w) 一致),保证 0<=out<=255 且分子分母同源
  451. wf = np.maximum(wf, 0.0)
  452. sum_s += wf
  453. acc += images[k].astype(np.float32) * (wf[:, :, None] if cn > 1 else wf)
  454. if progress:
  455. progress(n + k + 1, n * 3, f'权重 {k+1}/{n}')
  456. s = np.maximum(sum_s, 1e-12)
  457. if cn > 1:
  458. out = acc / s[:, :, None]
  459. else:
  460. out = acc / s
  461. bad = sum_s <= 1e-12
  462. if bad.any():
  463. src = images[0]
  464. if cn > 1:
  465. out[bad] = src[bad]
  466. else:
  467. out[bad] = src[bad]
  468. if progress:
  469. progress(n * 3, n * 3, '归一化完成')
  470. return _to_u8(out)
  471. def _to_u8(a: np.ndarray) -> np.ndarray:
  472. return np.clip(a, 0, 255).astype(np.uint8)# ============================================================================
  473. # 六、融合前置:暗帧剔除 / 坏点抑制(对应 src/m_opencv.cpp fuseAdvanced 前置)
  474. # ============================================================================
  475. def suppress_dead_pixels(img: np.ndarray) -> Tuple[np.ndarray, int]:
  476. """m_opencv.cpp suppressDeadPixels —— 单帧坏点抑制(只抬亮)"""
  477. if img.dtype != np.uint8 or img.ndim not in (2, 3):
  478. return img, 0
  479. gray = _to_gray8(img)
  480. med = cv2.medianBlur(gray, 3)
  481. diff = med.astype(np.int16) - gray.astype(np.int16)
  482. thr = np.maximum((med.astype(np.float32) * 0.45).astype(np.int16), np.int16(24))
  483. dark = (diff > thr) & (med > 24)
  484. if not dark.any():
  485. return img, 0
  486. du = dark.astype(np.uint8)
  487. cnt = cv2.boxFilter(du.astype(np.float32), -1, (3, 3), normalize=False,
  488. borderType=cv2.BORDER_CONSTANT)
  489. mask = (du > 0) & (cnt <= 4.0 * 255.0)
  490. n = int(mask.sum())
  491. if n == 0 or n > gray.size * 0.01:
  492. return img, 0
  493. mu = cv2.dilate(mask.astype(np.uint8), np.ones((3, 3), np.uint8))
  494. out = img.copy()
  495. med_img = cv2.medianBlur(img, 3)
  496. m3 = mu.astype(bool)
  497. out[m3] = med_img[m3]
  498. return out, int(mu.sum())
  499. def drop_dark_frames(labels: List[int], frames: List[np.ndarray],
  500. ratio: float = 0.55) -> Tuple[List[int], List[np.ndarray], List[int]]:
  501. """按灰度均值剔除异常暗帧(低于中位数的 ratio 倍)"""
  502. if len(frames) < 3:
  503. return labels, frames, []
  504. means = [float(_to_gray8(f).mean()) for f in frames]
  505. med = float(np.median(means))
  506. if med <= 1.0:
  507. return labels, frames, []
  508. keep_l, keep_f, dropped = [], [], []
  509. for lb, f, m in zip(labels, frames, means):
  510. if m >= ratio * med:
  511. keep_l.append(lb)
  512. keep_f.append(f)
  513. else:
  514. dropped.append(lb)
  515. if len(keep_f) < max(2, len(frames) // 2):
  516. return labels, frames, []
  517. return keep_l, keep_f, dropped
  518. # ============================================================================
  519. # 七、后处理(对应 src/m_opencv.cpp)
  520. # ============================================================================
  521. def unsharp_mask(src: np.ndarray, amount: float = 2.0, sigma: float = 3.0) -> np.ndarray:
  522. """unsharpMask:src + amount*(src - GaussianBlur(src, sigma))"""
  523. if src.size == 0:
  524. return src
  525. a = max(0.0, float(amount))
  526. s = 1.5 if sigma <= 0 else float(sigma)
  527. ksize = int(round(s * 3.0)) * 2 + 1
  528. ksize = max(3, ksize)
  529. f = src.astype(np.float32)
  530. blur = cv2.GaussianBlur(f, (ksize, ksize), s, s,
  531. borderType=cv2.BORDER_REFLECT_101)
  532. return _to_u8(f + a * (f - blur))
  533. def enhance_contrast_clahe(src: np.ndarray, clip: float = 2.0,
  534. tile: int = 8) -> np.ndarray:
  535. """enhanceContrastCLAHE:只在 Lab 的 L 通道做,避免色偏"""
  536. if src.size == 0:
  537. return src
  538. clahe = cv2.createCLAHE(clipLimit=float(clip),
  539. tileGridSize=(int(tile), int(tile)))
  540. if src.ndim == 2:
  541. return clahe.apply(src)
  542. lab = cv2.cvtColor(src, cv2.COLOR_BGR2Lab)
  543. ch = list(cv2.split(lab))
  544. ch[0] = clahe.apply(ch[0])
  545. return cv2.cvtColor(cv2.merge(ch), cv2.COLOR_Lab2BGR)
  546. def enhance_contrast_auto(src: np.ndarray, low_pct: float = 1.0,
  547. high_pct: float = 99.0) -> np.ndarray:
  548. """enhanceContrastAuto:百分位拉伸(用直方图分位点,抗孤立高光)"""
  549. if src.size == 0:
  550. return src
  551. gray = _to_gray8(src)
  552. hist = cv2.calcHist([gray], [0], None, [256], [0, 256]).ravel()
  553. total = float(hist.sum())
  554. if total < 1:
  555. return src.copy()
  556. t_lo, t_hi = total * low_pct / 100.0, total * high_pct / 100.0
  557. acc, p_lo, p_hi = 0.0, 0, 255
  558. for i in range(256):
  559. acc += hist[i]
  560. if p_lo == 0 and acc >= t_lo:
  561. p_lo = i
  562. if p_hi == 255 and acc >= t_hi:
  563. p_hi = i
  564. break
  565. if p_hi - p_lo < 2:
  566. return src.copy()
  567. span = p_hi - p_lo
  568. lut = np.zeros(256, np.uint8)
  569. for i in range(256):
  570. if i <= p_lo:
  571. v = 0
  572. elif i >= p_hi:
  573. v = 255
  574. else:
  575. v = ((i - p_lo) * 255 + span // 2) // span
  576. lut[i] = np.uint8(min(255, max(0, v)))
  577. return cv2.LUT(src, lut)
  578. def enhance_contrast_gamma(src: np.ndarray, gamma: float = 1.0,
  579. auto: bool = True) -> np.ndarray:
  580. """enhanceContrastGamma:auto=true 时按平均亮度自动求 gamma(目标 128 中灰)"""
  581. if src.size == 0:
  582. return src
  583. g = float(gamma)
  584. if auto:
  585. m = float(_to_gray8(src).mean())
  586. if m <= 1.0:
  587. g = 0.5
  588. elif m >= 254.0:
  589. g = 2.5
  590. else:
  591. g = float(np.log(m / 255.0) / np.log(128.0 / 255.0))
  592. g = min(2.5, max(0.4, g))
  593. inv = 1.0 / max(1e-6, g)
  594. lut = np.array([min(255, int(round((i / 255.0) ** inv * 255.0)))
  595. for i in range(256)], np.uint8)
  596. return cv2.LUT(src, lut)
  597. def enhance_contrast_retinex(src: np.ndarray,
  598. sigmas: Sequence[float] = (15.0, 80.0, 250.0)
  599. ) -> np.ndarray:
  600. """enhanceContrastRetinexMSR:多尺度 Retinex(慢,5MP 上明显较慢)"""
  601. if src.size == 0:
  602. return src
  603. work = src
  604. if work.ndim == 2:
  605. work = cv2.cvtColor(work, cv2.COLOR_GRAY2BGR)
  606. f = work.astype(np.float32) + 1.0
  607. log_i = np.log(f)
  608. acc = np.zeros_like(f)
  609. for s in sigmas:
  610. blur = cv2.GaussianBlur(f, (0, 0), float(s), float(s),
  611. borderType=cv2.BORDER_REFLECT_101)
  612. acc += log_i - np.log(blur + 1e-6)
  613. acc /= float(len(sigmas))
  614. # 归一到 0~255
  615. out = acc - acc.min()
  616. mx = float(out.max())
  617. if mx > 1e-6:
  618. out = out * (255.0 / mx)
  619. return _to_u8(out)
  620. CONTRAST_PIPELINES = {
  621. 0: 'CLAHE(默认,现场口径)',
  622. 1: 'Auto(百分位拉伸)',
  623. 2: 'Gamma(auto)',
  624. 3: 'Retinex MSR',
  625. 4: 'CLAHE → Auto',
  626. 5: 'Auto → Retinex',
  627. 6: 'Gamma → CLAHE',
  628. -1: '跳过对比度增强',
  629. }
  630. def enhance_contrast(src: np.ndarray, pipeline: int = 0,
  631. clahe_clip: float = 2.0, clahe_tile: int = 8,
  632. auto_low: float = 1.0, auto_high: float = 99.0,
  633. gamma: float = 1.0, gamma_auto: bool = True) -> np.ndarray:
  634. """enhanceContrast(pipeline) —— 与 C++ 的分支一一对应"""
  635. if pipeline < 0:
  636. return src
  637. if pipeline == 0:
  638. return enhance_contrast_clahe(src, clahe_clip, clahe_tile)
  639. if pipeline == 1:
  640. return enhance_contrast_auto(src, auto_low, auto_high)
  641. if pipeline == 2:
  642. return enhance_contrast_gamma(src, gamma, gamma_auto)
  643. if pipeline == 3:
  644. return enhance_contrast_retinex(src)
  645. if pipeline == 4:
  646. a = enhance_contrast_clahe(src, clahe_clip, clahe_tile)
  647. return enhance_contrast_auto(a, auto_low, auto_high)
  648. if pipeline == 5:
  649. a = enhance_contrast_auto(src, auto_low, auto_high)
  650. return enhance_contrast_retinex(a)
  651. if pipeline == 6:
  652. g = enhance_contrast_gamma(src, gamma, gamma_auto)
  653. return enhance_contrast_clahe(g, clahe_clip, clahe_tile)
  654. return src.copy()
  655. def repair_dark_spots(img: np.ndarray) -> Tuple[np.ndarray, int]:
  656. """repairDarkSpots —— 亮区黑点/黑斑修复,数学上只抬亮,不会压暗
  657. 这是"纯黑像素归零"的关键:后处理里的 USM 过冲会被 clamp 到 0,
  658. 本函数把孤立的纯黑点用 5x5 中值抬回来。
  659. """
  660. if img.dtype != np.uint8 or img.ndim not in (2, 3):
  661. return img, 0
  662. cn = 1 if img.ndim == 2 else img.shape[2]
  663. if cn not in (1, 3):
  664. return img, 0
  665. gray = img if cn == 1 else cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  666. out = img.copy()
  667. repaired = 0
  668. # ---- a) 孤立黑点 / 小暗块 ----
  669. med_g = cv2.medianBlur(gray, 5).astype(np.int16)
  670. g16 = gray.astype(np.int16)
  671. diff = med_g - g16
  672. thr = np.maximum((med_g.astype(np.float32) * 0.50).astype(np.int16), np.int16(30))
  673. dark = (diff > thr) & (med_g > 60) & (g16 <= 12)
  674. if dark.any():
  675. du = dark.astype(np.uint8)
  676. cnt = cv2.boxFilter(du.astype(np.float32), -1, (3, 3), normalize=False,
  677. borderType=cv2.BORDER_CONSTANT)
  678. mask = (du > 0) & (cnt <= 4.0)
  679. core = cv2.erode(du, cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)))
  680. if core.any():
  681. blob = cv2.dilate(core, cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)))
  682. mask = mask | ((blob > 0) & (du > 0))
  683. mu = mask.astype(np.uint8)
  684. ratio = mu.sum() / float(gray.size)
  685. if 0 < ratio <= 0.25 and mu.any():
  686. mu = cv2.dilate(mu, cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)))
  687. med_img = cv2.medianBlur(img, 5)
  688. boosted = np.maximum(out, med_img) # 只许抬亮
  689. m3 = mu.astype(bool)
  690. out[m3] = boosted[m3]
  691. repaired += int(mu.sum())
  692. # ---- b) 亮区里的成片黑洞 ----
  693. mean_big = cv2.blur(gray, (31, 31), borderType=cv2.BORDER_REFLECT_101)
  694. thr_b = (mean_big.astype(np.float32) * 0.30).astype(np.uint8)
  695. hole = (gray < thr_b) & (mean_big > 60)
  696. if hole.any():
  697. hu = hole.astype(np.uint8)
  698. line_h = cv2.morphologyEx(hu, cv2.MORPH_OPEN,
  699. cv2.getStructuringElement(cv2.MORPH_RECT, (11, 1)))
  700. line_v = cv2.morphologyEx(hu, cv2.MORPH_OPEN,
  701. cv2.getStructuringElement(cv2.MORPH_RECT, (1, 11)))
  702. line_like = cv2.bitwise_or(line_h, line_v)
  703. blob = cv2.subtract(hu, line_like)
  704. n = int(cv2.countNonZero(blob))
  705. if 0 < n <= gray.size * 0.05:
  706. floor_img = (mean_big.astype(np.float32) * 0.30).astype(np.uint8)
  707. if cn == 3:
  708. floor_img = cv2.cvtColor(floor_img, cv2.COLOR_GRAY2BGR)
  709. out = np.maximum(out, floor_img)
  710. repaired += n
  711. return out, repaired
  712. def finish_fusion_classic(src: np.ndarray, amount: float = 2.0, sigma: float = 3.0,
  713. pipeline: int = 0, clahe_clip: float = 2.0,
  714. clahe_tile: int = 8, auto_low: float = 1.0,
  715. auto_high: float = 99.0, gamma: float = 1.0,
  716. gamma_auto: bool = True,
  717. do_repair: bool = True) -> Tuple[np.ndarray, dict]:
  718. """finishFusionImageClassic:USM → enhanceContrast(pipeline) → repairDarkSpots"""
  719. if src.size == 0:
  720. return src, {}
  721. sharp = unsharp_mask(src, amount, sigma)
  722. enh = enhance_contrast(sharp, pipeline, clahe_clip, clahe_tile,
  723. auto_low, auto_high, gamma, gamma_auto)
  724. fixed = 0
  725. if do_repair:
  726. enh, fixed = repair_dark_spots(enh)
  727. return enh, dict(usm_amount=amount, usm_sigma=sigma, pipeline=pipeline,
  728. repaired=fixed)
  729. # ============================================================================
  730. # 八、参数与流水线
  731. # ============================================================================
  732. SELECT_MODE_NARROW = 'narrow'
  733. SELECT_MODE_WIDE = 'wide'
  734. SELECT_MODE_NAMES = {
  735. SELECT_MODE_NARROW: '窄段 · 单焦面(app 2.8.39 口径)',
  736. SELECT_MODE_WIDE: '宽段 · 景深扩展',
  737. }
  738. SELECT_MODE_SHORT = {
  739. SELECT_MODE_NARROW: '窄段',
  740. SELECT_MODE_WIDE: '宽段',
  741. }
  742. @dataclass
  743. class FusionParams:
  744. """全部可调参数;默认值 = app 侧 2.8.39 的实际取值"""
  745. # --- 选帧 selectFuseFrames ---
  746. # 窄段(narrow):段长到 enough_span 就收手,只挑最清晰的那个焦面 → 细节最锐、但不扩展景深
  747. # 宽段(wide) :不提前收手,一路放宽到 wide_ratio_lo,把相邻焦面也拉进来 → 景深扩展
  748. select_mode: str = SELECT_MODE_NARROW
  749. max_frames: int = 12
  750. ratio_lo: float = 0.50 # ratio 序列的下限(决定愿意放宽到多低)
  751. min_span: int = 4
  752. enough_span: int = 6
  753. wide_max_frames: int = 18 # 宽段模式下的帧数上限
  754. wide_ratio_lo: float = 0.60 # 宽段模式下的阈值下限(越低纳入越多离焦帧)
  755. # --- 配准 alignTranslationSLView ---
  756. align_enable: bool = True
  757. align_max_edge: int = 512
  758. align_min_apply_px: float = 0.6
  759. align_max_shift_px: float = 24.0
  760. align_min_response: float = 0.05
  761. # --- 融合 guideFilterFusion ---
  762. max_pixels: int = K_DEFAULT_MAX_PIXELS
  763. clarity: int = K_DEFAULT_CLARITY
  764. guide_radius: int = K_GUIDE_RADIUS
  765. guide_eps: float = K_GUIDE_EPS
  766. # --- 前置 ---
  767. drop_dark: bool = True
  768. drop_dark_ratio: float = 0.55
  769. dead_pixel: bool = True
  770. # --- 后处理 finishFusionImageClassic ---
  771. post_enable: bool = True
  772. usm_amount: float = 2.0
  773. usm_sigma: float = 3.0
  774. pipeline: int = 0
  775. clahe_clip: float = 2.0
  776. clahe_tile: int = 8
  777. auto_low: float = 1.0
  778. auto_high: float = 99.0
  779. gamma: float = 1.0
  780. gamma_auto: bool = True
  781. repair_dark: bool = True
  782. def ratios(self) -> Tuple[float, ...]:
  783. """阈值序列(从高到低)。宽段模式额外补几档低阈值,让段能一路放宽。"""
  784. base = [0.97, 0.95, 0.92, 0.90, 0.85, 0.80, 0.72, 0.65, 0.60,
  785. 0.55, 0.50, 0.45, 0.40]
  786. lo = self.wide_ratio_lo if self.is_wide() else self.ratio_lo
  787. lo = float(np.clip(lo, 0.10, 0.99))
  788. return tuple(r for r in base if r >= lo - 1e-9) or (lo,)
  789. def is_wide(self) -> bool:
  790. return self.select_mode == SELECT_MODE_WIDE
  791. def eff_max_frames(self) -> int:
  792. return max(1, self.wide_max_frames if self.is_wide() else self.max_frames)
  793. def eff_enough_span(self) -> int:
  794. """宽段模式返回 0 → 选帧不提前收手,一路放宽到 ratio 下限"""
  795. return 0 if self.is_wide() else max(1, self.enough_span)
  796. def as_dict(self) -> dict:
  797. return asdict(self)
  798. Progress = Optional[Callable[[int, int, str], None]]
  799. def analyze(video: RawVideo, clarity: int = K_DEFAULT_CLARITY,
  800. progress: Progress = None, div: int = 4) -> np.ndarray:
  801. """逐帧清晰度评分(对应 findSharpestFrameIndex 的评分环节)
  802. 评分用的就是 slview::focusScore。分辨率与 app 对齐:宽高各 1/4
  803. (app 用 decodeRawBufferToBgrSmall(…, smallSize=w/4, h/4))。
  804. """
  805. n = video.usable_frames
  806. scores = np.zeros(n, np.float64)
  807. for i in range(n):
  808. g = _to_gray8(video.bgr_at_div(i, div))
  809. scores[i] = slview_focus_score(g, clarity)
  810. if progress:
  811. progress(i + 1, n, f'评分 {i+1}/{n}')
  812. return scores
  813. @dataclass
  814. class FuseResult:
  815. fused_raw: Optional[np.ndarray] = None # 融合后、未后处理
  816. fused_final: Optional[np.ndarray] = None # 融合 + 后处理
  817. selected: List[int] = field(default_factory=list)
  818. shifts: List[Tuple[float, float]] = field(default_factory=list)
  819. log: List[str] = field(default_factory=list)
  820. post_info: dict = field(default_factory=dict)
  821. factor: float = 1.0
  822. dropped: List[int] = field(default_factory=list)
  823. repaired: int = 0
  824. select: Optional['SelectResult'] = None # 选帧详情,供界面展示
  825. mode: str = SELECT_MODE_NARROW
  826. def fuse(video: RawVideo, scores: np.ndarray, params: FusionParams,
  827. progress: Progress = None) -> FuseResult:
  828. """完整复刻 app 的 fuseRawVideoFrames + fuseAdvanced(SLView 分支)
  829. 顺序严格一致:
  830. 选帧 → 读帧 → 暗帧剔除 → 坏点抑制 → 配准 → GFF 融合 → 后处理
  831. """
  832. res = FuseResult()
  833. n_total = max(1, video.usable_frames)
  834. peak_idx = int(np.argmax(scores)) if len(scores) else 0
  835. res.mode = params.select_mode
  836. sel = select_fuse_frames(scores, peak_idx, params.eff_max_frames(),
  837. params.ratios(), params.min_span,
  838. params.eff_enough_span())
  839. res.select = sel
  840. res.selected = sel.indices
  841. res.log.append(f'选帧模式={SELECT_MODE_NAMES.get(params.select_mode, params.select_mode)}')
  842. res.log.append(f'评分峰值帧=#{peak_idx} (peak={sel.peak:.4f})')
  843. if sel.fallback:
  844. res.log.append(f'选帧回退中心邻域:{sel.note}')
  845. else:
  846. res.log.append(f'焦面段=[{sel.segment[0]},{sel.segment[1]}] '
  847. f'ratio={sel.ratio} 取 {len(sel.indices)} 帧')
  848. res.log.append(f'选中帧: {sel.indices}')
  849. if not sel.indices:
  850. res.log.append('没有可融合的帧')
  851. return res
  852. # 读帧
  853. frames = []
  854. for k, idx in enumerate(sel.indices):
  855. frames.append(video.bgr(idx))
  856. if progress:
  857. progress(k + 1, len(sel.indices) * 4, f'读帧 {k+1}/{len(sel.indices)}')
  858. labels = list(sel.indices)
  859. # 前置:暗帧剔除 + 坏点抑制
  860. if params.drop_dark:
  861. labels, frames, dropped = drop_dark_frames(labels, frames, params.drop_dark_ratio)
  862. res.dropped = dropped
  863. if dropped:
  864. res.log.append(f'剔除异常暗帧: {dropped}')
  865. if params.dead_pixel:
  866. fixed_total = 0
  867. newf = []
  868. for f in frames:
  869. ff, c = suppress_dead_pixels(f)
  870. fixed_total += c
  871. newf.append(ff)
  872. frames = newf
  873. if fixed_total:
  874. res.log.append(f'坏点抑制 {fixed_total} px')
  875. if not frames:
  876. res.log.append('前置处理后无可用帧')
  877. return res
  878. # 配准
  879. if params.align_enable and len(frames) > 1:
  880. ar = align_translation(frames, params.align_max_edge,
  881. params.align_min_apply_px,
  882. params.align_max_shift_px,
  883. params.align_min_response)
  884. frames = ar.frames
  885. res.shifts = ar.shifts
  886. res.log.append(f'配准:{ar.note}')
  887. else:
  888. res.shifts = [(0.0, 0.0)] * len(frames)
  889. res.log.append('配准:已关闭')
  890. if len(frames) == 1:
  891. res.log.append('只有 1 帧,走单帧后处理路径')
  892. if params.post_enable:
  893. img, info = finish_fusion_classic(
  894. frames[0], params.usm_amount, params.usm_sigma, params.pipeline,
  895. params.clahe_clip, params.clahe_tile, params.auto_low,
  896. params.auto_high, params.gamma, params.gamma_auto,
  897. params.repair_dark)
  898. res.post_info = info
  899. res.repaired = info.get('repaired', 0)
  900. else:
  901. img = frames[0]
  902. res.fused_raw = frames[0]
  903. res.fused_final = img
  904. return res
  905. h, w = frames[0].shape[:2]
  906. factor = compute_factor(w, h, params.max_pixels)
  907. res.factor = factor
  908. res.log.append(f'GFF 融合:{len(frames)} 帧 factor={factor:.4f} '
  909. f'clarity={params.clarity}')
  910. base = len(frames) * 4
  911. fused = guide_filter_fusion(
  912. frames, factor, params.clarity, params.guide_radius, params.guide_eps,
  913. progress=lambda a, b, msg: progress(len(frames) + a, base, msg) if progress else None)
  914. res.fused_raw = fused
  915. if params.post_enable:
  916. if progress:
  917. progress(base - 1, base, '后处理中...')
  918. img, info = finish_fusion_classic(
  919. fused, params.usm_amount, params.usm_sigma, params.pipeline,
  920. params.clahe_clip, params.clahe_tile, params.auto_low,
  921. params.auto_high, params.gamma, params.gamma_auto, params.repair_dark)
  922. res.post_info = info
  923. res.repaired = info.get('repaired', 0)
  924. res.log.append(f'后处理:USM({params.usm_amount},{params.usm_sigma}) + '
  925. f'{CONTRAST_PIPELINES.get(params.pipeline, params.pipeline)}'
  926. + (f',修复黑点 {info["repaired"]} px' if info.get('repaired') else ''))
  927. res.fused_final = img
  928. else:
  929. res.log.append('后处理:已关闭')
  930. res.fused_final = fused
  931. if progress:
  932. progress(base, base, '完成')
  933. return res
  934. def reprocess(fused_raw: np.ndarray, params: FusionParams) -> Tuple[np.ndarray, dict]:
  935. """只重跑后处理(调锐化/对比度参数时用,不必重新融合)"""
  936. if fused_raw is None or fused_raw.size == 0:
  937. return fused_raw, {}
  938. if not params.post_enable:
  939. return fused_raw, {}
  940. return finish_fusion_classic(
  941. fused_raw, params.usm_amount, params.usm_sigma, params.pipeline,
  942. params.clahe_clip, params.clahe_tile, params.auto_low,
  943. params.auto_high, params.gamma, params.gamma_auto, params.repair_dark)
  944. # ============================================================================
  945. # 九、质量指标(辅助判断,非 app 逻辑)
  946. # ============================================================================
  947. def quick_metrics(img: np.ndarray) -> dict:
  948. if img is None or img.size == 0:
  949. return {}
  950. g = _to_gray8(img)
  951. lap = cv2.Laplacian(g.astype(np.float32), cv2.CV_32F, ksize=3)
  952. pure_black = int(np.count_nonzero(g <= 12))
  953. bg = g >= 235
  954. dark = g < 170
  955. rb = 0.0
  956. if img.ndim == 3 and dark.any():
  957. b = img[:, :, 0].astype(np.float32)[dark].mean()
  958. r = img[:, :, 2].astype(np.float32)[dark].mean()
  959. rb = float(r - b)
  960. return dict(
  961. mean=round(float(g.mean()), 2),
  962. lapvar=round(float(lap.var()), 1),
  963. pure_black=pure_black,
  964. bg245=round(float(100.0 * np.count_nonzero(g >= 245) / g.size), 1),
  965. bg_std=round(float(g[bg].std()), 2) if bg.any() else 0.0,
  966. rb=round(rb, 1),
  967. )