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 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
| import numpy as np import onnxruntime as ort from ast import literal_eval from typing import List, Dict, Tuple, Callable, Optional, Union, Any
class Detection: """表示目标检测中的单个检测结果""" def __init__(self, class_id: int, class_name: str, confidence: float, x_center: float, y_center: float, width: float, height: float, image_scale_x: float = 1, image_scale_y: float = 1): """ 初始化检测结果对象
参数: class_id: 类别ID class_name: 类别名称 confidence: 置信度分数 x_center: 边界框中心x坐标 y_center: 边界框中心y坐标 width: 边界框宽度 height: 边界框高度 image_scale_x: x轴缩放因子,默认为1 image_scale_y: y轴缩放因子,默认为1 """ self.class_id = class_id self.class_name = class_name self.confidence = confidence scaled_center = (x_center * image_scale_x, y_center * image_scale_y) scaled_size = (width * image_scale_x, height * image_scale_y) half_size = (scaled_size[0] * 0.5, scaled_size[1] * 0.5) self.x1, self.y1 = scaled_center[0] - half_size[0], scaled_center[1] - half_size[1] self.x2, self.y2 = scaled_center[0] + half_size[0], scaled_center[1] + half_size[1] self.area = scaled_size[0] * scaled_size[1]
def __str__(self) -> str: """返回检测结果的字符串表示""" return f"{self.class_name} ({self.confidence:.2f}) [{self.x1:.1f}, {self.y1:.1f}, {self.x2:.1f}, {self.y2:.1f}]"
class ONNXYOLODetector : """ONNX模型的封装,提供简单的接口进行目标检测""" PROVIDER_PRIORITY = ["CUDAExecutionProvider", "CoreMLExecutionProvider", "CPUExecutionProvider"] @staticmethod def _calculate_iou(box1: Detection, box2: Detection) -> float: """ 计算两个检测框之间的IoU(交并比)
参数: box1: 第一个检测框 box2: 第二个检测框
返回: 计算得到的IoU值,范围为[0,1] """ x1 = max(box1.x1, box2.x1) y1 = max(box1.y1, box2.y1) x2 = min(box1.x2, box2.x2) y2 = min(box1.y2, box2.y2) inter_w, inter_h = max(0, x2 - x1), max(0, y2 - y1) if inter_w <= 0 or inter_h <= 0: return 0 intersection_area = inter_w * inter_h union_area = box1.area + box2.area - intersection_area if union_area <= 0: return 0 return intersection_area / union_area def __init__(self, model_path: str, confidence_threshold: float = 0.35, nms_iou_threshold: float = 0.45, class_filter: Optional[Callable[[int, str], bool]] = None, use_gpu: bool = True): """ 初始化YOLO目标检测器
参数: model_path: ONNX模型文件路径 confidence_threshold: 最小置信度阈值,用于过滤检测结果 nms_iou_threshold: 非极大值抑制的IoU阈值 class_filter: 用于过滤有效类别的函数,接收类别索引(int)和标签(str),返回布尔值 use_gpu: 是否使用GPU进行推理,默认为True """ self.model_path = model_path self.confidence_threshold = confidence_threshold self.nms_iou_threshold = nms_iou_threshold self.class_filter = class_filter or (lambda class_id, class_name: True) self._initialize_model(model_path, use_gpu) def _initialize_model(self, model_path: str, use_gpu: bool) -> None: """ 初始化ONNX模型 参数: model_path: ONNX模型文件路径 use_gpu: 是否使用GPU """ providers = self.PROVIDER_PRIORITY if use_gpu else ["CPUExecutionProvider"] self.session = ort.InferenceSession(model_path, providers=providers) self.input_name = self.session.get_inputs()[0].name self.output_name = self.session.get_outputs()[0].name self._load_metadata() def _load_metadata(self) -> None: """从ONNX模型加载元数据信息""" meta = self.session.get_modelmeta() custom_metadata = meta.custom_metadata_map if "imgsz" not in custom_metadata: raise ValueError("ONNX模型缺少'imgsz'元数据") self.input_size = np.array(literal_eval(custom_metadata['imgsz'])) if "names" not in custom_metadata: raise ValueError("ONNX模型缺少'names'元数据") self.class_names = literal_eval(custom_metadata["names"])
def _validate_input(self, image: np.ndarray) -> None: """ 验证输入图像格式 参数: image: 输入图像 引发: TypeError: 如果图像不是uint8类型的numpy数组 ValueError: 如果图像不是HxWxC格式的RGB图像 """ image = np.squeeze(image) if not (isinstance(image, np.ndarray) and image.dtype == np.uint8): raise TypeError("输入必须是uint8类型的numpy数组") shape = image.shape if not (len(shape) == 3 and shape[-1] == 3): raise ValueError("输入必须是HxWxC格式的RGB图像")
def _preprocess_image(self, image: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: """ 预处理输入图像
参数: image: 原始图像,HxWxC格式(高度x宽度x通道)
返回: 预处理后的图像和原始图像到预处理图像的缩放因子 """ import cv2 original_shape = np.array(image.shape[:2]) resized_image = cv2.resize(image, tuple(self.input_size)) normalized_image = resized_image.astype(np.float32) / 255.0 chw_image = np.transpose(normalized_image, (2, 0, 1)) batched_image = np.expand_dims(chw_image, axis=0) scale_factors = original_shape / self.input_size return batched_image, scale_factors
def _run_inference(self, processed_image: np.ndarray) -> np.ndarray: """ 执行模型推理 参数: processed_image: 预处理后的图像 返回: 模型的原始输出 引发: RuntimeError: 如果推理失败 """ outputs = self.session.run([self.output_name], {self.input_name: processed_image}) if len(outputs) != 1: raise RuntimeError("ONNX模型推理失败") return outputs[0]
def _extract_prediction_data(self, predictions: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: """ 从预测中提取边界框数据和类别分数 参数: predictions: 模型的原始输出 返回: 边界框数据和类别分数 """ predictions = np.squeeze(predictions) n_classes = len(self.class_names) expected_first_dim = 4 + n_classes if predictions.shape[0] != expected_first_dim: raise ValueError(f"输出形状不匹配:预期第一维为{expected_first_dim},实际为{predictions.shape[0]}") bbox_data = predictions[:4, :] class_scores = predictions[4:, :] return bbox_data, class_scores
def _apply_nms(self, bbox_data: np.ndarray, class_scores: np.ndarray, scale_factors: np.ndarray) -> List[Detection]: """ 应用非极大值抑制算法 参数: bbox_data: 边界框数据 (x_center, y_center, width, height) class_scores: 类别分数 scale_factors: 缩放因子 返回: 检测结果列表 """ n_det = bbox_data.shape[1] if n_det <= 0: return [] class_ids = np.argmax(class_scores, axis=0) max_scores = np.take_along_axis(class_scores, class_ids[None, :], axis=0).squeeze() sorted_indices = np.argsort(max_scores)[::-1] valid_detections = [] suppressed_mask = np.zeros(n_det, dtype=bool) for i, idx in enumerate(sorted_indices): class_id = class_ids[idx] class_name = self.class_names[class_id] confidence = max_scores[idx] if (suppressed_mask[idx] or not self.class_filter(class_id, class_name) or confidence < self.confidence_threshold): continue detection = Detection( class_id, class_name, confidence, *bbox_data[:4, idx], scale_factors[1], scale_factors[0] ) valid_detections.append(detection) self._suppress_overlapping_detections( sorted_indices[i+1:], bbox_data, class_ids, max_scores, suppressed_mask, scale_factors, detection ) return valid_detections def _suppress_overlapping_detections(self, indices: np.ndarray, bbox_data: np.ndarray, class_ids: np.ndarray, max_scores: np.ndarray, suppressed_mask: np.ndarray, scale_factors: np.ndarray, reference_detection: Detection) -> None: """ 抑制与参考检测框重叠的检测框 参数: indices: 要检查的检测索引 bbox_data: 边界框数据 class_ids: 每个检测的类别ID max_scores: 每个检测的最大置信度 suppressed_mask: 被抑制的检测掩码 scale_factors: 缩放因子 reference_detection: 参考检测框 """ for idx in indices: class_id = class_ids[idx] class_name = self.class_names[class_id] confidence = max_scores[idx] if (suppressed_mask[idx] or not self.class_filter(class_id, class_name) or confidence < self.confidence_threshold): continue detection = Detection( class_id, class_name, confidence, *bbox_data[:4, idx], scale_factors[1], scale_factors[0] ) iou = self._calculate_iou(reference_detection, detection) if iou > self.nms_iou_threshold: suppressed_mask[idx] = True def _process_predictions(self, raw_predictions: np.ndarray, scale_factors: np.ndarray) -> List[Detection]: """ 处理原始预测结果转换为检测对象 参数: raw_predictions: 模型的原始输出 scale_factors: 缩放因子 返回: 检测结果列表 """ bbox_data, class_scores = self._extract_prediction_data(raw_predictions) detections = self._apply_nms(bbox_data, class_scores, scale_factors) return detections def get_class_mapping(self) -> Dict[int, str]: """ 获取类别ID到名称的映射 返回: 包含所有可检测类别的{id: name}字典 """ return {i: name for i, name in enumerate(self.class_names)}
def detect(self, image: np.ndarray) -> List[Detection]: """ 对图像执行目标检测 参数: image: 输入图像,HxWxC格式(高度x宽度x通道) 返回: 检测结果列表 """ self._validate_input(image) processed_image, scale_factors = self._preprocess_image(image) raw_predictions = self._run_inference(processed_image) detections = self._process_predictions(raw_predictions, scale_factors) return detections
|