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
| import numpy as np import cv2 from typing import Tuple, Optional, List from dataclasses import dataclass from enum import Enum
class OccupantStatus(Enum): """乘员状态""" EMPTY = "empty" OCCUPIED = "occupied" CHILD_SEAT = "child_seat" UNKNOWN = "unknown"
@dataclass class SeatInfo: """座椅信息""" row: int position: int status: OccupantStatus confidence: float bbox: Tuple[int, int, int, int]
class RearOccupantDetector: """ 后排乘员检测器 使用目标检测模型检测后排座椅区域的人员 支持 YOLOv8/YOLOv11 等 ONNX 模型 """ SEAT_ZONES = { (2, 1): (0.0, 0.3, 0.33, 0.9), (2, 2): (0.33, 0.3, 0.67, 0.9), (2, 3): (0.67, 0.3, 1.0, 0.9), } def __init__(self, model_path: str = "yolov8n.onnx", conf_threshold: float = 0.5, nms_threshold: float = 0.45, frame_width: int = 1280, frame_height: int = 720): """ 初始化后排乘员检测器 Args: model_path: ONNX 模型路径 conf_threshold: 置信度阈值 nms_threshold: NMS 阈值 frame_width: 图像宽度 frame_height: 图像高度 """ self.conf_threshold = conf_threshold self.nms_threshold = nms_threshold self.frame_width = frame_width self.frame_height = frame_height self.session = cv2.dnn.readNetFromONNX(model_path) self.session.setPreferableBackend(cv2.dnn.DNN_BACKEND_OPENCV) self.session.setPreferableTarget(cv2.dnn.DNN_TARGET_CPU) self.class_names = ['person', 'bicycle', 'car', ...] self.person_class_id = 0 def detect(self, frame: np.ndarray) -> List[SeatInfo]: """ 检测后排座椅乘员 Args: frame: BGR 图像,shape=(H, W, 3) Returns: 座椅信息列表 """ h, w = frame.shape[:2] blob = cv2.dnn.blobFromImage( frame, 1/255.0, (640, 640), swapRB=True, crop=False ) self.session.setInput(blob) outputs = self.session.forward() detections = self._postprocess(outputs, w, h) seat_infos = self._assign_to_seats(detections, w, h) return seat_infos def _postprocess(self, outputs: np.ndarray, frame_w: int, frame_h: int) -> List[dict]: """ 后处理:解析检测结果 Args: outputs: 模型输出 frame_w: 图像宽度 frame_h: 图像高度 Returns: 检测结果列表 """ detections = [] outputs = outputs[0].transpose(1, 0) for detection in outputs: x, y, w, h = detection[:4] class_scores = detection[4:] class_id = np.argmax(class_scores) confidence = class_scores[class_id] if class_id != self.person_class_id: continue if confidence < self.conf_threshold: continue x1 = int((x - w/2) * frame_w / 640) y1 = int((y - h/2) * frame_h / 640) x2 = int((x + w/2) * frame_w / 640) y2 = int((y + h/2) * frame_h / 640) detections.append({ 'bbox': (x1, y1, x2, y2), 'confidence': confidence, 'class_id': class_id }) return detections def _assign_to_seats(self, detections: List[dict], frame_w: int, frame_h: int) -> List[SeatInfo]: """ 将检测结果分配到座椅区域 Args: detections: 检测结果列表 frame_w: 图像宽度 frame_h: 图像高度 Returns: 座椅信息列表 """ seat_infos = [] for (row, position), zone in self.SEAT_ZONES.items(): x_min, y_min, x_max, y_max = zone seat_x1 = int(x_min * frame_w) seat_y1 = int(y_min * frame_h) seat_x2 = int(x_max * frame_w) seat_y2 = int(y_max * frame_h) best_detection = None best_iou = 0.0 for det in detections: iou = self._calculate_iou( det['bbox'], (seat_x1, seat_y1, seat_x2, seat_y2) ) if iou > best_iou: best_iou = iou best_detection = det if best_detection is not None and best_iou > 0.1: status = OccupantStatus.OCCUPIED confidence = best_detection['confidence'] bbox = best_detection['bbox'] else: status = OccupantStatus.EMPTY confidence = 0.9 bbox = (seat_x1, seat_y1, seat_x2, seat_y2) seat_info = SeatInfo( row=row, position=position, status=status, confidence=confidence, bbox=bbox ) seat_infos.append(seat_info) return seat_infos def _calculate_iou(self, box1: Tuple, box2: Tuple) -> float: """计算两个边界框的 IoU""" x1 = max(box1[0], box2[0]) y1 = max(box1[1], box2[1]) x2 = min(box1[2], box2[2]) y2 = min(box1[3], box2[3]) if x2 <= x1 or y2 <= y1: return 0.0 intersection = (x2 - x1) * (y2 - y1) area1 = (box1[2] - box1[0]) * (box1[3] - box1[1]) area2 = (box2[2] - box2[0]) * (box2[3] - box2[1]) union = area1 + area2 - intersection return intersection / union if union > 0 else 0.0
if __name__ == "__main__": detector = RearOccupantDetector(model_path="yolov8n.onnx") cap = cv2.VideoCapture(0) print("按 'q' 退出") while True: ret, frame = cap.read() if not ret: break seat_infos = detector.detect(frame) for seat in seat_infos: x1, y1, x2, y2 = seat.bbox color = (0, 255, 0) if seat.status == OccupantStatus.OCCUPIED else (128, 128, 128) cv2.rectangle(frame, (x1, y1), (x2, y2), color, 2) label = f"R{seat.row}P{seat.position}: {seat.status.value}" cv2.putText(frame, label, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2) cv2.imshow("Rear Occupant Detection", frame) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows()
|