using Microsoft.ML.OnnxRuntime; using Microsoft.ML.OnnxRuntime.Tensors; using OpenCvSharp; using SopHelper.Engine.Common; using YamlDotNet.Serialization; namespace SopHelper.Engine.Inference; /// /// YOLOv8 检测(纯 ONNX Runtime,自带 DFL 解码 + NMS,不依赖 YoloDotNet)。 /// 不用 YoloDotNet 的理由:它是 GPL-3.0-only,会污染整个骨架的 MIT;且拖 SixLabors 全家。 /// public class YoloDetector : IDisposable { private InferenceSession? _session; private string[] _classNames = []; private float _confThreshold = 0.4f; private float _nmsThreshold = 0.45f; private int _inputSize = 640; public IReadOnlyList ClassNames => _classNames; /// 模型是否就绪 public bool IsReady => _session is not null; /// 实际使用的设备 public bool UsingGpu { get; private set; } public string? GpuFallbackReason { get; private set; } /// /// 加载模型。classNames 顺序必须与训练时一致(decoding 出来的类别索引直接按它取名)。 /// public void Load(string modelPath, IReadOnlyList classNames, int inputSize = 640, bool preferGpu = true) { Dispose(); UsingGpu = false; GpuFallbackReason = null; if (!File.Exists(modelPath)) return; _classNames = classNames.ToArray(); _inputSize = inputSize; if (preferGpu) { try { using var options = Options(true); _session = new InferenceSession(modelPath, options); UsingGpu = true; } catch (Exception ex) { GpuFallbackReason = ex.Message; } } try { if (_session is null) { using var cpuOptions = Options(false); _session = new InferenceSession(modelPath, cpuOptions); UsingGpu = false; } var metadata = _session.ModelMetadata.CustomMetadataMap; if (metadata.TryGetValue("names", out var names)) { var labels = new DeserializerBuilder().Build().Deserialize>(names); if (labels is not null && labels.Count > 0) { if (!labels.Keys.Order().SequenceEqual(Enumerable.Range(0, labels.Count))) throw new InvalidDataException("模型类别索引必须从 0 连续编号"); if (_classNames.Length == 0) _classNames = labels.OrderBy(p => p.Key).Select(p => p.Value).ToArray(); else if (_classNames.Length != labels.Count) throw new InvalidDataException($"模型包含 {labels.Count} 个类别,配方却配置了 {_classNames.Length} 个,请使用与模型一致的类别表"); } } if (_classNames.Length == 0) throw new InvalidDataException("模型没有类别名称,请填写类别表或使用含 names 元数据的 ONNX"); } catch { Dispose(); throw; } } /// /// 阈值 /// public void SetThresholds(float conf, float nms) { _confThreshold = conf; _nmsThreshold = nms; } /// /// 推理一帧(BGR) /// public List Detect(Mat bgr) { var list = new List(); if (!IsReady) return list; // letterbox:保持长宽比缩放,边缘补灰 var inputSize = _inputSize; var scale = Math.Min((double)inputSize / bgr.Width, (double)inputSize / bgr.Height); var newW = (int)Math.Round(bgr.Width * scale); var newH = (int)Math.Round(bgr.Height * scale); var padX = (inputSize - newW) / 2; var padY = (inputSize - newH) / 2; using var rgb = new Mat(); Cv2.CvtColor(bgr, rgb, ColorConversionCodes.BGR2RGB); using var resized = new Mat(); Cv2.Resize(rgb, resized, new Size(newW, newH)); using var canvas = new Mat(inputSize, inputSize, MatType.CV_8UC3, new Scalar(114, 114, 114)); using (var roi = new Mat(canvas, new Rect(padX, padY, newW, newH))) { resized.CopyTo(roi); } var tensor = new DenseTensor([1, 3, inputSize, inputSize]); for (var y = 0; y < inputSize; y++) { for (var x = 0; x < inputSize; x++) { var px = canvas.At(y, x); tensor[0, 0, y, x] = px.Item0 / 255f; tensor[0, 1, y, x] = px.Item1 / 255f; tensor[0, 2, y, x] = px.Item2 / 255f; } } var inputs = new List { NamedOnnxValue.CreateFromTensor(InputName(), tensor) }; using var results = _session!.Run(inputs); var output = results.FirstOrDefault(); if (output is null) return list; var t = output.AsTensor(); if (t is null) return list; // 标准 YOLOv8 / YOLO11 导出:[1, 4+nc, anchors]。 // 实测(yolo11n.onnx,api.github.com 取的 YoloSharp 那份):前 4 通道是**已解码的 // cx,cy,w,h**(letterbox 空间像素,取值范围 3~637),DFL 已烘焙进图, // 再跑一次 16-bin 期望就是乱值。 var decoded = t.Dimensions.Length == 3 && t.Dimensions[1] == 4 + _classNames.Length; // 实测(yolo11n.onnx,YoloSharp 那份)类别块 min=0、max=0.61、8.8% 恰好为 0 // → sigmoid 已烘进图里,类别通道本身就是概率;官方标准导出才是 logits(含大量负值)。 // 判错会把背景 0.0 抬成 0.5 越过阈值——每帧两千多个框就是这么来的。 var candidates = new List(); if (decoded) { var isLogit = ClassChannelsAreLogits(t, 4); var anchorCount = t.Dimensions[2]; for (var a = 0; a < anchorCount; a++) { var best = 0; var bestRaw = float.MinValue; for (var c = 0; c < _classNames.Length; c++) { var raw = t[0, 4 + c, a]; if (raw > bestRaw) { bestRaw = raw; best = c; } } var score = isLogit ? Sigmoid(bestRaw) : bestRaw; if (score < _confThreshold) continue; // 实测:前 4 通道 = cx,cy,w,h(letterbox 空间像素),DFL 已烘焙,直接用 var cx = t[0, 0, a]; var cy = t[0, 1, a]; var bw = t[0, 2, a]; var bh = t[0, 3, a]; // letterbox → 原图 candidates.Add(new Detection { Label = _classNames[best], Confidence = score, Rect = new DetRect( (float)((cx - bw / 2 - padX) / scale), (float)((cy - bh / 2 - padY) / scale), (float)(bw / scale), (float)(bh / scale)), }); } } else if (t.Dimensions.Length == 3 && t.Dimensions[1] == 64 + _classNames.Length) { // 未烘焙 DFL 的导出:[1, 4×16 + nc, anchors],前 64 行才是 4 组 16-bin 分布 var isLogit = ClassChannelsAreLogits(t, 64); var anchorCount = t.Dimensions[2]; for (var a = 0; a < anchorCount; a++) { var best = 0; var bestRaw = float.MinValue; for (var c = 0; c < _classNames.Length; c++) { var raw = t[0, 64 + c, a]; if (raw > bestRaw) { bestRaw = raw; best = c; } } var score = isLogit ? Sigmoid(bestRaw) : bestRaw; if (score < _confThreshold) continue; var (cx, cy) = DflBox(t, a, anchorCount, inputSize, scale, padX, padY, out var w, out var h); candidates.Add(new Detection { Label = _classNames[best], Confidence = score, Rect = new DetRect(cx - w / 2f, cy - h / 2f, w, h), }); } } else if (t.Dimensions.Length == 3 && t.Dimensions[2] == 6) { // YOLO26 / 端到端版:[1, N, 6] = [x1, y1, x2, y2, score, class] var n = t.Dimensions.Length >= 2 ? t.Dimensions[1] : 0; var cols = t.Dimensions.Length >= 3 ? t.Dimensions[2] : 0; if (cols < 6) return list; for (var i = 0; i < n; i++) { var score = t[0, i, 4]; if (score < _confThreshold) continue; var cls = (int)t[0, i, 5]; var x1 = (float)((t[0, i, 0] - padX) / scale); var y1 = (float)((t[0, i, 1] - padY) / scale); var x2 = (float)((t[0, i, 2] - padX) / scale); var y2 = (float)((t[0, i, 3] - padY) / scale); candidates.Add(new Detection { Label = cls >= 0 && cls < _classNames.Length ? _classNames[cls] : cls.ToString(), Confidence = score, Rect = new DetRect(x1, y1, x2 - x1, y2 - y1), }); } } else { throw new InvalidDataException($"不支持的检测输出 [{string.Join(",", t.Dimensions.ToArray())}],请检查类别表和 ONNX 导出设置"); } list.AddRange(Nms(candidates)); return list; } /// /// DFL(Distribution Focal Loss)解码:对 4 组 16 bin 做 softmax 取期望,得到边界框 /// private static (float Cx, float Cy) DflBox(Tensor t, int anchor, int anchorCount, int inputSize, double scale, int padX, int padY, out float w, out float h) { // YOLOv8 锚点是三层拼接(80×80 + 40×40 + 20×20 = 8400),不是单个方格网格。 // 按 [8,16,32] 顺序逐层行优先消耗 anchor 索引,才能还原正确的 grid 与 stride。 var (col, row, stride) = AnchorGrid(anchor, inputSize); // 锚点中心(letterbox 空间)→ 减 padding 除 scale 回原图 var anchorCx = (col + 0.5f) * stride; var anchorCy = (row + 0.5f) * stride; static float DflBin(Tensor tt, int channel, int a) { // 16 bin 的 softmax 期望 var max = float.MinValue; for (var d = 0; d < 16; d++) max = Math.Max(max, tt[0, channel, a]); var sum = 0.0; var exp = new double[16]; for (var d = 0; d < 16; d++) { exp[d] = Math.Exp(tt[0, channel, a] - max); sum += exp[d]; } var expected = 0.0; for (var d = 0; d < 16; d++) expected += d * (exp[d] / sum); return (float)expected; } var lt = DflBin(t, 0, anchor); var tp = DflBin(t, 1, anchor); var rb = DflBin(t, 2, anchor); var db = DflBin(t, 3, anchor); // DFL 距离以"特征图 stride"为单位,先在 letterbox 空间算出四边,再统一映射回原图 var leftIn = anchorCx - lt * stride; var topIn = anchorCy - tp * stride; var rightIn = anchorCx + rb * stride; var bottomIn = anchorCy + db * stride; var left = (float)((leftIn - padX) / scale); var top = (float)((topIn - padY) / scale); var right = (float)((rightIn - padX) / scale); var bottom = (float)((bottomIn - padY) / scale); w = right - left; h = bottom - top; return ((left + right) / 2f, (top + bottom) / 2f); } /// /// 类别通道是 logits,必须先过 sigmoid 才能和置信度阈值比 /// (之前 conf=68 那种数就是因为漏了这步,直接把 logits 当概率) /// private static float Sigmoid(float x) => (float)(1.0 / (1.0 + Math.Exp(-x))); /// /// 把拼接后的锚点索引还原为 (列, 行, stride)。 /// YOLOv8 检测头输出是 P3/P4/P5 三层按 [8,16,32] 顺序拼接,每层内部行优先。 /// private static (int Col, int Row, int Stride) AnchorGrid(int anchor, int inputSize) { int[] strides = [8, 16, 32]; foreach (var stride in strides) { var grid = inputSize / stride; var count = grid * grid; if (anchor >= count) { anchor -= count; continue; } return (anchor % grid, anchor / grid, stride); } // 索引超出总锚点数(理论上不会走到) return (0, 0, strides[0]); } /// /// 类别块是 logits(要 sigmoid)还是已烘好的概率(不能再见 sigmoid): /// 只看类别块自己有没有负值(坐标行在暗帧上会出负值,不能拿来当判据)。 /// private bool ClassChannelsAreLogits(Tensor t, int classStart) { var anchors = t.Dimensions[2]; for (var a = 0; a < anchors; a++) { for (var c = 0; c < _classNames.Length; c++) if (t[0, classStart + c, a] < 0f) return true; } return false; } /// /// NMS /// private List Nms(List list) { if (list.Count == 0) return list; var keep = new List(); foreach (var group in list.GroupBy(d => d.Label)) { var sorted = group.OrderByDescending(d => d.Confidence).ToList(); while (sorted.Count > 0) { var best = sorted[0]; keep.Add(best); sorted.RemoveAt(0); sorted = sorted.Where(d => IoU(best.Rect, d.Rect) <= _nmsThreshold).ToList(); } } return keep; } private static float IoU(DetRect a, DetRect b) { var x1 = Math.Max(a.X, b.X); var y1 = Math.Max(a.Y, b.Y); var x2 = Math.Min(a.Right, b.Right); var y2 = Math.Min(a.Bottom, b.Bottom); var inter = Math.Max(0, x2 - x1) * Math.Max(0, y2 - y1); var union = a.W * a.H + b.W * b.H - inter; return union <= 0 ? 0 : inter / union; } /// /// 取模型真实输入节点名(不写死 "input",各家导出不一样) /// private string InputName() { try { // InputMetadata 是字典,键就是节点名 return _session!.InputMetadata.Keys.First(); } catch { return "images"; } } private static SessionOptions Options(bool cuda) { var o = new SessionOptions { GraphOptimizationLevel = GraphOptimizationLevel.ORT_ENABLE_ALL, }; try { if (cuda) { CudaRuntime.Prepare(); o.AppendExecutionProvider_CUDA(0); } } catch { o.Dispose(); throw; } return o; } /// public void Dispose() { _session?.Dispose(); _session = null; UsingGpu = false; } }