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
| """ 论文复现:LDIE-FDNet完整实现 论文:LDIE-FDNet: Lightweight Dynamic Image Enhancement-Enabled Real-time Fatigue Driving Detection Network 作者:Dong, Zhang, Liu 期刊:PLOS ONE, 2026 DOI: 10.1371/journal.pone.0346055 """
import torch import torch.nn as nn import torch.nn.functional as F import cv2 import numpy as np from typing import List, Dict, Tuple
class LDIEFDNet(nn.Module): """ LDIE-FDNet完整网络 包含: - MSR-LIENET (低光照增强) - GSConv_C3k2 Backbone - DHFAR-Net Neck - PIoU Loss """ def __init__(self, num_classes: int = 5): """ Args: num_classes: 检测类别数 0: normal, 1: eye_closed, 2: yawn, 3: smoking, 4: phone """ super().__init__() self.msr_lienet = MSRLIENET() self.backbone = nn.ModuleList([ nn.Sequential( nn.Conv2d(3, 16, 3, stride=2, padding=1, bias=False), nn.BatchNorm2d(16), nn.SiLU(inplace=True) ), GSConv_C3k2(16, 32, n=1), GSConv_C3k2(32, 64, n=2), GSConv_C3k2(64, 128, n=2), GSConv_C3k2(128, 256, n=1), nn.Sequential( nn.Conv2d(256, 256, 1, bias=False), nn.BatchNorm2d(256), nn.SiLU(inplace=True), nn.MaxPool2d(5, stride=1, padding=2), nn.MaxPool2d(5, stride=1, padding=2), nn.MaxPool2d(5, stride=1, padding=2), ) ]) self.neck = DHFARNet([64, 128, 256]) self.head = nn.Conv2d(256, num_classes + 5, 1) self.piou_loss = PIoULoss() def forward(self, x: torch.Tensor) -> torch.Tensor: """ Args: x: 输入图像 (B, 3, 640, 640) Returns: out: 检测输出 (B, num_classes+5, H, W) """ x = self.msr_lienet(x) features = [] for i, layer in enumerate(self.backbone): x = layer(x) if i in [2, 3, 4]: features.append(x) x = self.neck(features + [x]) out = self.head(x) return out
class FatigueDetector: """疲劳检测完整管道""" def __init__(self, model_path: str, device: str = 'cuda'): self.device = device self.model = LDIEFDNet(num_classes=5) if model_path: self.model.load_state_dict(torch.load(model_path, map_location=device)) self.model.to(device) self.model.eval() self.decision = FatigueDecision(fps=20) self.class_names = ['normal', 'eye_closed', 'yawn', 'smoking', 'phone'] def detect_frame(self, frame: np.ndarray) -> Dict: """ 检测单帧 Args: frame: BGR图像 (H, W, 3) Returns: result: 检测结果 """ image = cv2.resize(frame, (640, 640)) image = image[:, :, ::-1] image = image.transpose(2, 0, 1) image = torch.from_numpy(image).float() / 255.0 image = image.unsqueeze(0).to(self.device) with torch.no_grad(): output = self.model(image) detections = self.postprocess(output) decision_result = self.decision.update(detections) return { 'detections': detections, 'fatigue': decision_result } def postprocess(self, output: torch.Tensor, conf_thresh: float = 0.5) -> List[Dict]: """后处理:提取检测框""" detections = [] output = output.squeeze(0) obj_conf = output[4].sigmoid() mask = obj_conf > conf_thresh if mask.any(): class_conf, class_idx = output[5:].sigmoid().max(dim=0) class_conf = class_conf[mask] class_idx = class_idx[mask] for conf, idx in zip(class_conf, class_idx): detections.append({ 'class': self.class_names[idx.item()], 'conf': conf.item() }) return detections
if __name__ == "__main__": model = LDIEFDNet(num_classes=5) x = torch.randn(1, 3, 640, 640) output = model(x) print(f"输入形状: {x.shape}") print(f"输出形状: {output.shape}") print(f"参数量: {sum(p.numel() for p in model.parameters()):,}") print(f"计算量: {sum(p.numel() * p.numel() for p in model.parameters()) / 1e9:.2f} GFLOPs")
|