1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
| import torch import torch.nn as nn import numpy as np from typing import Tuple
class FocusGate(nn.Module): """ FocusGate: 可靠性门控的先验融合模块 论文: arXiv:2610.08663 (ICASSP 2027投稿) 功能: 1. 从散焦图计算3个形状统计量 2. 基于阈值判断帧是否可靠 3. 可靠时融合散焦先验,不可靠时退回基线 """ def __init__( self, spread_thresh: float = 0.55, sep_thresh: float = 0.45, sharp_min: float = 0.03, sharp_max: float = 0.70, defocus_weight: float = 0.25 ): super().__init__() self.spread_thresh = spread_thresh self.sep_thresh = sep_thresh self.sharp_min = sharp_min self.sharp_max = sharp_max self.defocus_weight = defocus_weight def compute_shape_stats(self, defocus_map: torch.Tensor) -> dict: """ 计算散焦图的3个形状统计量 Args: defocus_map: (B, H, W) in-focus概率, 值域[0,1] Returns: stats字典 """ B = defocus_map.shape[0] flat = defocus_map.reshape(B, -1) p10 = torch.quantile(flat, 0.10, dim=-1) p90 = torch.quantile(flat, 0.90, dim=-1) spread = p90 - p10 high_mean = (flat * (flat > 0.5).float()).sum(-1) / \ ((flat > 0.5).float().sum(-1) + 1e-8) low_mean = (flat * (flat <= 0.5).float()).sum(-1) / \ ((flat <= 0.5).float().sum(-1) + 1e-8) separation = high_mean - low_mean sharp_frac = (flat > 0.5).float().mean(-1) return { 'spread': spread, 'separation': separation, 'sharp_frac': sharp_frac } def forward( self, base_pred: torch.Tensor, defocus_map: torch.Tensor ) -> Tuple[torch.Tensor, torch.Tensor]: """ 门控融合 Args: base_pred: 基线预测 (B, H, W) defocus_map: 散焦图 (B, H, W) Returns: fused: (B, H, W) 融合后预测 gate: (B,) 门控状态 """ stats = self.compute_shape_stats(defocus_map) gate = ( (stats['spread'] >= self.spread_thresh) & (stats['separation'] >= self.sep_thresh) & (stats['sharp_frac'] >= self.sharp_min) & (stats['sharp_frac'] <= self.sharp_max) ).float() defocus_rank = self._rank_normalize(defocus_map) fused = base_pred + gate.unsqueeze(-1).unsqueeze(-1) * \ self.defocus_weight * defocus_rank return fused, gate def _rank_normalize(self, x: torch.Tensor) -> torch.Tensor: """逐帧rank归一化到[0,1]""" B = x.shape[0] flat = x.reshape(B, -1) sorted_vals, _ = torch.sort(flat, dim=-1) ranks = torch.zeros_like(flat) for b in range(B): ranks[b] = torch.searchsorted(sorted_vals[b], flat[b]) ranks = ranks / (flat.shape[-1] - 1) return ranks.reshape(x.shape)
class DefocusEstimator(nn.Module): """ 散焦估计器 论文中两个版本: 1. Scratch estimator: U-Net, 2.76M参数 2. Recipe estimator: MobileNetV3-L + 深度蒸馏 + 高频通道 """ def __init__(self, backbone='mobilenetv3'): super().__init__() if backbone == 'mobilenetv3': import torchvision.models as models self.encoder = models.mobilenet_v3_large(weights='DEFAULT') self.encoder.classifier = nn.Identity() self.head = nn.Sequential( nn.Conv2d(960, 256, 1), nn.BatchNorm2d(256), nn.ReLU6(inplace=True), nn.Conv2d(256, 1, 1), nn.Sigmoid() ) self.high_freq_conv = nn.Conv2d(1, 3, 1) else: self.encoder = nn.Sequential( nn.Conv2d(4, 64, 3, padding=1), nn.ReLU(inplace=True), nn.MaxPool2d(2), nn.Conv2d(64, 128, 3, padding=1), nn.ReLU(inplace=True), nn.MaxPool2d(2), nn.Conv2d(128, 256, 3, padding=1), nn.ReLU(inplace=True), nn.MaxPool2d(2), ) self.decoder = nn.Sequential( nn.ConvTranspose2d(256, 128, 2, stride=2), nn.ReLU(inplace=True), nn.ConvTranspose2d(128, 64, 2, stride=2), nn.ReLU(inplace=True), nn.ConvTranspose2d(64, 1, 2, stride=2), nn.Sigmoid() ) def forward(self, x: torch.Tensor) -> torch.Tensor: """预测in-focus概率图""" if hasattr(self, 'high_freq_conv'): gray = x.mean(dim=1, keepdim=True) high_freq = gray - torch.nn.functional.avg_pool2d( gray, 3, stride=1, padding=1 ) x_hf = self.high_freq_conv(high_freq) x = torch.cat([x, x_hf], dim=1) if hasattr(self, 'decoder'): feat = self.encoder(x) out = self.decoder(feat) else: feat = self.encoder(x) out = self.head(feat) return out.squeeze(1)
class FullFocusGate(nn.Module): """ 完整FocusGate系统 包含: 1. 多个gaze-free先验(中心高斯、人脸、谱残差等) 2. 散焦估计器 3. 可靠性门控 """ def __init__(self): super().__init__() self.defocus_estimator = DefocusEstimator(backbone='mobilenetv3') self.gate = FocusGate() self.weights = { 'center': 1.0, 'face': 2.0, 'spectral_residual': 0.0, 'dino_attn': 1.5, 'depth': 0.0, 'flow': 1.0, 'defocus': 0.25, } def forward(self, frame, priors): """ Args: frame: (B, 3, H, W) 输入帧 priors: dict of (B, H, W) 先验图 """ base = torch.zeros_like(priors['center']) for name, (w, gamma) in [ ('center', (1.0, 1)), ('face', (2.0, 0.5)), ('dino_attn', (1.5, 3)), ('flow', (1.0, 1)), ]: base += w * priors[name].clamp(0, 1).pow(gamma) defocus = self.defocus_estimator(frame) fused, gate = self.gate(base, defocus) return fused, gate
if __name__ == "__main__": print("=" * 60) print("FocusGate 可靠性门控融合 - 测试") print("=" * 60) B, H, W = 2, 224, 224 defocus_shallow = torch.zeros(B, H, W) defocus_shallow[:, :H//2, :] = 0.9 defocus_shallow[:, H//2:, :] = 0.1 defocus_deep = torch.full((B, H, W), 0.5) defocus_deep += torch.randn(B, H, W) * 0.05 base_pred = torch.randn(B, H, W).sigmoid() gate_module = FocusGate() fused_shallow, gate_shallow = gate_module(base_pred, defocus_shallow) print(f"\n浅景深场景:") print(f" 门控状态: {gate_shallow.tolist()}") print(f" 融合变化: {(fused_shallow - base_pred).abs().mean():.6f}") fused_deep, gate_deep = gate_module(base_pred, defocus_deep) print(f"\n深景深场景:") print(f" 门控状态: {gate_deep.tolist()}") print(f" 融合变化: {(fused_deep - base_pred).abs().mean():.6f}") print(f"\n门控效果验证:") print(f" 浅景深门控开启: {gate_shallow.mean():.2f} (应≈1)") print(f" 深景深门控关闭: {gate_deep.mean():.2f} (应≈0)")
|