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
| import numpy as np import cv2 from typing import Tuple, List, Dict
class InfraredSeatbeltDetector: """红外安全带检测器""" def __init__(self): self.ir_wavelength_range = (850, 940) self.detection_thresholds = { 'min_brightness': 150, 'min_area': 100, 'aspect_ratio': (0.05, 0.3) } self.ir_color_range = { 'lower': np.array([200, 200, 200]), 'upper': np.array([255, 255, 255]) } def detect_seatbelt_status(self, ir_image: np.ndarray, rgb_image: np.ndarray) -> Dict: """ 检测安全带状态 Args: ir_image: 红外图像(含红外补光) rgb_image: RGB图像(用于人体检测) Returns: status: 安全带状态 """ person_roi = self._detect_person(rgb_image) if person_roi is None: return {'status': 'no_person', 'confidence': 1.0} seatbelt_mask = self._detect_ir_seatbelt(ir_image, person_roi) seatbelt_path = self._extract_seatbelt_path(seatbelt_mask) status = self._classify_seatbelt_status(seatbelt_path, person_roi) return status def _detect_person(self, rgb_image: np.ndarray) -> np.ndarray: """检测人体区域""" h, w = rgb_image.shape[:2] roi = rgb_image[h//4:3*h//4, w//4:3*w//4] return roi def _detect_ir_seatbelt(self, ir_image: np.ndarray, person_roi: np.ndarray) -> np.ndarray: """ 检测红外安全带 Args: ir_image: 红外图像 person_roi: 人体区域 Returns: mask: 安全带掩码 """ ir_enhanced = cv2.equalizeHist(ir_image) _, mask = cv2.threshold( ir_enhanced, self.detection_thresholds['min_brightness'], 255, cv2.THRESH_BINARY ) kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5)) mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel) mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel) contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) valid_contours = [] for contour in contours: area = cv2.contourArea(contour) if area > self.detection_thresholds['min_area']: x, y, w, h = cv2.boundingRect(contour) aspect_ratio = w / h if h > 0 else 0 if self.detection_thresholds['aspect_ratio'][0] < aspect_ratio < self.detection_thresholds['aspect_ratio'][1]: valid_contours.append(contour) mask_filtered = np.zeros_like(mask) cv2.drawContours(mask_filtered, valid_contours, -1, 255, -1) return mask_filtered def _extract_seatbelt_path(self, mask: np.ndarray) -> List[Tuple[int, int]]: """提取安全带路径""" skeleton = self._skeletonize(mask) points = np.column_stack(np.where(skeleton > 0)) points = points[np.argsort(points[:, 0])] return points.tolist() def _skeletonize(self, mask: np.ndarray) -> np.ndarray: """骨架化""" skeleton = np.zeros_like(mask) kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (3, 3)) while True: eroded = cv2.erode(mask, kernel) temp = cv2.dilate(eroded, kernel) temp = mask - temp skeleton = cv2.bitwise_or(skeleton, temp) mask = eroded.copy() if cv2.countNonZero(mask) == 0: break return skeleton def _classify_seatbelt_status(self, path: List[Tuple[int, int]], person_roi: np.ndarray) -> Dict: """ 分类安全带状态 Args: path: 安全带路径点 person_roi: 人体区域 Returns: status: 状态判定 """ if len(path) < 10: return { 'status': 'not_worn', 'confidence': 0.9, 'description': '未检测到安全带' } path_array = np.array(path) start_y = path_array[0, 0] end_y = path_array[-1, 0] if len(path_array) > 1: delta_x = path_array[-1, 1] - path_array[0, 1] delta_y = path_array[-1, 0] - path_array[0, 0] angle = np.arctan2(delta_y, delta_x) * 180 / np.pi else: angle = 0 if 30 < angle < 70 and start_y < end_y: return { 'status': 'correctly_worn', 'confidence': 0.85, 'description': '正确佩戴', 'angle': angle } elif angle > 0: return { 'status': 'misuse', 'confidence': 0.75, 'description': '安全带误用(位置错误)', 'angle': angle } else: return { 'status': 'not_worn', 'confidence': 0.6, 'description': '安全带未佩戴或检测失败' }
class SeatbeltMisuseDetector: """安全带误用检测器""" def __init__(self): self.misuse_types = { 'behind_back': '安全带系在背后', 'under_arm': '安全带从腋下穿过', 'too_loose': '安全带过松', 'twisted': '安全带扭曲', 'multiple_passengers': '多人共用一条安全带' } def detect_misuse(self, seatbelt_path: List[Tuple[int, int]], body_landmarks: Dict) -> Dict: """ 检测安全带误用 Args: seatbelt_path: 安全带路径 body_landmarks: 人体关键点 Returns: misuse_result: 误用检测结果 """ if len(seatbelt_path) < 5: return {'misuse': False, 'type': None} path_array = np.array(seatbelt_path) under_arm_misuse = self._detect_under_arm(path_array, body_landmarks) behind_back_misuse = self._detect_behind_back(path_array, body_landmarks) loose_misuse = self._detect_loose_seatbelt(path_array, body_landmarks) if under_arm_misuse['detected']: return { 'misuse': True, 'type': 'under_arm', 'description': self.misuse_types['under_arm'], 'confidence': under_arm_misuse['confidence'] } if behind_back_misuse['detected']: return { 'misuse': True, 'type': 'behind_back', 'description': self.misuse_types['behind_back'], 'confidence': behind_back_misuse['confidence'] } if loose_misuse['detected']: return { 'misuse': True, 'type': 'too_loose', 'description': self.misuse_types['too_loose'], 'confidence': loose_misuse['confidence'] } return {'misuse': False, 'type': None} def _detect_under_arm(self, path: np.ndarray, landmarks: Dict) -> Dict: """检测腋下误用""" return {'detected': False, 'confidence': 0.0} def _detect_behind_back(self, path: np.ndarray, landmarks: Dict) -> Dict: """检测背后误用""" return {'detected': False, 'confidence': 0.0} def _detect_loose_seatbelt(self, path: np.ndarray, landmarks: Dict) -> Dict: """检测过松""" path_length = np.sum(np.sqrt(np.sum(np.diff(path, axis=0)**2, axis=1))) straight_distance = np.sqrt(np.sum((path[-1] - path[0])**2)) curvature = path_length / straight_distance if straight_distance > 0 else 1.0 if curvature > 1.5: return {'detected': True, 'confidence': 0.7} return {'detected': False, 'confidence': 0.0}
if __name__ == "__main__": detector = InfraredSeatbeltDetector() misuse_detector = SeatbeltMisuseDetector() ir_image = np.random.randint(0, 100, (256, 256), dtype=np.uint8) for i in range(50, 200): ir_image[i, int(100 + i * 0.3)] = 255 rgb_image = np.random.randint(0, 255, (256, 256, 3), dtype=np.uint8) result = detector.detect_seatbelt_status(ir_image, rgb_image) print(f"安全带状态: {result['status']}") print(f"置信度: {result['confidence']}") print(f"描述: {result['description']}") if 'angle' in result: print(f"角度: {result['angle']:.1f}度")
|