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
| """ 视觉安全带误用检测系统
功能: 1. 安全带分割 2. 关键点检测 3. 几何分析 4. 误用分类 """
import numpy as np import cv2 from typing import List, Tuple, Dict from dataclasses import dataclass from enum import Enum
class MisuseType(Enum): """误用类型""" NORMAL = "normal" SHOULDER_SLIP = "shoulder_slip" LAP_TOO_LOOSE = "lap_too_loose" LAP_WRONG_POS = "lap_wrong_pos" BEHIND_BUCKLE = "behind_buckle" CHILD_MISUSE = "child_misuse"
@dataclass class BeltKeypoints: """安全带关键点""" shoulder_point: Tuple[float, float] chest_point: Tuple[float, float] lap_left: Tuple[float, float] lap_right: Tuple[float, float] buckle: Tuple[float, float]
class SeatbeltMisuseDetector: """ 安全带误用检测器 方法: 1. 安全带分割(语义分割网络) 2. 关键点检测(回归网络) 3. 几何分析(规则引擎) """ THRESHOLDS = { 'shoulder_slip_angle': 30, 'lap_loose_distance': 0.05, 'lap_wrong_y': 0.3 } def __init__(self, model_path: str): """ 初始化 Args: model_path: 模型路径 """ self.segmentation_net = cv2.dnn.readNetFromONNX(f"{model_path}/belt_seg.onnx") self.keypoint_net = cv2.dnn.readNetFromONNX(f"{model_path}/belt_kpts.onnx") def detect(self, image: np.ndarray) -> Dict: """ 检测安全带误用 Args: image: 输入图像 (H, W, 3) Returns: result: { 'misuse_type': MisuseType, 'keypoints': BeltKeypoints, 'confidence': float } """ belt_mask = self._segment_belt(image) keypoints = self._detect_keypoints(image, belt_mask) misuse_type = self._analyze_misuse(keypoints) return { 'misuse_type': misuse_type, 'keypoints': keypoints, 'confidence': 0.95 } def _segment_belt(self, image: np.ndarray) -> np.ndarray: """ 安全带分割 Returns: mask: 安全带掩码 (H, W) """ blob = cv2.dnn.blobFromImage(image, 1/255.0, (224, 224), (0, 0, 0), swapRB=True) self.segmentation_net.setInput(blob) output = self.segmentation_net.forward() mask = output.squeeze().argmax(axis=0) mask = cv2.resize(mask, (image.shape[1], image.shape[0])) return mask.astype(np.uint8) def _detect_keypoints(self, image: np.ndarray, mask: np.ndarray) -> BeltKeypoints: """ 安全带关键点检测 Returns: keypoints: 安全带关键点 """ masked = cv2.bitwise_and(image, image, mask=mask) blob = cv2.dnn.blobFromImage(masked, 1/255.0, (224, 224)) self.keypoint_net.setInput(blob) output = self.keypoint_net.forward() kpts = output.reshape(-1, 2) kpts[:, 0] *= image.shape[1] kpts[:, 1] *= image.shape[0] keypoints = BeltKeypoints( shoulder_point=(kpts[0, 0], kpts[0, 1]), chest_point=(kpts[1, 0], kpts[1, 1]), lap_left=(kpts[2, 0], kpts[2, 1]), lap_right=(kpts[3, 0], kpts[3, 1]), buckle=(kpts[4, 0], kpts[4, 1]) ) return keypoints def _analyze_misuse(self, kpts: BeltKeypoints) -> MisuseType: """ 几何分析判断误用 Returns: misuse_type: 误用类型 """ shoulder_angle = self._calculate_angle( kpts.shoulder_point, kpts.chest_point ) if shoulder_angle > self.THRESHOLDS['shoulder_slip_angle']: return MisuseType.SHOULDER_SLIP lap_width = np.linalg.norm( np.array(kpts.lap_left) - np.array(kpts.lap_right) ) image_width = 640 relative_width = lap_width / image_width if relative_width > self.THRESHOLDS['lap_loose_distance']: return MisuseType.LAP_TOO_LOOSE lap_y = (kpts.lap_left[1] + kpts.lap_right[1]) / 2 relative_y = lap_y / 480 if relative_y < self.THRESHOLDS['lap_wrong_y']: return MisuseType.LAP_WRONG_POS return MisuseType.NORMAL def _calculate_angle(self, p1: Tuple[float, float], p2: Tuple[float, float]) -> float: """ 计算角度 Returns: angle: 角度(度) """ dx = p2[0] - p1[0] dy = p2[1] - p1[1] angle = np.arctan2(dy, dx) * 180 / np.pi return abs(angle)
class SeatbeltAlertSystem: """ 安全带误用告警系统 告警策略: 1. 车辆启动前检测 2. 视觉告警(仪表盘) 3. 听觉告警(蜂鸣) 4. 拒绝启动(严重误用) """ def __init__(self): self.detector = SeatbeltMisuseDetector(model_path="models") def check_before_start(self, image: np.ndarray) -> bool: """ 启动前检查 Returns: can_start: 是否允许启动 """ result = self.detector.detect(image) if result['misuse_type'] == MisuseType.NORMAL: print("[INFO] 安全带正常,允许启动") return True else: print(f"[WARN] 检测到安全带误用: {result['misuse_type'].value}") self._alert(result['misuse_type']) if result['misuse_type'] in [MisuseType.BEHIND_BUCKLE, MisuseType.CHILD_MISUSE]: return False else: return True def _alert(self, misuse_type: MisuseType): """发出告警""" if misuse_type == MisuseType.SHOULDER_SLIP: print("[ALERT] 肩带位置错误,请调整安全带") elif misuse_type == MisuseType.LAP_TOO_LOOSE: print("[ALERT] 腰带过松,请拉紧安全带") elif misuse_type == MisuseType.LAP_WRONG_POS: print("[ALERT] 腰带位置错误,请调整到髋骨位置") elif misuse_type == MisuseType.BEHIND_BUCKLE: print("[ALERT] 安全带位置严重错误,请重新佩戴!")
if __name__ == "__main__": alerter = SeatbeltAlertSystem() image = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8) can_start = alerter.check_before_start(image) print(f"允许启动: {can_start}")
|