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
| import numpy as np import cv2 from typing import List, Dict, Tuple
class SeatbeltMisuseDetector: """ 安全带错误佩戴检测器 基于视觉方法检测安全带错误佩戴 """ def __init__(self, config: dict): self.belt_detector = BeltDetector( model_path=config.get('belt_model', 'yolov8_belt.onnx') ) self.pose_estimator = PoseEstimator( model_path=config.get('pose_model', 'openpose_body.onnx') ) self.misuse_classifier = MisuseClassifier() self.shoulder_angle_threshold = config.get('shoulder_angle_threshold', 30) self.loose_threshold = config.get('loose_threshold', 50) def detect(self, image: np.ndarray) -> Dict: """ 检测安全带错误佩戴 Args: image: 车内RGB或IR图像 Returns: result: { 'is_misuse': bool, 'misuse_type': str, 'confidence': float, 'belt_points': List[Tuple], 'shoulder_points': List[Tuple] } """ belt_result = self.belt_detector.detect(image) pose_result = self.pose_estimator.estimate(image) misuse_result = self._analyze_belt_position( belt_result, pose_result ) return misuse_result def _analyze_belt_position(self, belt_result: Dict, pose_result: Dict) -> Dict: """ 分析安全带与人体位置关系 判断逻辑: 1. 肩带在背后:安全带中心线在肩膀外侧 2. 肩带在手臂下:安全带中心线在腋下 3. 安全带松弛:安全带与身体距离过大 """ belt_line = belt_result['belt_line'] keypoints = pose_result['keypoints'] left_shoulder = keypoints[5][:2] right_shoulder = keypoints[6][:2] left_hip = keypoints[11][:2] right_hip = keypoints[12][:2] shoulder_y = (left_shoulder[1] + right_shoulder[1]) / 2 belt_at_shoulder = self._find_belt_point_at_y(belt_line, shoulder_y) hip_y = (left_hip[1] + right_hip[1]) / 2 belt_at_hip = self._find_belt_point_at_y(belt_line, hip_y) if belt_at_shoulder is None or belt_at_hip is None: return { 'is_misuse': True, 'misuse_type': 'BELT_NOT_DETECTED', 'confidence': 0.9 } misuse_type = 'NORMAL' shoulder_center_x = (left_shoulder[0] + right_shoulder[0]) / 2 if belt_at_shoulder[0] < left_shoulder[0] - 30: misuse_type = 'SHOULDER_BEHIND_BACK' if belt_at_shoulder[1] > left_shoulder[1] + 50: misuse_type = 'SHOULDER_UNDER_ARM' distance = self._calculate_belt_body_distance(belt_line, keypoints) if distance > self.loose_threshold: misuse_type = 'BELT_LOOSE' return { 'is_misuse': misuse_type != 'NORMAL', 'misuse_type': misuse_type, 'confidence': 0.85, 'belt_points': belt_line, 'shoulder_points': [left_shoulder, right_shoulder] } def _find_belt_point_at_y(self, belt_line: List[Tuple], y: float) -> Tuple: """找到安全带在指定y坐标的点""" for point in belt_line: if abs(point[1] - y) < 10: return point return None def _calculate_belt_body_distance(self, belt_line: List[Tuple], keypoints: np.ndarray) -> float: """计算安全带与身体的平均距离""" torso_center = [] left_shoulder = keypoints[5][:2] right_shoulder = keypoints[6][:2] left_hip = keypoints[11][:2] right_hip = keypoints[12][:2] shoulder_center = ((left_shoulder[0] + right_shoulder[0]) / 2, (left_shoulder[1] + right_shoulder[1]) / 2) hip_center = ((left_hip[0] + right_hip[0]) / 2, (left_hip[1] + right_hip[1]) / 2) total_distance = 0 for belt_point in belt_line: distance = self._point_to_line_distance( belt_point, shoulder_center, hip_center ) total_distance += distance avg_distance = total_distance / len(belt_line) if belt_line else 0 return avg_distance def _point_to_line_distance(self, point: Tuple, line_start: Tuple, line_end: Tuple) -> float: """计算点到线段的距离""" x0, y0 = point x1, y1 = line_start x2, y2 = line_end line_len = np.sqrt((x2 - x1)**2 + (y2 - y1)**2) if line_len == 0: return np.sqrt((x0 - x1)**2 + (y0 - y1)**2) distance = abs((y2 - y1) * x0 - (x2 - x1) * y0 + x2 * y1 - y2 * x1) / line_len return distance
class BeltDetector: """ 安全带检测器 使用深度学习模型检测安全带 """ def __init__(self, model_path: str): self.model = self._load_model(model_path) def detect(self, image: np.ndarray) -> Dict: """ 检测安全带 Returns: result: { 'belt_line': List[Tuple], # 安全带中心线点 'belt_mask': np.ndarray, 'confidence': float } """ detections = self.model.predict(image) belt_mask = self._extract_belt_mask(detections) belt_line = self._extract_centerline(belt_mask) return { 'belt_line': belt_line, 'belt_mask': belt_mask, 'confidence': detections['confidence'] } def _load_model(self, model_path: str): """加载模型""" pass def _extract_belt_mask(self, detections: Dict) -> np.ndarray: """提取安全带掩码""" pass def _extract_centerline(self, mask: np.ndarray) -> List[Tuple]: """提取安全带中心线""" pass
class PoseEstimator: """ 人体姿态估计器 """ def __init__(self, model_path: str): self.model = self._load_model(model_path) def estimate(self, image: np.ndarray) -> Dict: """估计人体关键点""" pass def _load_model(self, model_path: str): pass
class MisuseClassifier: """ 错误类型分类器 """ def __init__(self): self.misuse_types = [ 'NORMAL', 'SHOULDER_BEHIND_BACK', 'SHOULDER_UNDER_ARM', 'BELT_LOOSE', 'BELT_TWISTED' ] def classify(self, features: np.ndarray) -> str: """分类错误类型""" pass
if __name__ == "__main__": config = { 'shoulder_angle_threshold': 30, 'loose_threshold': 50 } detector = SeatbeltMisuseDetector(config) test_image = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8) result = detector.detect(test_image) print("安全带检测结果:") print(f" 是否错误佩戴: {result['is_misuse']}") print(f" 错误类型: {result['misuse_type']}") print(f" 置信度: {result['confidence']:.2f}")
|