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
| import numpy as np import cv2 from typing import Tuple, List
class SeatbeltMisuseDetector: """ 安全带误用检测器 基于视觉识别安全带佩戴状态 """ def __init__(self, config: dict = None): self.config = config or { 'belt_width_range': (40, 60), 'min_belt_length': 100, 'confidence_threshold': 0.7, } self.belt_detector = self._load_detector() self.classifier = self._load_classifier() def detect(self, image: np.ndarray) -> dict: """ 检测安全带状态 Args: image: 输入图像 (H, W, 3) Returns: result: 检测结果字典 """ belt_segments = self._detect_belt_segments(image) belt_trajectory = self._extract_trajectory(belt_segments) misuse_type = self._classify_misuse(belt_trajectory) return { 'belt_detected': len(belt_segments) > 0, 'belt_trajectory': belt_trajectory, 'misuse_type': misuse_type, 'confidence': self._calc_confidence(belt_trajectory), } def _detect_belt_segments(self, image: np.ndarray) -> List[dict]: """ 检测安全带片段 使用CNN检测图像中的安全带区域 """ hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) lower_black = np.array([0, 0, 0]) upper_black = np.array([180, 255, 50]) mask = cv2.inRange(hsv, lower_black, upper_black) kernel = np.ones((5, 5), np.uint8) mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel) contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) segments = [] for contour in contours: if cv2.contourArea(contour) < 100: continue x, y, w, h = cv2.boundingRect(contour) aspect_ratio = max(w, h) / (min(w, h) + 1e-6) if aspect_ratio > 3: segments.append({ 'bbox': (x, y, w, h), 'contour': contour, 'center': (x + w//2, y + h//2), }) return segments def _extract_trajectory(self, segments: List[dict]) -> List[Tuple[int, int]]: """ 提取安全带轨迹 将检测到的片段连接成连续轨迹 """ if not segments: return [] centers = [s['center'] for s in segments] centers = sorted(centers, key=lambda p: p[1]) trajectory = [centers[0]] for i in range(1, len(centers)): dist = np.sqrt((centers[i][0] - trajectory[-1][0])**2 + (centers[i][1] - trajectory[-1][1])**2) if dist < 100: trajectory.append(centers[i]) return trajectory def _classify_misuse(self, trajectory: List[Tuple[int, int]]) -> str: """ 分类安全带误用类型 基于轨迹分析判断佩戴状态 """ if not trajectory: return 'unbuckled' if len(trajectory) < 3: return 'partial_detection' points = np.array(trajectory) slopes = [] for i in range(len(points) - 1): dy = points[i+1, 1] - points[i, 1] dx = points[i+1, 0] - points[i, 0] slope = dy / (dx + 1e-6) slopes.append(slope) slope_std = np.std(slopes) if slope_std < 0.1: return 'underarm_misuse' elif slope_std > 0.5: return 'behind_back_misuse' else: return 'normal' def _calc_confidence(self, trajectory: List[Tuple[int, int]]) -> float: """计算置信度""" if not trajectory: return 0.0 length = len(trajectory) confidence = min(length / 10.0, 1.0) return confidence def _load_detector(self): """加载检测模型(占位)""" return None def _load_classifier(self): """加载分类器(占位)""" return None
if __name__ == "__main__": detector = SeatbeltMisuseDetector() image = np.random.randint(0, 255, (720, 1280, 3), dtype=np.uint8) result = detector.detect(image) print(f"检测结果: {result}")
|