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 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
| import numpy as np import cv2 from typing import Tuple, List
class AlcoholDetectionFromFace: """ 基于面部特征的酒精检测 复现WACV 2024论文方法 """ def __init__(self): self.face_detector = cv2.CascadeClassifier( cv2.data.haarcascades + 'haarcascade_frontalface_default.xml' ) self.landmark_detector = cv2.face.createFacemarkLBF() self.landmark_detector.loadModel('lbfmodel.yaml') self.feature_weights = { 'eye_redness': 0.25, 'facial_flushing': 0.20, 'pupil_dilation': 0.20, 'eyelid_drooping': 0.15, 'facial_asymmetry': 0.10, 'micro_expressions': 0.10 } def estimate_bac(self, face_image: np.ndarray) -> dict: """ 估计血液酒精浓度 Args: face_image: 面部RGB图像 Returns: result: { 'bac_estimate': float, # 估计的BAC值 'impairment_level': str, # 损伤等级 'confidence': float, 'features': dict # 各特征得分 } """ gray = cv2.cvtColor(face_image, cv2.COLOR_BGR2GRAY) faces = self.face_detector.detectMultiScale(gray, 1.3, 5) if len(faces) == 0: return {'error': 'No face detected'} x, y, w, h = max(faces, key=lambda f: f[2] * f[3]) face_roi = face_image[y:y+h, x:x+w] _, landmarks = self.landmark_detector.fit(gray, faces) landmark_points = landmarks[0].reshape(-1, 2) features = self._extract_features(face_roi, landmark_points) bac_estimate = sum( self.feature_weights[feat] * score for feat, score in features.items() ) impairment_level = self._classify_impairment(bac_estimate) return { 'bac_estimate': bac_estimate, 'impairment_level': impairment_level, 'confidence': self._calculate_confidence(features), 'features': features } def _extract_features(self, face_roi: np.ndarray, landmarks: np.ndarray) -> dict: """ 提取酒精损伤相关特征 论文Section 3.2描述的方法实现 """ features = {} features['eye_redness'] = self._detect_eye_redness(face_roi, landmarks) features['facial_flushing'] = self._detect_facial_flushing(face_roi, landmarks) features['pupil_dilation'] = self._detect_pupil_dilation(face_roi, landmarks) features['eyelid_drooping'] = self._detect_eyelid_drooping(landmarks) features['facial_asymmetry'] = self._detect_facial_asymmetry(landmarks) features['micro_expressions'] = self._detect_micro_expressions(face_roi) return features def _detect_eye_redness(self, face_roi: np.ndarray, landmarks: np.ndarray) -> float: """ 检测眼睛充血程度 酒精摄入后,眼部血管扩张,巩膜(眼白)呈现红色。 论文方法: 1. 提取眼睛区域 2. 分离巩膜 3. 计算红色通道强度 """ left_eye_indices = list(range(36, 42)) right_eye_indices = list(range(42, 48)) left_eye_points = landmarks[left_eye_indices] left_eye_mask = self._create_eye_mask(face_roi, left_eye_points) right_eye_points = landmarks[right_eye_indices] right_eye_mask = self._create_eye_mask(face_roi, right_eye_points) left_sclera = self._extract_sclera(face_roi, left_eye_mask) right_sclera = self._extract_sclera(face_roi, right_eye_mask) left_redness = np.mean(left_sclera[:, :, 2]) right_redness = np.mean(right_sclera[:, :, 2]) redness_score = np.mean([left_redness, right_redness]) / 255.0 return redness_score def _detect_facial_flushing(self, face_roi: np.ndarray, landmarks: np.ndarray) -> float: """ 检测面部潮红程度 酒精摄入后,面部血管扩张,皮肤呈现潮红。 论文方法: 1. 提取脸颊区域 2. 计算红色通道强度 3. 与正常肤色对比 """ h, w = face_roi.shape[:2] lower_face = face_roi[h//2:, :, :] hsv = cv2.cvtColor(lower_face, cv2.COLOR_BGR2HSV) red_mask = (hsv[:, :, 0] < 10) | (hsv[:, :, 0] > 170) red_ratio = np.sum(red_mask) / red_mask.size return min(1.0, red_ratio * 5) def _detect_pupil_dilation(self, face_roi: np.ndarray, landmarks: np.ndarray) -> float: """ 检测瞳孔扩张程度 酒精会导致瞳孔轻度扩张。 论文方法: 1. 提取瞳孔区域 2. 计算瞳孔直径 3. 与正常值对比 """ gray = cv2.cvtColor(face_roi, cv2.COLOR_BGR2GRAY) left_eye_indices = list(range(36, 42)) left_eye_points = landmarks[left_eye_indices] x_min, y_min = left_eye_points.min(axis=0).astype(int) x_max, y_max = left_eye_points.max(axis=0).astype(int) eye_region = gray[y_min:y_max, x_min:x_max] circles = cv2.HoughCircles( eye_region, cv2.HOUGH_GRADIENT, dp=1, minDist=20, param1=50, param2=30, minRadius=5, maxRadius=30 ) if circles is not None: pupil = circles[0][0] pupil_diameter = pupil[2] * 2 dilation_score = min(1.0, pupil_diameter / 25.0) return dilation_score return 0.5 def _detect_eyelid_drooping(self, landmarks: np.ndarray) -> float: """ 检测眼睑下垂程度 酒精会导致眼睑肌肉松弛,表现为下垂。 论文方法: 1. 计算眼睛开度(上下眼睑距离) 2. 与正常值对比 """ left_eye = landmarks[36:42] left_upper = landmarks[37:39].mean(axis=0) left_lower = landmarks[40:42].mean(axis=0) left_openness = np.linalg.norm(left_upper - left_lower) right_eye = landmarks[42:48] right_upper = landmarks[43:45].mean(axis=0) right_lower = landmarks[46:48].mean(axis=0) right_openness = np.linalg.norm(right_upper - right_lower) avg_openness = (left_openness + right_openness) / 2 drooping_score = max(0, 1 - avg_openness / 20.0) return drooping_score def _detect_facial_asymmetry(self, landmarks: np.ndarray) -> float: """ 检测面部不对称程度 酒精会影响神经控制,导致面部表情不对称。 论文方法: 1. 计算面部对称轴 2. 比较左右两侧特征点距离 """ nose_tip = landmarks[30] nose_bridge = landmarks[27] symmetry_axis = nose_tip - nose_bridge symmetry_axis = symmetry_axis / np.linalg.norm(symmetry_axis) left_corner = landmarks[36] right_corner = landmarks[45] mid_point = (left_corner + right_corner) / 2 left_dist = np.linalg.norm(left_corner - mid_point) right_dist = np.linalg.norm(right_corner - mid_point) asymmetry = abs(left_dist - right_dist) / max(left_dist, right_dist) return asymmetry def _detect_micro_expressions(self, face_roi: np.ndarray) -> float: """ 检测微表情异常 酒精会影响微表情的产生和控制。 简化实现:需要时序分析 """ return 0.3 def _classify_impairment(self, bac_estimate: float) -> str: """ 根据BAC值分类损伤等级 参考标准: - 0.00-0.05: 清醒 - 0.05-0.08: 轻度损伤 - 0.08-0.15: 中度损伤 - 0.15+: 重度损伤 """ if bac_estimate < 0.05: return 'SOBER' elif bac_estimate < 0.08: return 'MILD_IMPAIRMENT' elif bac_estimate < 0.15: return 'MODERATE_IMPAIRMENT' else: return 'SEVERE_IMPAIRMENT' def _calculate_confidence(self, features: dict) -> float: """计算检测置信度""" values = list(features.values()) std = np.std(values) confidence = 1.0 / (1.0 + std * 5) return confidence def _create_eye_mask(self, face_roi: np.ndarray, eye_points: np.ndarray) -> np.ndarray: """创建眼睛区域掩码""" mask = np.zeros(face_roi.shape[:2], dtype=np.uint8) cv2.fillPoly(mask, [eye_points.astype(int)], 255) return mask def _extract_sclera(self, face_roi: np.ndarray, eye_mask: np.ndarray) -> np.ndarray: """提取巩膜区域""" eye_region = cv2.bitwise_and(face_roi, face_roi, mask=eye_mask) gray = cv2.cvtColor(eye_region, cv2.COLOR_BGR2GRAY) _, sclera_mask = cv2.threshold(gray, 180, 255, cv2.THRESH_BINARY) sclera = cv2.bitwise_and(eye_region, eye_region, mask=sclera_mask) return sclera
if __name__ == "__main__": detector = AlcoholDetectionFromFace() test_image = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8) result = detector.estimate_bac(test_image) print("检测结果:") print(f" BAC估计: {result['bac_estimate']:.3f}") print(f" 损伤等级: {result['impairment_level']}") print(f" 置信度: {result['confidence']:.2f}") print(f" 特征详情: {result['features']}")
|