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
| """ 高通 QCS8255 DMS 部署示例
使用 ONNX Runtime QNN Execution Provider """
import numpy as np import onnxruntime as ort from typing import Dict, List, Tuple, Optional import time
class QNNInferenceEngine: """ QNN 推理引擎 支持在高通平台上加速推理 """ def __init__( self, model_path: str, backend: str = "HTP", precision: str = "int8" ): """ Args: model_path: ONNX 模型路径 backend: 推理后端 precision: 推理精度 """ self.model_path = model_path self.backend = backend self.precision = precision provider_options = self._get_provider_options() self.session = ort.InferenceSession( model_path, providers=['QNNExecutionProvider'], provider_options=[provider_options] ) self.input_names = [inp.name for inp in self.session.get_inputs()] self.output_names = [out.name for out in self.session.get_outputs()] print(f"模型加载完成: {model_path}") print(f"后端: {backend}, 精度: {precision}") print(f"输入: {self.input_names}") print(f"输出: {self.output_names}") def _get_provider_options(self) -> dict: """获取 QNN Provider 配置""" options = { "backend_type": self.backend, "profiling_level": "basic", } if self.backend == "HTP": options.update({ "htp_arch": "v68", "skew_factor": 4, }) return options def infer( self, inputs: Dict[str, np.ndarray] ) -> Dict[str, np.ndarray]: """ 执行推理 Args: inputs: {输入名: 输入数组} Returns: {输出名: 输出数组} Example: >>> engine = QNNInferenceEngine("model.onnx", backend="HTP") >>> inputs = {"input": np.random.randn(1, 3, 224, 224).astype(np.float32)} >>> outputs = engine.infer(inputs) """ start_time = time.perf_counter() outputs = self.session.run( output_names=self.output_names, input_feed=inputs ) elapsed_ms = (time.perf_counter() - start_time) * 1000 return { name: output for name, output in zip(self.output_names, outputs) }, elapsed_ms
class DMSModel: """ DMS 模型封装 包含:人脸检测、关键点检测、疲劳检测 """ def __init__(self, model_dir: str, backend: str = "HTP"): self.face_detector = QNNInferenceEngine( f"{model_dir}/face_detector.onnx", backend=backend ) self.landmark_detector = QNNInferenceEngine( f"{model_dir}/landmark_detector.onnx", backend=backend ) self.fatigue_classifier = QNNInferenceEngine( f"{model_dir}/fatigue_classifier.onnx", backend=backend ) def detect_fatigue( self, frame: np.ndarray ) -> dict: """ 检测疲劳状态 Args: frame: 输入图像 (H, W, 3) Returns: { 'faces': list of bboxes, 'landmarks': list of landmarks, 'fatigue_score': float, 'is_fatigued': bool, 'latency_ms': dict } """ latency = {} face_input = self._preprocess(frame, (320, 240)) face_outputs, face_latency = self.face_detector.infer({"input": face_input}) latency['face_detection'] = face_latency faces = self._postprocess_faces(face_outputs) if len(faces) == 0: return {'is_fatigued': False, 'latency_ms': latency} landmarks_list = [] for face in faces: face_crop = self._crop_face(frame, face) landmark_input = self._preprocess(face_crop, (112, 112)) landmark_outputs, landmark_latency = self.landmark_detector.infer({"input": landmark_input}) landmarks = landmark_outputs['output'].reshape(-1, 2) landmarks_list.append(landmarks) latency['landmark_detection'] = landmark_latency if len(landmarks_list) > 0: feat = self._extract_fatigue_features(landmarks_list[0]) fatigue_input = feat.reshape(1, -1).astype(np.float32) fatigue_outputs, fatigue_latency = self.fatigue_classifier.infer({"input": fatigue_input}) latency['fatigue_classification'] = fatigue_latency fatigue_score = float(fatigue_outputs['output'][0, 0]) is_fatigued = fatigue_score > 0.5 else: fatigue_score = 0.0 is_fatigued = False return { 'faces': faces, 'landmarks': landmarks_list, 'fatigue_score': fatigue_score, 'is_fatigued': is_fatigued, 'latency_ms': latency, 'total_latency_ms': sum(latency.values()) } def _preprocess(self, frame: np.ndarray, size: Tuple[int, int]) -> np.ndarray: """图像预处理""" import cv2 resized = cv2.resize(frame, size[::-1]) normalized = (resized - 127.5) / 127.5 transposed = np.transpose(normalized, (2, 0, 1)) return np.expand_dims(transposed, 0).astype(np.float32) def _postprocess_faces(self, outputs: dict) -> List: """后处理人脸检测结果""" return [[50, 50, 200, 200]] def _crop_face(self, frame: np.ndarray, bbox: List) -> np.ndarray: """裁剪人脸区域""" x1, y1, x2, y2 = bbox return frame[y1:y2, x1:x2] def _extract_fatigue_features(self, landmarks: np.ndarray) -> np.ndarray: """从关键点提取疲劳特征""" ear = self._calculate_ear(landmarks) return np.array([ear, 0.0, 0.0, 0.0, 0.0]) def _calculate_ear(self, landmarks: np.ndarray) -> float: """计算眼睛纵横比""" return 0.3
def benchmark_qnn_backends(model_path: str, input_shape: Tuple = (1, 3, 224, 224)): """ 对比不同后端的性能 Args: model_path: ONNX 模型路径 input_shape: 输入形状 """ backends = ["CPU", "GPU", "HTP"] results = {} dummy_input = np.random.randn(*input_shape).astype(np.float32) for backend in backends: try: engine = QNNInferenceEngine(model_path, backend=backend) for _ in range(10): engine.infer({"input": dummy_input}) latencies = [] for _ in range(100): _, latency = engine.infer({"input": dummy_input}) latencies.append(latency) results[backend] = { 'mean_ms': np.mean(latencies), 'std_ms': np.std(latencies), 'min_ms': np.min(latencies), 'max_ms': np.max(latencies), 'fps': 1000.0 / np.mean(latencies) } except Exception as e: results[backend] = {'error': str(e)} print("\n" + "=" * 60) print(f"性能测试: {model_path}") print("=" * 60) print(f"{'Backend':<10} {'Mean (ms)':<12} {'Std (ms)':<12} {'FPS':<10}") print("-" * 60) for backend, result in results.items(): if 'error' not in result: print(f"{backend:<10} {result['mean_ms']:<12.2f} {result['std_ms']:<12.2f} {result['fps']:<10.1f}") else: print(f"{backend:<10} Error: {result['error']}") print("=" * 60) return results
if __name__ == "__main__": print("高通 QCS8255 DMS 部署测试")
|