# -*- coding: utf-8 -*- """RawvStudio 算法核心 —— 与 app 端 C++ 逐条对应 本模块是 app 侧成像链路的 Python 等价实现,供 Windows 上位机(app.py)调用。 所有函数的注释都标了对应的 C++ 文件与函数名,便于逐条核对。 对应关系: RawVideo ← src/cameramanager.cpp readRawVideoMeta / readRawVideoFrameBgr decodeRawBufferToBgr slview_get_edge ← src/slview_focus.cpp getEdge slview_focus_score ← src/slview_focus.cpp focusScore select_fuse_frames ← src/cameramanager.cpp selectFuseFrames (2.8.39) align_translation ← src/m_opencv.cpp alignTranslationSLView (2.8.39) guided_filter ← src/slview_focus.cpp guidedFilter guide_filter_fusion ← src/slview_focus.cpp guideFilterFusion suppress_dead_pixels ← src/m_opencv.cpp suppressDeadPixels unsharp_mask ← src/m_opencv.cpp unsharpMask enhance_contrast ← src/m_opencv.cpp enhanceContrast (+CLAHE/Auto/Gamma/Retinex) repair_dark_spots ← src/m_opencv.cpp repairDarkSpots finish_fusion_classic ← src/m_opencv.cpp finishFusionImageClassic 【通道顺序铁律】本项目 Bayer 必须用 COLOR_BayerXX2RGB 解码、然后当 BGR 用。 app 侧 decodeRawBufferToBgr 就是这么做的(OpenCV 的 Bayer 命名与海康相差一个 R/B)。 若误用 XX2BGR,孢子会由金褐色变成青蓝色。 """ from __future__ import annotations import os import struct from dataclasses import dataclass, field, asdict from typing import Callable, List, Optional, Sequence, Tuple import cv2 import numpy as np # ============================================================================ # 一、.rawv 读取(对应 src/cameramanager.cpp) # ============================================================================ RAW_HEADER_SIZE = 32 # kRawHeaderSize RAW_MAGIC = b'RAWV' # kRawVersion=1 RAW_VERSION = 1 # RawPixelFormat 枚举(cameramanager.cpp:82-89) PIXFMT_BGRA8 = 0 PIXFMT_BAYER_RG8 = 1 PIXFMT_BAYER_GR8 = 2 PIXFMT_BAYER_GB8 = 3 PIXFMT_BAYER_BG8 = 4 PIXFMT_YUYV = 5 PIXFMT_NAMES = { PIXFMT_BGRA8: 'BGRA8(旧格式)', PIXFMT_BAYER_RG8: 'BayerRG8', PIXFMT_BAYER_GR8: 'BayerGR8', PIXFMT_BAYER_GB8: 'BayerGB8', PIXFMT_BAYER_BG8: 'BayerBG8', PIXFMT_YUYV: 'YUYV', } # 与 decodeRawBufferToBgr 完全一致的转换码:XX2RGB 后当 BGR 用 _BAYER_CODES = { PIXFMT_BAYER_RG8: cv2.COLOR_BayerRG2RGB, PIXFMT_BAYER_GR8: cv2.COLOR_BayerGR2RGB, PIXFMT_BAYER_GB8: cv2.COLOR_BayerGB2RGB, PIXFMT_BAYER_BG8: cv2.COLOR_BayerBG2RGB, } class RawVideo: """读取 .rawv 录制文件。 文件头 32 字节(writeRawHeader,大端序无关,统一小端): magic[4]='RAWV' | ver u32 | w u32 | h u32 | stride u32 | fps u32 | frames u32 | pixfmt u32 """ def __init__(self, path: str): self.path = path with open(path, 'rb') as f: head = f.read(RAW_HEADER_SIZE) if len(head) < RAW_HEADER_SIZE or head[:4] != RAW_MAGIC: raise ValueError('不是有效的 .rawv 文件(magic 不匹配)') (self.version, self.width, self.height, self.stride, self.fps, self.frame_count, self.pixfmt) = struct.unpack('<7I', head[4:32]) self.frame_bytes = self.stride * self.height self.expected_size = RAW_HEADER_SIZE + self.frame_bytes * self.frame_count self.real_size = os.path.getsize(path) self._cache: dict = {} # ---------- 元信息 ---------- @property def pixfmt_name(self) -> str: return PIXFMT_NAMES.get(self.pixfmt, f'未知({self.pixfmt})') @property def truncated(self) -> bool: return self.real_size < self.expected_size @property def usable_frames(self) -> int: """实际可读帧数:文件被截断时按实际大小算,避免读到半帧""" if self.frame_bytes <= 0: return 0 avail = max(0, self.real_size - RAW_HEADER_SIZE) return min(self.frame_count, avail // self.frame_bytes) def info(self) -> dict: return dict(file=os.path.basename(self.path), path=self.path, width=self.width, height=self.height, stride=self.stride, fps=self.fps, frames=self.frame_count, usable=self.usable_frames, pixfmt=self.pixfmt, pixfmt_name=self.pixfmt_name, size_real=self.real_size, size_expect=self.expected_size, truncated=self.truncated) # ---------- 帧读取 ---------- def raw(self, index: int) -> np.ndarray: """读单通道原始帧(Bayer 或 BGRA 字节流),返回 (h, stride) 的 uint8""" if index < 0 or index >= self.usable_frames: raise IndexError(f'帧号 {index} 超出范围 [0, {self.usable_frames})') with open(self.path, 'rb') as f: f.seek(RAW_HEADER_SIZE + index * self.frame_bytes) buf = f.read(self.frame_bytes) arr = np.frombuffer(buf, np.uint8) return arr.reshape(self.height, self.stride)[:, :self.width] def bgr(self, index: int) -> np.ndarray: """解码为 BGR 顺序的图(与 app 同一口径,见文件头注释)""" if index in self._cache: return self._cache[index] raw = self.raw(index) if self.pixfmt == PIXFMT_BGRA8: # 旧格式:BGRA 交织,stride 为字节数 rows = self.stride // 4 rgba = raw.reshape(self.height, rows, 4)[:, :self.width // 4, :] img = cv2.cvtColor(rgba, cv2.COLOR_BGRA2BGR) elif self.pixfmt == PIXFMT_YUYV: yuyv = raw.reshape(self.height, self.width // 2, 2) img = cv2.cvtColor(yuyv, cv2.COLOR_YUV2BGR_YUYV) elif self.pixfmt in _BAYER_CODES: img = cv2.cvtColor(raw, _BAYER_CODES[self.pixfmt]) else: raise ValueError(f'不支持的像素格式 pixfmt={self.pixfmt}') if len(self._cache) > 64: # 只缓存少量,避免 5MP×N 吃满内存 self._cache.clear() self._cache[index] = img return img def bgr_at_div(self, index: int, div: int = 4) -> np.ndarray: """对应 decodeRawBufferToBgrSmall:先在单通道域 INTER_AREA 降采样,再解马赛克。 为什么这样做:Bayer 的 2x2 相位只有在"整块平均"下才能保持; 先把原图按整数倍缩小再解马赛克,等价于对 R/G/G/B 各自降采样, 结果与"全量解马赛克再缩小"几乎一致,但插值计算量降到 1/div²。 div 必须是 2 的倍数(否则相位被破坏,会出现彩色摩尔纹)。 """ div = max(2, int(div) // 2 * 2) raw = self.raw(index) if self.pixfmt in _BAYER_CODES: h, w = raw.shape sw = max(2, (w // div) & ~1) sh = max(2, (h // div) & ~1) small = cv2.resize(raw, (sw, sh), interpolation=cv2.INTER_AREA) return cv2.cvtColor(small, _BAYER_CODES[self.pixfmt]) img = self.bgr(index) h, w = img.shape[:2] return cv2.resize(img, (max(1, w // div), max(1, h // div)), interpolation=cv2.INTER_AREA) def score_size(self) -> Tuple[int, int]: """app 评分用的分辨率:宽高各 1/4(findSharpestFrameIndex 的 smallSize)""" return max(1, self.width // 4), max(1, self.height // 4) def bgr_small(self, index: int, max_edge: int = 900) -> np.ndarray: """缩小预览(播放用):解码后按长边缩放。 不用"Bayer 2x2 块抽样":那只对 GR 图案成立,其余图案会错相位产生彩色摩尔纹。 解码本身是主要开销(5MP 约 25ms),缩放只在缩略图上做,代价可忽略。 """ img = self.bgr(index) h, w = img.shape[:2] sc = min(1.0, max_edge / float(max(h, w))) if sc < 1.0: img = cv2.resize(img, None, fx=sc, fy=sc, interpolation=cv2.INTER_AREA) return img # ============================================================================ # 二、SLView 焦点度量(对应 src/slview_focus.cpp) # ============================================================================ K_LOG_SCALE = 150.0 / np.log(256.0) # kLogScale ≈ 27.0505 K_GUIDE_EPS = 0.065025 # kGuideEps = (0.001*255)^2 K_GUIDE_RADIUS = 5 # kGuideRadius K_FOCUS_BLUR = 9 # kFocusBlur K_SOBEL_KSIZE = 1 # kSobelKsize K_DEFAULT_CLARITY = 5 # kDefaultClarity K_DEFAULT_MAX_PIXELS = 1280 * 720 # kDefaultMaxPixels def _to_gray8(src: np.ndarray) -> np.ndarray: if src.ndim == 2: return src if src.shape[2] == 3: return cv2.cvtColor(src, cv2.COLOR_BGR2GRAY) if src.shape[2] == 4: return cv2.cvtColor(src, cv2.COLOR_BGRA2GRAY) raise ValueError('slview::getEdge: 不支持的通道数') def slview_get_edge(src: np.ndarray, radius: int = K_DEFAULT_CLARITY ) -> Tuple[np.ndarray, np.ndarray]: """slview::getEdge —— 返回 (mag, focus) gray → log(I+1)*150/ln256 → Sobel(ksize=1) 的 L1 幅值 → dilate((2r+1)²) 局部最大 → GaussianBlur(9x9) """ gray = _to_gray8(src).astype(np.float32) mag = np.log(gray + 1.0, dtype=np.float32) * np.float32(K_LOG_SCALE) # ksize=1 的 Sobel 就是无平滑的 [-1,0,1]。用 filter2D 显式构造, # 与 C++ 的 cv::Sobel(..., ksize=1) 完全等价(避免 OpenCV 对 float 输入的限制)。 kx = np.array([[-1.0, 0.0, 1.0]], np.float32) # 1x3 水平差分 ky = kx.T.copy() # 3x1 垂直差分 gx = cv2.filter2D(mag, -1, kx, borderType=cv2.BORDER_REFLECT_101) gy = cv2.filter2D(mag, -1, ky, borderType=cv2.BORDER_REFLECT_101) mag = np.abs(gx) + np.abs(gy) r = max(0, int(radius)) if r > 0: k = 2 * r + 1 kern = cv2.getStructuringElement(cv2.MORPH_RECT, (k, k)) focus = cv2.dilate(mag, kern, borderType=cv2.BORDER_CONSTANT, borderValue=0) else: focus = mag.copy() focus = cv2.GaussianBlur(focus, (K_FOCUS_BLUR, K_FOCUS_BLUR), 0, 0, borderType=cv2.BORDER_REFLECT_101) return mag, focus def slview_focus_score(src: np.ndarray, radius: int = K_DEFAULT_CLARITY) -> float: """slview::focusScore —— 焦点图均值(用它圈定焦面区间)""" if src is None or src.size == 0: return 0.0 _, focus = slview_get_edge(src, radius) return float(focus.mean()) # ============================================================================ # 三、选帧(对应 src/cameramanager.cpp selectFuseFrames,2.8.39 新实现) # ============================================================================ @dataclass class SelectResult: indices: List[int] peak: float peak_index: int segment: Tuple[int, int] ratio: float fallback: bool note: str = '' def select_fuse_frames(scores: Sequence[float], center: int, max_frames: int = 12, ratios: Sequence[float] = (0.97, 0.95, 0.92, 0.90, 0.85, 0.80, 0.72, 0.62, 0.50), min_span: int = 4, enough_span: int = 6) -> SelectResult: """选帧:在"评分 ≥ ratio×峰值"的连续段里取 Σscore 最大的一段。 为什么不用"围绕 argmax 取邻域":录制末端常有同焦面的重复帧, 它会把评分峰值顶到末尾,导致"清晰帧 + 一堆离焦帧"被一起融合。 段积分天然抑制这种孤立尖刺。 """ n = len(scores) if n == 0 or center < 0 or center >= n or max_frames <= 0: return SelectResult([], 0.0, center, (-1, -1), 0.0, True, '参数非法') peak = float(max(scores)) peak_idx = int(np.argmax(np.asarray(scores))) def _fallback(reason: str) -> SelectResult: idx, d = [center], 1 while len(idx) < max_frames: if center - d >= 0: idx.append(center - d) if len(idx) >= max_frames: break if center + d < n: idx.append(center + d) if center - d < 0 and center + d >= n: break d += 1 return SelectResult(idx, peak, peak_idx, (-1, -1), 0.0, True, reason) if not peak > 0.0: return _fallback('评分峰值非正,回退中心帧邻域') k_min = min(max(1, min_span), max_frames) # enough_span <= 0 表示"不提前收手":一路放宽到 ratios 的最低档, # 让连续段尽可能宽 —— 这是宽段景深扩展模式的关键。 k_enough = 0 if enough_span <= 0 else min(max(1, enough_span), max_frames) best_lo, best_hi, best_area, hit_ratio = -1, -1, -1.0, 0.0 for ratio in ratios: thr = ratio * peak i = 0 while i < n: if not scores[i] >= thr: i += 1 continue j = i area = float(scores[i]) while j + 1 < n and scores[j + 1] >= thr: j += 1 area += float(scores[j]) span = j - i + 1 if span >= k_min and area > best_area: best_area, best_lo, best_hi, hit_ratio = area, i, j, ratio i = j + 1 if k_enough > 0 and best_lo >= 0 and (best_hi - best_lo + 1) >= k_enough: break if best_lo < 0: return _fallback('未找到有效对焦段') count = best_hi - best_lo + 1 if count <= max_frames: idx = list(range(best_lo, best_hi + 1)) else: step = (count - 1) / float(max_frames - 1) if max_frames > 1 else 0.0 idx = sorted(set(best_lo + int(round(k * step)) for k in range(max_frames))) return SelectResult(idx, peak, peak_idx, (best_lo, best_hi), hit_ratio, False) def summarize_scores(scores: Sequence[float], sel: Optional['SelectResult'] = None) -> dict: """分析结果摘要(供界面展示,不参与算法)""" s = np.asarray(scores, np.float64) if s.size == 0: return {} peak = float(s.max()) peak_idx = int(s.argmax()) out = dict(frames=int(s.size), peak=round(peak, 4), peak_index=peak_idx, smin=round(float(s.min()), 4), median=round(float(np.median(s)), 4), mean=round(float(s.mean()), 4), std=round(float(s.std()), 4)) if sel is not None and sel.indices: ratios = [float(s[i] / peak) if peak > 0 else 0.0 for i in sel.indices] out.update(count=len(sel.indices), segment=sel.segment, ratio=round(float(sel.ratio), 3), fallback=sel.fallback, span_ratio_min=round(min(ratios), 3), span_ratio_max=round(max(ratios), 3), indices=list(sel.indices)) return out # ============================================================================ # 四、平移配准(对应 src/m_opencv.cpp alignTranslationSLView,2.8.39 新增) # ============================================================================ @dataclass class AlignResult: frames: List[np.ndarray] shifts: List[Tuple[float, float]] applied: int ref_index: int max_abs: float note: str = '' def align_translation(frames: List[np.ndarray], max_edge: int = 512, min_apply_px: float = 0.6, max_shift_px: float = 24.0, min_response: float = 0.05) -> AlignResult: """亚像素平移配准(相位相关),只解 2 自由度。 位移符号(已在合成图上验证):phaseCorrelate(ref, mov) 返回 d, 使 mov(x) ≈ ref(x - d);贴回用 M=[[1,0,dx],[0,1,dy]] + WARP_INVERSE_MAP。 参考帧 = 清晰度最高的一帧,保证观感锚点不变。 """ n = len(frames) shifts = [(0.0, 0.0)] * n if n < 2: return AlignResult(list(frames), shifts, 0, 0, 0.0, '帧数不足,跳过') h, w = frames[0].shape[:2] sc = max_edge / float(max(h, w)) if max(h, w) > max_edge else 1.0 grays, smalls, sharp = [], [], [] ref_i, best = 0, -1.0 for i, f in enumerate(frames): g = _to_gray8(f) grays.append(g) s = cv2.resize(g, None, fx=sc, fy=sc, interpolation=cv2.INTER_AREA) \ if sc < 0.999 else g smalls.append(s) lap = cv2.Laplacian(s, cv2.CV_32F, ksize=3) v = float(lap.std()) ** 2 sharp.append(v) if v > best: best, ref_i = v, i rh, rw = smalls[ref_i].shape hann = (np.hanning(max(2, rh))[:rh, None] * np.hanning(max(2, rw))[:rw][None, :] ).astype(np.float32) ref_f = smalls[ref_i].astype(np.float32) * hann out = list(frames) applied, max_abs = 0, 0.0 skipped = [] for i in range(n): if i == ref_i: continue mov_f = smalls[i].astype(np.float32) * hann try: (dx_r, dy_r), resp = cv2.phaseCorrelate(ref_f, mov_f) except cv2.error: skipped.append(i) continue if not (np.isfinite(dx_r) and np.isfinite(dy_r)) or resp < min_response: skipped.append(i) continue dx, dy = dx_r / sc, dy_r / sc if abs(dx) > max_shift_px or abs(dy) > max_shift_px: skipped.append(i) continue shifts[i] = (float(dx), float(dy)) max_abs = max(max_abs, abs(dx), abs(dy)) if abs(dx) < min_apply_px and abs(dy) < min_apply_px: continue m = np.float32([[1, 0, dx], [0, 1, dy]]) warped = cv2.warpAffine(frames[i], m, (w, h), flags=cv2.INTER_LINEAR | cv2.WARP_INVERSE_MAP, borderMode=cv2.BORDER_REFLECT_101) if warped.shape[:2] == (h, w): out[i] = warped applied += 1 note = f'参考帧 idx{ref_i},重采样 {applied}/{n} 帧,最大位移 {max_abs:.2f}px' if skipped: note += f',跳过 {len(skipped)} 帧' return AlignResult(out, shifts, applied, ref_i, max_abs, note) # ============================================================================ # 五、引导滤波 + GFF 融合(对应 src/slview_focus.cpp) # ============================================================================ def _box(img: np.ndarray, r: int) -> np.ndarray: k = 2 * r + 1 return cv2.blur(img, (k, k), borderType=cv2.BORDER_REFLECT_101) def guided_filter(guide: np.ndarray, src: np.ndarray, r: int = K_GUIDE_RADIUS, eps: float = K_GUIDE_EPS) -> np.ndarray: """slview::guidedFilter(无 ximgproc 时的等价实现)""" rr = max(1, int(r)) g = guide.astype(np.float32) p = src.astype(np.float32) mean_g, mean_p = _box(g, rr), _box(p, rr) corr_gg = _box(g * g, rr) corr_gp = _box(g * p, rr) var_g = corr_gg - mean_g * mean_g cov_gp = corr_gp - mean_g * mean_p a = cov_gp / (var_g + np.float32(eps)) b = mean_p - a * mean_g return _box(a, rr) * g + _box(b, rr) def compute_factor(width: int, height: int, max_pixels: int = K_DEFAULT_MAX_PIXELS) -> float: """slview::computeFactor —— 缩图比例,焦点图在缩图上算""" if width <= 0 or height <= 0: return 1.0 return float(min(1.0, np.sqrt(max_pixels / float(width * height)))) def guide_filter_fusion(images: List[np.ndarray], factor: float, clarity: int = K_DEFAULT_CLARITY, guide_radius: int = K_GUIDE_RADIUS, guide_eps: float = K_GUIDE_EPS, progress: Optional[Callable] = None) -> np.ndarray: """slview::guideFilterFusion —— 逐像素 one-hot 选最清晰帧 + 引导滤波平滑权重 + 归一化加权""" n = len(images) if n == 0: raise ValueError('融合输入为空') if n == 1: return images[0].copy() full = (images[0].shape[1], images[0].shape[0]) cn = 1 if images[0].ndim == 2 else images[0].shape[2] if not (factor > 0.0) or factor > 1.0: factor = min(1.0, max(1e-3, factor)) r = max(1, int(clarity)) # stage1: 缩图 + 焦点度量 mags, focals = [], [] for k, im in enumerate(images): small = cv2.resize(im, None, fx=factor, fy=factor, interpolation=cv2.INTER_LINEAR) if factor < 0.999 else im m, f_ = slview_get_edge(small, r) mags.append(m) focals.append(f_) if progress: progress(k + 1, n * 3, f'焦点图 {k+1}/{n}') # stage2: 逐像素 argmax → one-hot(并列取小索引,与 cv::compare CMP_GT 一致) stack = np.stack(focals) best_idx = stack.argmax(axis=0) del stack, focals # stage3~5: 引导滤波权重 → 放大回原图 → 累加 sum_s = np.zeros((full[1], full[0]), np.float32) acc = np.zeros((full[1], full[0], cn), np.float32) for k in range(n): w0 = (best_idx == k).astype(np.float32) w1 = guided_filter(mags[k], w0, guide_radius, guide_eps) mags[k] = None wf = cv2.resize(w1, full, interpolation=cv2.INTER_LINEAR) # 负权重不参与(与 C++ 的 max(0,w) 一致),保证 0<=out<=255 且分子分母同源 wf = np.maximum(wf, 0.0) sum_s += wf acc += images[k].astype(np.float32) * (wf[:, :, None] if cn > 1 else wf) if progress: progress(n + k + 1, n * 3, f'权重 {k+1}/{n}') s = np.maximum(sum_s, 1e-12) if cn > 1: out = acc / s[:, :, None] else: out = acc / s bad = sum_s <= 1e-12 if bad.any(): src = images[0] if cn > 1: out[bad] = src[bad] else: out[bad] = src[bad] if progress: progress(n * 3, n * 3, '归一化完成') return _to_u8(out) def _to_u8(a: np.ndarray) -> np.ndarray: return np.clip(a, 0, 255).astype(np.uint8)# ============================================================================ # 六、融合前置:暗帧剔除 / 坏点抑制(对应 src/m_opencv.cpp fuseAdvanced 前置) # ============================================================================ def suppress_dead_pixels(img: np.ndarray) -> Tuple[np.ndarray, int]: """m_opencv.cpp suppressDeadPixels —— 单帧坏点抑制(只抬亮)""" if img.dtype != np.uint8 or img.ndim not in (2, 3): return img, 0 gray = _to_gray8(img) med = cv2.medianBlur(gray, 3) diff = med.astype(np.int16) - gray.astype(np.int16) thr = np.maximum((med.astype(np.float32) * 0.45).astype(np.int16), np.int16(24)) dark = (diff > thr) & (med > 24) if not dark.any(): return img, 0 du = dark.astype(np.uint8) cnt = cv2.boxFilter(du.astype(np.float32), -1, (3, 3), normalize=False, borderType=cv2.BORDER_CONSTANT) mask = (du > 0) & (cnt <= 4.0 * 255.0) n = int(mask.sum()) if n == 0 or n > gray.size * 0.01: return img, 0 mu = cv2.dilate(mask.astype(np.uint8), np.ones((3, 3), np.uint8)) out = img.copy() med_img = cv2.medianBlur(img, 3) m3 = mu.astype(bool) out[m3] = med_img[m3] return out, int(mu.sum()) def drop_dark_frames(labels: List[int], frames: List[np.ndarray], ratio: float = 0.55) -> Tuple[List[int], List[np.ndarray], List[int]]: """按灰度均值剔除异常暗帧(低于中位数的 ratio 倍)""" if len(frames) < 3: return labels, frames, [] means = [float(_to_gray8(f).mean()) for f in frames] med = float(np.median(means)) if med <= 1.0: return labels, frames, [] keep_l, keep_f, dropped = [], [], [] for lb, f, m in zip(labels, frames, means): if m >= ratio * med: keep_l.append(lb) keep_f.append(f) else: dropped.append(lb) if len(keep_f) < max(2, len(frames) // 2): return labels, frames, [] return keep_l, keep_f, dropped # ============================================================================ # 七、后处理(对应 src/m_opencv.cpp) # ============================================================================ def unsharp_mask(src: np.ndarray, amount: float = 2.0, sigma: float = 3.0) -> np.ndarray: """unsharpMask:src + amount*(src - GaussianBlur(src, sigma))""" if src.size == 0: return src a = max(0.0, float(amount)) s = 1.5 if sigma <= 0 else float(sigma) ksize = int(round(s * 3.0)) * 2 + 1 ksize = max(3, ksize) f = src.astype(np.float32) blur = cv2.GaussianBlur(f, (ksize, ksize), s, s, borderType=cv2.BORDER_REFLECT_101) return _to_u8(f + a * (f - blur)) def enhance_contrast_clahe(src: np.ndarray, clip: float = 2.0, tile: int = 8) -> np.ndarray: """enhanceContrastCLAHE:只在 Lab 的 L 通道做,避免色偏""" if src.size == 0: return src clahe = cv2.createCLAHE(clipLimit=float(clip), tileGridSize=(int(tile), int(tile))) if src.ndim == 2: return clahe.apply(src) lab = cv2.cvtColor(src, cv2.COLOR_BGR2Lab) ch = list(cv2.split(lab)) ch[0] = clahe.apply(ch[0]) return cv2.cvtColor(cv2.merge(ch), cv2.COLOR_Lab2BGR) def enhance_contrast_auto(src: np.ndarray, low_pct: float = 1.0, high_pct: float = 99.0) -> np.ndarray: """enhanceContrastAuto:百分位拉伸(用直方图分位点,抗孤立高光)""" if src.size == 0: return src gray = _to_gray8(src) hist = cv2.calcHist([gray], [0], None, [256], [0, 256]).ravel() total = float(hist.sum()) if total < 1: return src.copy() t_lo, t_hi = total * low_pct / 100.0, total * high_pct / 100.0 acc, p_lo, p_hi = 0.0, 0, 255 for i in range(256): acc += hist[i] if p_lo == 0 and acc >= t_lo: p_lo = i if p_hi == 255 and acc >= t_hi: p_hi = i break if p_hi - p_lo < 2: return src.copy() span = p_hi - p_lo lut = np.zeros(256, np.uint8) for i in range(256): if i <= p_lo: v = 0 elif i >= p_hi: v = 255 else: v = ((i - p_lo) * 255 + span // 2) // span lut[i] = np.uint8(min(255, max(0, v))) return cv2.LUT(src, lut) def enhance_contrast_gamma(src: np.ndarray, gamma: float = 1.0, auto: bool = True) -> np.ndarray: """enhanceContrastGamma:auto=true 时按平均亮度自动求 gamma(目标 128 中灰)""" if src.size == 0: return src g = float(gamma) if auto: m = float(_to_gray8(src).mean()) if m <= 1.0: g = 0.5 elif m >= 254.0: g = 2.5 else: g = float(np.log(m / 255.0) / np.log(128.0 / 255.0)) g = min(2.5, max(0.4, g)) inv = 1.0 / max(1e-6, g) lut = np.array([min(255, int(round((i / 255.0) ** inv * 255.0))) for i in range(256)], np.uint8) return cv2.LUT(src, lut) def enhance_contrast_retinex(src: np.ndarray, sigmas: Sequence[float] = (15.0, 80.0, 250.0) ) -> np.ndarray: """enhanceContrastRetinexMSR:多尺度 Retinex(慢,5MP 上明显较慢)""" if src.size == 0: return src work = src if work.ndim == 2: work = cv2.cvtColor(work, cv2.COLOR_GRAY2BGR) f = work.astype(np.float32) + 1.0 log_i = np.log(f) acc = np.zeros_like(f) for s in sigmas: blur = cv2.GaussianBlur(f, (0, 0), float(s), float(s), borderType=cv2.BORDER_REFLECT_101) acc += log_i - np.log(blur + 1e-6) acc /= float(len(sigmas)) # 归一到 0~255 out = acc - acc.min() mx = float(out.max()) if mx > 1e-6: out = out * (255.0 / mx) return _to_u8(out) CONTRAST_PIPELINES = { 0: 'CLAHE(默认,现场口径)', 1: 'Auto(百分位拉伸)', 2: 'Gamma(auto)', 3: 'Retinex MSR', 4: 'CLAHE → Auto', 5: 'Auto → Retinex', 6: 'Gamma → CLAHE', -1: '跳过对比度增强', } def enhance_contrast(src: np.ndarray, pipeline: int = 0, clahe_clip: float = 2.0, clahe_tile: int = 8, auto_low: float = 1.0, auto_high: float = 99.0, gamma: float = 1.0, gamma_auto: bool = True) -> np.ndarray: """enhanceContrast(pipeline) —— 与 C++ 的分支一一对应""" if pipeline < 0: return src if pipeline == 0: return enhance_contrast_clahe(src, clahe_clip, clahe_tile) if pipeline == 1: return enhance_contrast_auto(src, auto_low, auto_high) if pipeline == 2: return enhance_contrast_gamma(src, gamma, gamma_auto) if pipeline == 3: return enhance_contrast_retinex(src) if pipeline == 4: a = enhance_contrast_clahe(src, clahe_clip, clahe_tile) return enhance_contrast_auto(a, auto_low, auto_high) if pipeline == 5: a = enhance_contrast_auto(src, auto_low, auto_high) return enhance_contrast_retinex(a) if pipeline == 6: g = enhance_contrast_gamma(src, gamma, gamma_auto) return enhance_contrast_clahe(g, clahe_clip, clahe_tile) return src.copy() def repair_dark_spots(img: np.ndarray) -> Tuple[np.ndarray, int]: """repairDarkSpots —— 亮区黑点/黑斑修复,数学上只抬亮,不会压暗 这是"纯黑像素归零"的关键:后处理里的 USM 过冲会被 clamp 到 0, 本函数把孤立的纯黑点用 5x5 中值抬回来。 """ if img.dtype != np.uint8 or img.ndim not in (2, 3): return img, 0 cn = 1 if img.ndim == 2 else img.shape[2] if cn not in (1, 3): return img, 0 gray = img if cn == 1 else cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) out = img.copy() repaired = 0 # ---- a) 孤立黑点 / 小暗块 ---- med_g = cv2.medianBlur(gray, 5).astype(np.int16) g16 = gray.astype(np.int16) diff = med_g - g16 thr = np.maximum((med_g.astype(np.float32) * 0.50).astype(np.int16), np.int16(30)) dark = (diff > thr) & (med_g > 60) & (g16 <= 12) if dark.any(): du = dark.astype(np.uint8) cnt = cv2.boxFilter(du.astype(np.float32), -1, (3, 3), normalize=False, borderType=cv2.BORDER_CONSTANT) mask = (du > 0) & (cnt <= 4.0) core = cv2.erode(du, cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))) if core.any(): blob = cv2.dilate(core, cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))) mask = mask | ((blob > 0) & (du > 0)) mu = mask.astype(np.uint8) ratio = mu.sum() / float(gray.size) if 0 < ratio <= 0.25 and mu.any(): mu = cv2.dilate(mu, cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))) med_img = cv2.medianBlur(img, 5) boosted = np.maximum(out, med_img) # 只许抬亮 m3 = mu.astype(bool) out[m3] = boosted[m3] repaired += int(mu.sum()) # ---- b) 亮区里的成片黑洞 ---- mean_big = cv2.blur(gray, (31, 31), borderType=cv2.BORDER_REFLECT_101) thr_b = (mean_big.astype(np.float32) * 0.30).astype(np.uint8) hole = (gray < thr_b) & (mean_big > 60) if hole.any(): hu = hole.astype(np.uint8) line_h = cv2.morphologyEx(hu, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_RECT, (11, 1))) line_v = cv2.morphologyEx(hu, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_RECT, (1, 11))) line_like = cv2.bitwise_or(line_h, line_v) blob = cv2.subtract(hu, line_like) n = int(cv2.countNonZero(blob)) if 0 < n <= gray.size * 0.05: floor_img = (mean_big.astype(np.float32) * 0.30).astype(np.uint8) if cn == 3: floor_img = cv2.cvtColor(floor_img, cv2.COLOR_GRAY2BGR) out = np.maximum(out, floor_img) repaired += n return out, repaired def finish_fusion_classic(src: np.ndarray, amount: float = 2.0, sigma: float = 3.0, pipeline: int = 0, clahe_clip: float = 2.0, clahe_tile: int = 8, auto_low: float = 1.0, auto_high: float = 99.0, gamma: float = 1.0, gamma_auto: bool = True, do_repair: bool = True) -> Tuple[np.ndarray, dict]: """finishFusionImageClassic:USM → enhanceContrast(pipeline) → repairDarkSpots""" if src.size == 0: return src, {} sharp = unsharp_mask(src, amount, sigma) enh = enhance_contrast(sharp, pipeline, clahe_clip, clahe_tile, auto_low, auto_high, gamma, gamma_auto) fixed = 0 if do_repair: enh, fixed = repair_dark_spots(enh) return enh, dict(usm_amount=amount, usm_sigma=sigma, pipeline=pipeline, repaired=fixed) # ============================================================================ # 八、参数与流水线 # ============================================================================ SELECT_MODE_NARROW = 'narrow' SELECT_MODE_WIDE = 'wide' SELECT_MODE_NAMES = { SELECT_MODE_NARROW: '窄段 · 单焦面(app 2.8.39 口径)', SELECT_MODE_WIDE: '宽段 · 景深扩展', } SELECT_MODE_SHORT = { SELECT_MODE_NARROW: '窄段', SELECT_MODE_WIDE: '宽段', } @dataclass class FusionParams: """全部可调参数;默认值 = app 侧 2.8.39 的实际取值""" # --- 选帧 selectFuseFrames --- # 窄段(narrow):段长到 enough_span 就收手,只挑最清晰的那个焦面 → 细节最锐、但不扩展景深 # 宽段(wide) :不提前收手,一路放宽到 wide_ratio_lo,把相邻焦面也拉进来 → 景深扩展 select_mode: str = SELECT_MODE_NARROW max_frames: int = 12 ratio_lo: float = 0.50 # ratio 序列的下限(决定愿意放宽到多低) min_span: int = 4 enough_span: int = 6 wide_max_frames: int = 18 # 宽段模式下的帧数上限 wide_ratio_lo: float = 0.60 # 宽段模式下的阈值下限(越低纳入越多离焦帧) # --- 配准 alignTranslationSLView --- align_enable: bool = True align_max_edge: int = 512 align_min_apply_px: float = 0.6 align_max_shift_px: float = 24.0 align_min_response: float = 0.05 # --- 融合 guideFilterFusion --- max_pixels: int = K_DEFAULT_MAX_PIXELS clarity: int = K_DEFAULT_CLARITY guide_radius: int = K_GUIDE_RADIUS guide_eps: float = K_GUIDE_EPS # --- 前置 --- drop_dark: bool = True drop_dark_ratio: float = 0.55 dead_pixel: bool = True # --- 后处理 finishFusionImageClassic --- post_enable: bool = True usm_amount: float = 2.0 usm_sigma: float = 3.0 pipeline: int = 0 clahe_clip: float = 2.0 clahe_tile: int = 8 auto_low: float = 1.0 auto_high: float = 99.0 gamma: float = 1.0 gamma_auto: bool = True repair_dark: bool = True def ratios(self) -> Tuple[float, ...]: """阈值序列(从高到低)。宽段模式额外补几档低阈值,让段能一路放宽。""" base = [0.97, 0.95, 0.92, 0.90, 0.85, 0.80, 0.72, 0.65, 0.60, 0.55, 0.50, 0.45, 0.40] lo = self.wide_ratio_lo if self.is_wide() else self.ratio_lo lo = float(np.clip(lo, 0.10, 0.99)) return tuple(r for r in base if r >= lo - 1e-9) or (lo,) def is_wide(self) -> bool: return self.select_mode == SELECT_MODE_WIDE def eff_max_frames(self) -> int: return max(1, self.wide_max_frames if self.is_wide() else self.max_frames) def eff_enough_span(self) -> int: """宽段模式返回 0 → 选帧不提前收手,一路放宽到 ratio 下限""" return 0 if self.is_wide() else max(1, self.enough_span) def as_dict(self) -> dict: return asdict(self) Progress = Optional[Callable[[int, int, str], None]] def analyze(video: RawVideo, clarity: int = K_DEFAULT_CLARITY, progress: Progress = None, div: int = 4) -> np.ndarray: """逐帧清晰度评分(对应 findSharpestFrameIndex 的评分环节) 评分用的就是 slview::focusScore。分辨率与 app 对齐:宽高各 1/4 (app 用 decodeRawBufferToBgrSmall(…, smallSize=w/4, h/4))。 """ n = video.usable_frames scores = np.zeros(n, np.float64) for i in range(n): g = _to_gray8(video.bgr_at_div(i, div)) scores[i] = slview_focus_score(g, clarity) if progress: progress(i + 1, n, f'评分 {i+1}/{n}') return scores @dataclass class FuseResult: fused_raw: Optional[np.ndarray] = None # 融合后、未后处理 fused_final: Optional[np.ndarray] = None # 融合 + 后处理 selected: List[int] = field(default_factory=list) shifts: List[Tuple[float, float]] = field(default_factory=list) log: List[str] = field(default_factory=list) post_info: dict = field(default_factory=dict) factor: float = 1.0 dropped: List[int] = field(default_factory=list) repaired: int = 0 select: Optional['SelectResult'] = None # 选帧详情,供界面展示 mode: str = SELECT_MODE_NARROW def fuse(video: RawVideo, scores: np.ndarray, params: FusionParams, progress: Progress = None) -> FuseResult: """完整复刻 app 的 fuseRawVideoFrames + fuseAdvanced(SLView 分支) 顺序严格一致: 选帧 → 读帧 → 暗帧剔除 → 坏点抑制 → 配准 → GFF 融合 → 后处理 """ res = FuseResult() n_total = max(1, video.usable_frames) peak_idx = int(np.argmax(scores)) if len(scores) else 0 res.mode = params.select_mode sel = select_fuse_frames(scores, peak_idx, params.eff_max_frames(), params.ratios(), params.min_span, params.eff_enough_span()) res.select = sel res.selected = sel.indices res.log.append(f'选帧模式={SELECT_MODE_NAMES.get(params.select_mode, params.select_mode)}') res.log.append(f'评分峰值帧=#{peak_idx} (peak={sel.peak:.4f})') if sel.fallback: res.log.append(f'选帧回退中心邻域:{sel.note}') else: res.log.append(f'焦面段=[{sel.segment[0]},{sel.segment[1]}] ' f'ratio={sel.ratio} 取 {len(sel.indices)} 帧') res.log.append(f'选中帧: {sel.indices}') if not sel.indices: res.log.append('没有可融合的帧') return res # 读帧 frames = [] for k, idx in enumerate(sel.indices): frames.append(video.bgr(idx)) if progress: progress(k + 1, len(sel.indices) * 4, f'读帧 {k+1}/{len(sel.indices)}') labels = list(sel.indices) # 前置:暗帧剔除 + 坏点抑制 if params.drop_dark: labels, frames, dropped = drop_dark_frames(labels, frames, params.drop_dark_ratio) res.dropped = dropped if dropped: res.log.append(f'剔除异常暗帧: {dropped}') if params.dead_pixel: fixed_total = 0 newf = [] for f in frames: ff, c = suppress_dead_pixels(f) fixed_total += c newf.append(ff) frames = newf if fixed_total: res.log.append(f'坏点抑制 {fixed_total} px') if not frames: res.log.append('前置处理后无可用帧') return res # 配准 if params.align_enable and len(frames) > 1: ar = align_translation(frames, params.align_max_edge, params.align_min_apply_px, params.align_max_shift_px, params.align_min_response) frames = ar.frames res.shifts = ar.shifts res.log.append(f'配准:{ar.note}') else: res.shifts = [(0.0, 0.0)] * len(frames) res.log.append('配准:已关闭') if len(frames) == 1: res.log.append('只有 1 帧,走单帧后处理路径') if params.post_enable: img, info = finish_fusion_classic( frames[0], params.usm_amount, params.usm_sigma, params.pipeline, params.clahe_clip, params.clahe_tile, params.auto_low, params.auto_high, params.gamma, params.gamma_auto, params.repair_dark) res.post_info = info res.repaired = info.get('repaired', 0) else: img = frames[0] res.fused_raw = frames[0] res.fused_final = img return res h, w = frames[0].shape[:2] factor = compute_factor(w, h, params.max_pixels) res.factor = factor res.log.append(f'GFF 融合:{len(frames)} 帧 factor={factor:.4f} ' f'clarity={params.clarity}') base = len(frames) * 4 fused = guide_filter_fusion( frames, factor, params.clarity, params.guide_radius, params.guide_eps, progress=lambda a, b, msg: progress(len(frames) + a, base, msg) if progress else None) res.fused_raw = fused if params.post_enable: if progress: progress(base - 1, base, '后处理中...') img, info = finish_fusion_classic( fused, params.usm_amount, params.usm_sigma, params.pipeline, params.clahe_clip, params.clahe_tile, params.auto_low, params.auto_high, params.gamma, params.gamma_auto, params.repair_dark) res.post_info = info res.repaired = info.get('repaired', 0) res.log.append(f'后处理:USM({params.usm_amount},{params.usm_sigma}) + ' f'{CONTRAST_PIPELINES.get(params.pipeline, params.pipeline)}' + (f',修复黑点 {info["repaired"]} px' if info.get('repaired') else '')) res.fused_final = img else: res.log.append('后处理:已关闭') res.fused_final = fused if progress: progress(base, base, '完成') return res def reprocess(fused_raw: np.ndarray, params: FusionParams) -> Tuple[np.ndarray, dict]: """只重跑后处理(调锐化/对比度参数时用,不必重新融合)""" if fused_raw is None or fused_raw.size == 0: return fused_raw, {} if not params.post_enable: return fused_raw, {} return finish_fusion_classic( fused_raw, params.usm_amount, params.usm_sigma, params.pipeline, params.clahe_clip, params.clahe_tile, params.auto_low, params.auto_high, params.gamma, params.gamma_auto, params.repair_dark) # ============================================================================ # 九、质量指标(辅助判断,非 app 逻辑) # ============================================================================ def quick_metrics(img: np.ndarray) -> dict: if img is None or img.size == 0: return {} g = _to_gray8(img) lap = cv2.Laplacian(g.astype(np.float32), cv2.CV_32F, ksize=3) pure_black = int(np.count_nonzero(g <= 12)) bg = g >= 235 dark = g < 170 rb = 0.0 if img.ndim == 3 and dark.any(): b = img[:, :, 0].astype(np.float32)[dark].mean() r = img[:, :, 2].astype(np.float32)[dark].mean() rb = float(r - b) return dict( mean=round(float(g.mean()), 2), lapvar=round(float(lap.var()), 1), pure_black=pure_black, bg245=round(float(100.0 * np.count_nonzero(g >= 245) / g.size), 1), bg_std=round(float(g[bg].std()), 2) if bg.any() else 0.0, rb=round(rb, 1), )