using OpenCvSharp; using SopHelper.Engine.Inference; if (args.Length == 0) throw new ArgumentException("用法:YoloModelSmoke model.onnx [image.jpg]"); using var detector = new YoloDetector(); detector.Load(args[0], [], preferGpu: false); if (!detector.IsReady || detector.ClassNames.Count == 0) throw new Exception("未读取模型类别元数据"); Console.WriteLine($"PASS: 从 ONNX 元数据读取 {detector.ClassNames.Count} 个类别"); using var frame = args.Length > 1 ? Cv2.ImRead(args[1]) : new Mat(480, 640, MatType.CV_8UC3, Scalar.Black); if (frame.Empty()) throw new Exception("测试图像无法读取"); var detections = detector.Detect(frame); if (detections.Any(d => !float.IsFinite(d.Rect.X) || !float.IsFinite(d.Confidence) || d.Confidence is < 0 or > 1 || !detector.ClassNames.Contains(d.Label))) throw new Exception("检测结果的坐标、置信度或类别无效"); if (args.Length > 1 && detections.Count == 0) throw new Exception("真实样图未检出任何目标"); foreach (var d in detections) Console.WriteLine($"{d.Label}: {d.Confidence:P0} ({d.Rect.X:F0}, {d.Rect.Y:F0}, {d.Rect.W:F0}, {d.Rect.H:F0})"); Console.WriteLine($"PASS: 原生 ONNX 推理与输出解码,检出 {detections.Count} 个目标"); try { detector.Load(args[0], Enumerable.Repeat("错误类别", detector.ClassNames.Count + 1).ToArray(), preferGpu: false); throw new Exception("未拒绝错误的类别数量"); } catch (InvalidDataException) { if (detector.IsReady) throw new Exception("加载失败后保留了旧模型"); Console.WriteLine("PASS: 拒绝类别数量不匹配,加载失败后释放模型"); } detector.Load(args[0], [], preferGpu: false); detector.Load(Path.Combine(Path.GetDirectoryName(args[0])!, "missing-model.onnx"), [], preferGpu: false); if (detector.IsReady) throw new Exception("模型路径失效后仍使用旧模型"); Console.WriteLine("PASS: 切换到缺失模型时释放旧模型");