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
| import torch import torch.nn as nn import torch.nn.functional as F from torchvision.models.mobilenetv3 import mobilenet_v3_small
class MobileNetFatigueDistraction(nn.Module): """ MobileNet疲劳分心检测网络 多任务输出:疲劳状态 + 分心类型 """ def __init__(self, num_fatigue_classes: int = 3, num_distraction_classes: int = 6): """ Args: num_fatigue_classes: 疲劳等级(alert/drowsy/fatigued) num_distraction_classes: 分心类型(正常/手机/饮食/交谈/调节/其他) """ super().__init__() mobilenet = mobilenet_v3_small(pretrained=True) self.features = mobilenet.features self.fatigue_head = nn.Sequential( nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(576, 128), nn.ReLU(inplace=True), nn.Dropout(0.2), nn.Linear(128, num_fatigue_classes) ) self.distraction_head = nn.Sequential( nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(576, 128), nn.ReLU(inplace=True), nn.Dropout(0.2), nn.Linear(128, num_distraction_classes) ) self.shared_fc = nn.Linear(576, 256) def forward(self, x: torch.Tensor) -> dict: """ 前向传播 Args: x: 输入图像 (B, 3, 224, 224) Returns: output: { 'fatigue_logits': (B, 3), 'distraction_logits': (B, 6), 'shared_features': (B, 256) } """ features = self.features(x) shared = F.adaptive_avg_pool2d(features, 1).flatten(1) shared_features = F.relu(self.shared_fc(shared)) fatigue_logits = self.fatigue_head(features) distraction_logits = self.distraction_head(features) return { 'fatigue_logits': fatigue_logits, 'distraction_logits': distraction_logits, 'shared_features': shared_features }
class MultiTaskLoss(nn.Module): """ 多任务损失函数 疲劳 + 分心联合优化 """ def __init__(self, fatigue_weight: float = 1.0, distraction_weight: float = 1.0): super().__init__() self.fatigue_weight = fatigue_weight self.distraction_weight = distraction_weight self.ce_loss = nn.CrossEntropyLoss() def forward(self, predictions: dict, targets: dict) -> torch.Tensor: """ 计算损失 Args: predictions: 模型输出 targets: { 'fatigue': (B,), 'distraction': (B,) } """ fatigue_loss = self.ce_loss( predictions['fatigue_logits'], targets['fatigue'] ) distraction_loss = self.ce_loss( predictions['distraction_logits'], targets['distraction'] ) total_loss = (self.fatigue_weight * fatigue_loss + self.distraction_weight * distraction_loss) return total_loss
class PERCLOSCalculator(nn.Module): """ PERCLOS计算模块 基于眼睑开度序列 """ def __init__(self, window_sec: int = 60, fps: int = 30): super().__init__() self.window_frames = window_sec * fps self.threshold = 0.2 def forward(self, eye_openness: torch.Tensor) -> torch.Tensor: """ 计算PERCLOS Args: eye_openness: 眼睑开度序列 (B, T), 范围[0, 1] Returns: perclos: PERCLOS值 (B,) """ B, T = eye_openness.shape perclos_values = [] for i in range(T - self.window_frames): window = eye_openness[:, i:i+self.window_frames] closed = (window < self.threshold).float() perclos = closed.mean(dim=1) perclos_values.append(perclos) if len(perclos_values) > 0: return torch.stack(perclos_values, dim=1).mean(dim=1) else: return torch.zeros(B, device=eye_openness.device)
class RealTimeFatigueDetector: """ 实时疲劳分心检测器 优化推理速度 """ def __init__(self, model_path: str, device: str = 'cpu'): self.model = MobileNetFatigueDistraction() self.model.load_state_dict(torch.load(model_path, map_location=device)) self.model.eval() self.device = device self.model = self.model.to(device) self.transform = transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) def detect(self, frame: np.ndarray) -> dict: """ 单帧检测 Args: frame: 输入图像 (H, W, 3) Returns: result: { 'fatigue_level': str, 'distraction_type': str, 'latency_ms': float } """ import time start_time = time.time() frame_pil = Image.fromarray(frame) input_tensor = self.transform(frame_pil).unsqueeze(0).to(self.device) with torch.no_grad(): output = self.model(input_tensor) fatigue_idx = output['fatigue_logits'].argmax(dim=1).item() distraction_idx = output['distraction_logits'].argmax(dim=1).item() fatigue_levels = ['alert', 'drowsy', 'fatigued'] distraction_types = ['normal', 'phone', 'eating', 'talking', 'adjusting', 'other'] latency_ms = (time.time() - start_time) * 1000 return { 'fatigue_level': fatigue_levels[fatigue_idx], 'distraction_type': distraction_types[distraction_idx], 'fatigue_confidence': F.softmax(output['fatigue_logits'], dim=1)[0, fatigue_idx].item(), 'distraction_confidence': F.softmax(output['distraction_logits'], dim=1)[0, distraction_idx].item(), 'latency_ms': latency_ms }
if __name__ == "__main__": from torchvision import transforms from PIL import Image model = MobileNetFatigueDistraction() total_params = sum(p.numel() for p in model.parameters()) print(f"模型参数: {total_params:,}") print(f"模型大小: {total_params * 4 / 1024 / 1024:.2f} MB") x = torch.randn(1, 3, 224, 224) output = model(x) print(f"\n疲劳检测输出: {output['fatigue_logits'].shape}") print(f"分心检测输出: {output['distraction_logits'].shape}") print(f"共享特征: {output['shared_features'].shape}")
|