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
| import cv2 import numpy as np from typing import List, Dict, Tuple from dataclasses import dataclass from enum import Enum
class BeltStatus(Enum): """安全带状态枚举""" CORRECTLY_WORN = 0 NOT_WORN = 1 IMPROPER_POSITION = 2 BEHIND_BACK = 3 TOO_LOOSE = 4
@dataclass class BeltDetection: """安全带检测结果""" status: BeltStatus confidence: float belt_points: List[Tuple[int, int]] shoulder_position: str
class InfraredBeltDetector: """红外安全带检测器""" def __init__(self): self.ir_threshold = 200 self.body_keypoints = { 'left_shoulder': (0, 0), 'right_shoulder': (0, 0), 'chest_center': (0, 0), 'left_hip': (0, 0), 'right_hip': (0, 0) } def detect(self, ir_image: np.ndarray, body_keypoints: Dict) -> BeltDetection: """ 检测安全带状态 Args: ir_image: 红外图像 (H, W) body_keypoints: 人体关键点 Returns: detection: 安全带检测结果 """ self.body_keypoints = body_keypoints ir_enhanced = self._enhance_ir_image(ir_image) belt_mask = self._detect_belt_region(ir_enhanced) belt_skeleton = self._extract_skeleton(belt_mask) belt_points = self._fit_belt_curve(belt_skeleton) status, confidence = self._classify_belt_status(belt_points) return BeltDetection( status=status, confidence=confidence, belt_points=belt_points, shoulder_position=self._describe_shoulder_position(belt_points) ) def _enhance_ir_image(self, ir_image: np.ndarray) -> np.ndarray: """增强红外图像""" ir_enhanced = cv2.equalizeHist(ir_image) ir_enhanced = cv2.GaussianBlur(ir_enhanced, (5, 5), 0) return ir_enhanced def _detect_belt_region(self, ir_image: np.ndarray) -> np.ndarray: """检测安全带区域""" _, belt_mask = cv2.threshold(ir_image, self.ir_threshold, 255, cv2.THRESH_BINARY) kernel = np.ones((5, 5), np.uint8) belt_mask = cv2.morphologyEx(belt_mask, cv2.MORPH_CLOSE, kernel) belt_mask = cv2.morphologyEx(belt_mask, cv2.MORPH_OPEN, kernel) num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(belt_mask) min_area = 500 valid_mask = np.zeros_like(belt_mask) for i in range(1, num_labels): if stats[i, cv2.CC_STAT_AREA] > min_area: valid_mask[labels == i] = 255 return valid_mask def _extract_skeleton(self, mask: np.ndarray) -> np.ndarray: """提取骨架""" skeleton = np.zeros_like(mask, dtype=np.uint8) kernel = np.ones((3, 3), np.uint8) temp = mask.copy() while cv2.countNonZero(temp) > 0: eroded = cv2.erode(temp, kernel) skeleton_part = cv2.subtract(temp, cv2.dilate(eroded, kernel)) skeleton = cv2.bitwise_or(skeleton, skeleton_part) temp = eroded return skeleton def _fit_belt_curve(self, skeleton: np.ndarray) -> List[Tuple[int, int]]: """拟合安全带曲线""" points = np.column_stack(np.where(skeleton > 0)) if len(points) < 10: return [] points = points[np.argsort(points[:, 0])] num_points = 20 indices = np.linspace(0, len(points)-1, num_points).astype(int) sampled_points = points[indices] belt_points = [(int(p[1]), int(p[0])) for p in sampled_points] return belt_points def _classify_belt_status(self, belt_points: List[Tuple[int, int]]) -> Tuple[BeltStatus, float]: """分类安全带状态""" if len(belt_points) < 5: return BeltStatus.NOT_WORN, 0.95 left_shoulder = self.body_keypoints['left_shoulder'] right_shoulder = self.body_keypoints['right_shoulder'] chest_center = self.body_keypoints['chest_center'] belt_start = belt_points[0] belt_end = belt_points[-1] belt_crosses_shoulder = self._check_shoulder_crossing(belt_points, left_shoulder, right_shoulder) belt_near_chest = self._check_chest_proximity(belt_points, chest_center) if belt_crosses_shoulder and belt_near_chest: return BeltStatus.CORRECTLY_WORN, 0.85 elif not belt_crosses_shoulder: return BeltStatus.IMPROPER_POSITION, 0.75 elif not belt_near_chest: return BeltStatus.BEHIND_BACK, 0.70 else: return BeltStatus.TOO_LOOSE, 0.60 def _check_shoulder_crossing(self, belt_points: List[Tuple[int, int]], left_shoulder: Tuple[int, int], right_shoulder: Tuple[int, int]) -> bool: """检查安全带是否正确跨过肩膀""" belt_start = belt_points[0] dist_left = np.sqrt((belt_start[0] - left_shoulder[0])**2 + (belt_start[1] - left_shoulder[1])**2) dist_right = np.sqrt((belt_start[0] - right_shoulder[0])**2 + (belt_start[1] - right_shoulder[1])**2) return dist_left < 50 or dist_right < 50 def _check_chest_proximity(self, belt_points: List[Tuple[int, int]], chest_center: Tuple[int, int]) -> bool: """检查安全带是否靠近胸部""" mid_idx = len(belt_points) // 2 belt_mid = belt_points[mid_idx] dist = np.sqrt((belt_mid[0] - chest_center[0])**2 + (belt_mid[1] - chest_center[1])**2) return dist < 100 def _describe_shoulder_position(self, belt_points: List[Tuple[int, int]]) -> str: """描述安全带肩部位置""" if len(belt_points) < 2: return "未检测到安全带" return "安全带从左肩跨过"
if __name__ == "__main__": detector = InfraredBeltDetector() ir_image = np.zeros((480, 640), dtype=np.uint8) cv2.line(ir_image, (150, 100), (450, 400), 255, 10) body_keypoints = { 'left_shoulder': (200, 150), 'right_shoulder': (400, 150), 'chest_center': (300, 250), 'left_hip': (250, 400), 'right_hip': (350, 400) } result = detector.detect(ir_image, body_keypoints) print(f"安全带状态: {result.status.name}") print(f"置信度: {result.confidence:.2f}") print(f"肩部位置: {result.shoulder_position}") print(f"检测到的关键点数: {len(result.belt_points)}")
|