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
| """ Edge-VisionGuard 轻量框架 驾驶员状态 + 低能见度危险检测
混合架构: 信号处理(DSP) + AI分类 部署: 边缘设备 (RPi/Jetson) """
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from typing import Tuple, Dict from dataclasses import dataclass
@dataclass class DriverState: """驾驶员状态""" drowsiness_score: float distraction_type: str eye_openness: float head_pose: Tuple[float, float, float] behavior: str
@dataclass class RoadVisibility: """道路能见度""" visibility_level: str contrast_ratio: float brightness: float risk_score: float
@dataclass class FusedRisk: """融合风险评分""" driver_risk: float road_risk: float combined_risk: float alert_level: int recommendations: list
class SignalProcessingLayer: """信号处理层 (传统DSP)""" def __init__(self): self.perplos_window = 60 self.eye_threshold = 0.3 def compute_perclos(self, eye_openness_series: np.ndarray) -> float: """ PERCLOS: 眼睑闭合度百分比 Args: eye_openness_series: (N,) 眼部开度序列, 0-1 Returns: perclos: 0-100% """ closed_frames = np.sum(eye_openness_series < self.eye_threshold) perclos = closed_frames / len(eye_openness_series) * 100 if perclos < 15: return perclos elif perclos < 30: return perclos elif perclos < 50: return perclos else: return perclos def compute_contrast(self, image: np.ndarray) -> float: """计算图像对比度 (能见度指标)""" gray = np.mean(image, axis=2) if len(image.shape) == 3 else image contrast = np.std(gray.astype(np.float32)) / 255.0 return contrast def compute_brightness(self, image: np.ndarray) -> float: """计算图像亮度""" return np.mean(image) def detect_fog(self, image: np.ndarray) -> float: """雾检测 (基于频率域)""" gray = np.mean(image, axis=2) if len(image.shape) == 3 else image fft = np.fft.fft2(gray) fft_shift = np.fft.fftshift(fft) magnitude = np.abs(fft_shift) h, w = magnitude.shape center_h, center_w = h // 2, w // 2 low_freq = magnitude[ center_h-10:center_h+10, center_w-10:center_w+10 ].sum() total = magnitude.sum() high_freq_ratio = 1 - (low_freq / total) fog_score = 1 - high_freq_ratio return fog_score
class DriverStateDetector: """驾驶员状态检测 (AI)""" def __init__(self): self.behavior_classifier = self._build_classifier() self.eye_history = [] def _build_classifier(self): """轻量分类模型""" return nn.Sequential( nn.Conv2d(3, 32, 3, stride=2, padding=1), nn.BatchNorm2d(32), nn.ReLU(inplace=True), nn.Conv2d(32, 64, 3, stride=2, padding=1), nn.BatchNorm2d(64), nn.ReLU(inplace=True), nn.Conv2d(64, 128, 3, stride=2, padding=1), nn.BatchNorm2d(128), nn.ReLU(inplace=True), nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(128, 64), nn.ReLU(inplace=True), nn.Linear(64, 5), ) def detect(self, frame: np.ndarray) -> DriverState: """检测驾驶员状态""" eye_openness = np.random.uniform(0.3, 1.0) self.eye_history.append(eye_openness) if len(self.eye_history) > 300: self.eye_history.pop(0) return DriverState( drowsiness_score=1 - eye_openness, distraction_type='none', eye_openness=eye_openness, head_pose=(0, 0, 0), behavior='normal_driving' )
class RoadVisibilityDetector: """道路能见度检测""" def __init__(self): self.dsp = SignalProcessingLayer() def detect(self, frame: np.ndarray) -> RoadVisibility: """检测道路能见度""" contrast = self.dsp.compute_contrast(frame) brightness = self.dsp.compute_brightness(frame) fog_score = self.dsp.detect_fog(frame) if contrast > 0.3 and brightness > 80: level = 'clear' risk = 0.1 elif fog_score > 0.7: level = 'fog' risk = 0.7 elif brightness < 30: level = 'dark' risk = 0.5 elif contrast < 0.15: level = 'rain' risk = 0.6 else: level = 'cloudy' risk = 0.3 return RoadVisibility( visibility_level=level, contrast_ratio=contrast, brightness=brightness, risk_score=risk )
class EdgeVisionGuard: """Edge-VisionGuard 完整系统""" def __init__(self): self.driver_detector = DriverStateDetector() self.road_detector = RoadVisibilityDetector() self.dsp = SignalProcessingLayer() def process(self, frame: np.ndarray) -> FusedRisk: """处理单帧""" driver_state = self.driver_detector.detect(frame) road_vis = self.road_detector.detect(frame) if len(self.driver_detector.eye_history) > 10: perclos = self.dsp.compute_perclos( np.array(self.driver_detector.eye_history) ) else: perclos = 0 driver_risk = max( driver_state.drowsiness_score, perclos / 100 ) road_risk = road_vis.risk_score if driver_risk > 0.5 and road_risk > 0.5: combined = min(driver_risk + road_risk, 1.0) * 1.2 else: combined = (driver_risk + road_risk) / 2 combined = min(combined, 1.0) if combined > 0.8: level = 3 recs = ['立即停车休息', '开启双闪', '减速行驶'] elif combined > 0.6: level = 2 recs = ['建议休息', '提高注意力', '减速'] elif combined > 0.3: level = 1 recs = ['注意路况', '保持警觉'] else: level = 0 recs = [] return FusedRisk( driver_risk=driver_risk, road_risk=road_risk, combined_risk=combined, alert_level=level, recommendations=recs )
if __name__ == "__main__": print("=" * 60) print("Edge-VisionGuard 测试") print("=" * 60) system = EdgeVisionGuard() scenarios = [ ('正常白天驾驶', np.random.randint(100, 200, (480, 640, 3))), ('夜间疲劳+隧道', np.random.randint(20, 50, (480, 640, 3))), ('雾天驾驶', np.random.randint(150, 180, (480, 640, 3))), ('雨天驾驶', np.random.randint(60, 120, (480, 640, 3))), ] for name, frame in scenarios: risk = system.process(frame) print(f"\n{name}:") print(f" 驾驶员风险: {risk.driver_risk:.2f}") print(f" 道路风险: {risk.road_risk:.2f}") print(f" 综合风险: {risk.combined_risk:.2f}") print(f" 警报等级: L{risk.alert_level}") if risk.recommendations: print(f" 建议: {', '.join(risk.recommendations)}")
|