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 275 276 277 278
| import torch import torch.nn as nn import torch.nn.functional as F
class CabinSensorFusionSystem: """ 座舱多模态传感器融合系统 三级融合架构: 1. 早期融合(像素级):ToF深度+RGB-IR对齐合并 2. 中期融合(特征级):摄像头特征+雷达特征交叉注意力 3. 晚期融合(决策级):各模态独立决策+置信度加权 """ SENSORS = { 'dms_ir': { 'type': 'near-infrared camera', 'resolution': '1280x960', 'fps': 30, 'wavelength': '940nm', 'primary_function': 'gaze_estimation, fatigue_detection', 'fusion_role': 'feature_level', }, 'oms_wide': { 'type': 'wide-angle camera', 'resolution': '1920x1080', 'fps': 30, 'fov': '120°', 'primary_function': 'occupant_classification, seatbelt', 'fusion_role': 'feature_level', }, 'radar_60ghz': { 'type': 'mmWave FMCW radar', 'frequency': '60GHz', 'channels': '2T4R', 'range_resolution': '3.75cm', 'fps': 20, 'primary_function': 'CPD, vital_signs', 'fusion_role': 'decision_level', }, 'tof_depth': { 'type': 'time-of-flight depth camera', 'resolution': '320x240', 'fps': 30, 'range': '0.3-3.0m', 'primary_function': '3D_pose, OOP', 'fusion_role': 'pixel_level', }, }
class EarlyFusionModule(nn.Module): """ 早期融合:ToF深度图 + RGB-IR图像像素级合并 适用:3D姿态估计 + OOP检测 将深度信息作为RGB-IR的第4通道 """ def __init__(self): super().__init__() self.backbone = nn.Sequential( nn.Conv2d(4, 32, 3, stride=2, padding=1), nn.BatchNorm2d(32), nn.ReLU(), nn.Conv2d(32, 64, 3, stride=2, padding=1), nn.BatchNorm2d(64), nn.ReLU(), nn.Conv2d(64, 128, 3, stride=2, padding=1), nn.BatchNorm2d(128), nn.ReLU(), nn.AdaptiveAvgPool2d((20, 15)), ) def forward(self, rgb_ir: torch.Tensor, depth: torch.Tensor) -> torch.Tensor: """ Args: rgb_ir: (B, 3, H, W) RGB或IR图像 depth: (B, 1, H, W) 深度图 Returns: fused_feat: (B, 128, 20, 15) 融合特征 """ if rgb_ir.shape[-2:] != depth.shape[-2:]: depth = F.interpolate( depth, size=rgb_ir.shape[-2:], mode='bilinear', align_corners=False ) fused_input = torch.cat([rgb_ir, depth], dim=1) fused_feat = self.backbone(fused_input) return fused_feat
class MidLevelFusionModule(nn.Module): """ 中期融合:摄像头特征 + 雷达特征交叉注意力 适用:CPD + 乘员分类 + 生命体征 摄像头提供空间细节,雷达提供穿透/微动 """ def __init__(self, cam_dim: int = 128, radar_dim: int = 64, fusion_dim: int = 128): super().__init__() self.cam_proj = nn.Linear(cam_dim, fusion_dim) self.radar_proj = nn.Linear(radar_dim, fusion_dim) self.cam_to_radar_attn = nn.MultiheadAttention( embed_dim=fusion_dim, num_heads=4, batch_first=True ) self.radar_to_cam_attn = nn.MultiheadAttention( embed_dim=fusion_dim, num_heads=4, batch_first=True ) self.norm1 = nn.LayerNorm(fusion_dim) self.norm2 = nn.LayerNorm(fusion_dim) self.norm3 = nn.LayerNorm(fusion_dim) self.norm4 = nn.LayerNorm(fusion_dim) self.ffn = nn.Sequential( nn.Linear(fusion_dim, fusion_dim * 4), nn.GELU(), nn.Linear(fusion_dim * 4, fusion_dim) ) def forward(self, cam_feat: torch.Tensor, radar_feat: torch.Tensor) -> torch.Tensor: """ Args: cam_feat: (B, T_c, cam_dim) 摄像头时序特征 radar_feat: (B, T_r, radar_dim) 雷达时序特征 Returns: fused: (B, T_c, fusion_dim) 融合特征 """ cam_q = self.cam_proj(cam_feat) radar_k = self.radar_proj(radar_feat) attn1, _ = self.cam_to_radar_attn( query=cam_q, key=radar_k, value=radar_k ) cam_enhanced = self.norm1(cam_q + attn1) cam_enhanced = self.norm2(cam_enhanced + self.ffn(cam_enhanced)) attn2, _ = self.radar_to_cam_attn( query=radar_k, key=cam_q, value=cam_q ) radar_enhanced = self.norm3(radar_k + attn2) radar_enhanced = self.norm4(radar_enhanced + self.ffn(radar_enhanced)) if radar_enhanced.shape[1] != cam_enhanced.shape[1]: radar_enhanced = F.interpolate( radar_enhanced.transpose(1, 2), size=cam_enhanced.shape[1], mode='linear', align_corners=True ).transpose(1, 2) fused = (cam_enhanced + radar_enhanced) / 2 return fused
class LateFusionModule(nn.Module): """ 晚期融合:各模态独立决策 + 置信度加权 适用:最终决策层(警告等级/气囊部署) """ def __init__(self, num_classes: int = 5): super().__init__() self.camera_confidence = ConfidenceEstimator() self.radar_confidence = ConfidenceEstimator() self.tof_confidence = ConfidenceEstimator() self.weight_predictor = nn.Sequential( nn.Linear(6, 32), nn.ReLU(), nn.Linear(32, 3), nn.Softmax(dim=-1) ) def forward(self, cam_result: dict, radar_result: dict, tof_result: dict) -> dict: """ Args: cam_result: {prediction, confidence} radar_result: {prediction, confidence} tof_result: {prediction, confidence} Returns: fused_result """ input_vec = torch.stack([ cam_result['confidence'], radar_result['confidence'], tof_result['confidence'], cam_result['prediction'].max(), radar_result['prediction'].max(), tof_result['prediction'].max(), ], dim=-1) weights = self.weight_predictor(input_vec) fused_pred = (weights[:, 0:1] * cam_result['prediction'] + weights[:, 1:2] * radar_result['prediction'] + weights[:, 2:3] * tof_result['prediction']) return { 'prediction': fused_pred, 'weights': weights, 'cam_confidence': cam_result['confidence'], 'radar_confidence': radar_result['confidence'], 'tof_confidence': tof_result['confidence'], }
class ConfidenceEstimator(nn.Module): """基于预测熵的置信度估计""" def __init__(self): super().__init__() self.proj = nn.Sequential( nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(128, 32), nn.ReLU(), nn.Linear(32, 1), nn.Sigmoid() ) def forward(self, x): return self.proj(x).squeeze(-1)
if __name__ == "__main__": print("座舱多模态传感器融合系统:") print("=" * 50) system = CabinSensorFusionSystem() for name, spec in system.SENSORS.items(): print(f"\n{name}:") for k, v in spec.items(): print(f" {k}: {v}") fusion = MidLevelFusionModule() cam = torch.randn(2, 30, 128) radar = torch.randn(2, 20, 64) with torch.no_grad(): out = fusion(cam, radar) print(f"\n中期融合测试:") print(f" 摄像头输入: {cam.shape}") print(f" 雷达输入: {radar.shape}") print(f" 融合输出: {out.shape}") print(f" 参数量: {sum(p.numel() for p in fusion.parameters())/1e3:.1f}K")
|