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 279 280 281 282 283 284
| import numpy as np import snpe from typing import Dict, Tuple
class SNPEDMSModel: """ SNPE DMS 模型封装 使用高通 SNPE 在 QCS8255 上运行推理 """ def __init__(self, model_path: str, runtime: str = "GPU"): """ 初始化模型 Args: model_path: .dlc 模型路径 runtime: 运行时 ("GPU", "CPU", "DSP") """ self.runtime = runtime self.snpe_context = snpe.create_context( model_path=model_path, runtime=runtime, output_layers=["output"] ) self.input_name = self.snpe_context.get_input_names()[0] self.input_shape = self.snpe_context.get_input_shape(self.input_name) def preprocess(self, image: np.ndarray) -> np.ndarray: """ 图像预处理 Args: image: BGR 图像 (H, W, C) Returns: preprocessed: 预处理后的张量 """ target_h, target_w = self.input_shape[1:3] image = cv2.resize(image, (target_w, target_h)) image = image.astype(np.float32) / 255.0 mean = [0.485, 0.456, 0.406] std = [0.229, 0.224, 0.225] image = (image - mean) / std image = np.transpose(image, (2, 0, 1)) image = np.expand_dims(image, 0) return image def infer(self, image: np.ndarray) -> np.ndarray: """ 执行推理 Args: image: BGR 图像 Returns: output: 模型输出 """ input_tensor = self.preprocess(image) output = self.snpe_context.execute({ self.input_name: input_tensor }) return output["output"] def postprocess(self, output: np.ndarray) -> Dict: """ 后处理 Args: output: 模型输出 Returns: result: 检测结果 """ class_names = ["normal", "distracted", "drowsy", "phone_use"] probs = self._softmax(output[0]) pred_class = np.argmax(probs) return { "class": class_names[pred_class], "confidence": probs[pred_class], "probabilities": { name: float(prob) for name, prob in zip(class_names, probs) } } def _softmax(self, x: np.ndarray) -> np.ndarray: """Softmax""" e_x = np.exp(x - np.max(x)) return e_x / e_x.sum()
class DMSPipeline: """ 完整 DMS 流水线 集成眼动追踪 + 分心检测 + 疲劳检测 """ def __init__(self, model_dir: str): """ 初始化流水线 Args: model_dir: 模型目录 """ self.face_detector = SNPEDMSModel( f"{model_dir}/face_detector.dlc", runtime="GPU" ) self.eye_tracker = SNPEDMSModel( f"{model_dir}/eye_tracker.dlc", runtime="GPU" ) self.distraction_classifier = SNPEDMSModel( f"{model_dir}/distraction_classifier.dlc", runtime="GPU" ) self.perclos_history = [] self.blink_history = [] def process_frame(self, image: np.ndarray) -> Dict: """ 处理单帧 Args: image: BGR 图像 Returns: result: 检测结果 """ result = { "face_detected": False, "eye_openness": None, "perclos": None, "distraction_state": None, "drowsiness_level": None } face_output = self.face_detector.infer(image) face_box = self._parse_face_box(face_output) if face_box is None: return result result["face_detected"] = True x1, y1, x2, y2 = face_box face_roi = image[y1:y2, x1:x2] eye_output = self.eye_tracker.infer(face_roi) eye_state = self._parse_eye_state(eye_output) result["eye_openness"] = eye_state["openness"] self.perclos_history.append(eye_state["openness"]) if len(self.perclos_history) > 900: self.perclos_history.pop(0) result["perclos"] = self._calculate_perclos() distraction_output = self.distraction_classifier.infer(face_roi) distraction_result = self.distraction_classifier.postprocess(distraction_output) result["distraction_state"] = distraction_result if result["perclos"] is not None: if result["perclos"] > 0.3: result["drowsiness_level"] = "severe" elif result["perclos"] > 0.15: result["drowsiness_level"] = "moderate" else: result["drowsiness_level"] = "normal" return result def _parse_face_box(self, output: np.ndarray) -> Tuple[int, int, int, int]: """解析人脸框""" return (100, 50, 400, 400) def _parse_eye_state(self, output: np.ndarray) -> Dict: """解析眼部状态""" return { "openness": float(output[0][0]) } def _calculate_perclos(self) -> float: """计算 PERCLOS""" if len(self.perclos_history) < 100: return 0.0 closed_frames = sum(1 for o in self.perclos_history if o < 0.2) return closed_frames / len(self.perclos_history)
class PerformanceMonitor: """性能监控器""" def __init__(self): self.inference_times = [] self.fps_history = [] def record(self, inference_time: float): """记录推理时间""" self.inference_times.append(inference_time) if len(self.inference_times) > 100: self.inference_times.pop(0) def get_stats(self) -> Dict: """获取统计信息""" if not self.inference_times: return {"avg_time": 0, "fps": 0} avg_time = np.mean(self.inference_times) fps = 1000 / avg_time if avg_time > 0 else 0 return { "avg_time_ms": avg_time, "fps": fps, "min_time_ms": np.min(self.inference_times), "max_time_ms": np.max(self.inference_times) }
if __name__ == "__main__": import cv2 import time pipeline = DMSPipeline("/data/models") monitor = PerformanceMonitor() for i in range(100): image = np.random.randint(0, 255, (720, 1280, 3), dtype=np.uint8) start_time = time.time() result = pipeline.process_frame(image) inference_time = (time.time() - start_time) * 1000 monitor.record(inference_time) if i % 10 == 0: stats = monitor.get_stats() print(f"帧 {i}: 疲劳等级={result['drowsiness_level']}, " f"平均推理时间={stats['avg_time_ms']:.1f}ms, " f"FPS={stats['fps']:.1f}")
|