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
| """ 安全带误用检测算法 符合 Euro NCAP 2026 协议要求 """
import numpy as np import cv2 from typing import Dict, Tuple, List
class SeatbeltMisuseDetector: """ 安全带误用检测器 检测三种误用类型: 1. 仅扣扣环 2. 仅腰带(斜跨在背后) 3. 全部在背后 """ def __init__(self, config: Dict): self.belt_width_range = config.get('belt_width', (15, 40)) self.confidence_threshold = config.get('confidence', 0.7) self.belt_colors = { 'black': ([0, 0, 0], [50, 50, 50]), 'gray': ([100, 100, 100], [200, 200, 200]), 'beige': ([180, 180, 150], [220, 220, 200]) } def detect_belt_path(self, frame: np.ndarray) -> Dict: """ 检测安全带路径 Args: frame: 输入图像 (H, W, 3) Returns: belt_info: 安全带信息 """ belt_mask = self._segment_belt(frame) lines = cv2.HoughLinesP( belt_mask, rho=1, theta=np.pi/180, threshold=50, minLineLength=30, maxLineGap=10 ) if lines is None: return {'detected': False, 'type': 'no_belt'} belt_segments = self._analyze_segments(lines) misuse_type = self._classify_misuse(belt_segments) return { 'detected': True, 'type': misuse_type, 'segments': belt_segments } def _segment_belt(self, frame: np.ndarray) -> np.ndarray: """安全带颜色分割""" hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) mask = np.zeros(frame.shape[:2], dtype=np.uint8) for color_name, (lower, upper) in self.belt_colors.items(): lower = np.array(lower) upper = np.array(upper) color_mask = cv2.inRange(frame, lower, upper) mask = cv2.bitwise_or(mask, color_mask) kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5)) mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel) return mask def _analyze_segments(self, lines: np.ndarray) -> List[Dict]: """分析安全带线段""" segments = [] for line in lines: x1, y1, x2, y2 = line[0] length = np.sqrt((x2-x1)**2 + (y2-y1)**2) angle = np.arctan2(y2-y1, x2-x1) * 180 / np.pi if -30 < angle < 30: segment_type = 'lap' elif 60 < abs(angle) < 120: segment_type = 'shoulder' else: segment_type = 'diagonal' segments.append({ 'start': (x1, y1), 'end': (x2, y2), 'length': length, 'angle': angle, 'type': segment_type }) return segments def _classify_misuse(self, segments: List[Dict]) -> str: """ 分类误用类型 Returns: misuse_type: 'correct' | 'buckle_only' | 'lap_only' | 'behind_back' """ if not segments: return 'buckle_only' shoulder_count = sum(1 for s in segments if s['type'] == 'shoulder') lap_count = sum(1 for s in segments if s['type'] == 'lap') diagonal_count = sum(1 for s in segments if s['type'] == 'diagonal') if diagonal_count >= 1 and lap_count >= 1: return 'correct' elif lap_count >= 1 and diagonal_count == 0: return 'lap_only' elif shoulder_count >= 1 and lap_count == 0: return 'behind_back' else: return 'unknown'
class SeatbeltWarningSystem: """ 安全带警告系统 符合 Euro NCAP 2026 警告规范 """ def __init__(self, config: Dict): self.warning_duration = config.get('warning_duration', 90) self.sound_can_dismiss = True self.visual_must_stay = True self.warning_start_time = None self.sound_dismissed = False self.misuse_corrected = False def update(self, misuse_detected: bool, misuse_type: str, current_time: float) -> Dict: """ 更新警告状态 Args: misuse_detected: 是否检测到误用 misuse_type: 误用类型 current_time: 当前时间戳 Returns: warning_state: 警告状态 """ if misuse_detected: if self.warning_start_time is None: self.warning_start_time = current_time self.sound_dismissed = False elapsed = current_time - self.warning_start_time return { 'visual_active': True, 'sound_active': not self.sound_dismissed and elapsed < self.warning_duration, 'elapsed_time': elapsed, 'can_dismiss_sound': self.sound_can_dismiss and not self.sound_dismissed } else: self.warning_start_time = None self.sound_dismissed = False return { 'visual_active': False, 'sound_active': False, 'elapsed_time': 0, 'can_dismiss_sound': False } def dismiss_sound(self): """关闭声音警告(仅一次)""" if self.sound_can_dismiss and not self.sound_dismissed: self.sound_dismissed = True return True return False
class EuroNCAP_SeatbeltTest: """Euro NCAP 安全带误用测试""" def __init__(self): self.detector = SeatbeltMisuseDetector({}) self.warning = SeatbeltWarningSystem({}) self.test_scenarios = [ { 'id': 'SM-01', 'description': '仅扣扣环,安全带未绕过身体', 'expected_detection': 'buckle_only', 'expected_warning': True, 'time_limit': 30 }, { 'id': 'SM-02', 'description': '斜跨安全带在背后,仅腰带', 'expected_detection': 'lap_only', 'expected_warning': True, 'time_limit': 30 }, { 'id': 'SM-03', 'description': '整条安全带在背后', 'expected_detection': 'behind_back', 'expected_warning': True, 'time_limit': 30 } ] def run_test(self, scenario_id: str, test_frame: np.ndarray) -> Dict: """ 运行测试场景 Args: scenario_id: 场景 ID test_frame: 测试图像 Returns: test_result: 测试结果 """ scenario = next(s for s in self.test_scenarios if s['id'] == scenario_id) detection_result = self.detector.detect_belt_path(test_frame) detected_correctly = detection_result['type'] == scenario['expected_detection'] return { 'scenario_id': scenario_id, 'description': scenario['description'], 'detected_type': detection_result['type'], 'expected_type': scenario['expected_detection'], 'passed': detected_correctly, 'detection_time': '< 30s' if detected_correctly else 'N/A' }
if __name__ == "__main__": detector = SeatbeltMisuseDetector({}) dummy_frame = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8) result = detector.detect_belt_path(dummy_frame) print(f"检测类型: {result['type']}") print(f"线段数量: {len(result.get('segments', []))}")
|