aisop/src/SopHelper.Engine/Inference/YoloDetector.cs
sophelper 061b8cd3be feat(Engine): UVC 相机 + YOLO/MediaPipe 手部 ONNX 推理 + 抽帧管线
- 不引 YoloDotNet(GPL-3.0),自带 YOLOv8 letterbox + DFL 解码 + NMS
- MediaPipe 两阶段照搬参考项目解析:palm 192 → 方形裁剪 → landmark 224
- 相机 MSMF 优先/回退 DSHOW、DSHOW 进程级串行、不重复开同一索引、取帧后不补 Sleep
- 引擎层只用自有 DetRect,不绑定 SkiaSharp/OpenCvSharp/YoloDotNet 类型
2026-11-03 00:59:24 +08:00

341 lines
10 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Microsoft.ML.OnnxRuntime;
using Microsoft.ML.OnnxRuntime.Tensors;
using OpenCvSharp;
using SopHelper.Engine.Common;
namespace SopHelper.Engine.Inference;
/// <summary>
/// YOLOv8 检测(纯 ONNX Runtime,自带 DFL 解码 + NMS,不依赖 YoloDotNet)。
/// 不用 YoloDotNet 的理由:它是 GPL-3.0-only,会污染整个骨架的 MIT;且拖 SixLabors 全家。
/// </summary>
public class YoloDetector : IDisposable
{
private InferenceSession? _session;
private string[] _classNames = [];
private float _confThreshold = 0.4f;
private float _nmsThreshold = 0.45f;
private int _inputSize = 640;
/// <summary>模型是否就绪</summary>
public bool IsReady => _session is not null;
/// <summary>实际使用的设备</summary>
public bool UsingGpu { get; private set; }
/// <summary>
/// 加载模型。classNames 顺序必须与训练时一致(decoding 出来的类别索引直接按它取名)。
/// </summary>
public void Load(string modelPath, IReadOnlyList<string> classNames, int inputSize = 640, bool preferGpu = false)
{
if (!File.Exists(modelPath)) return;
_classNames = classNames.ToArray();
_inputSize = inputSize;
if (preferGpu)
{
try
{
_session = new InferenceSession(modelPath, Options(true));
UsingGpu = true;
return;
}
catch
{
// CUDA 不可用,回退 CPU
}
}
_session = new InferenceSession(modelPath, Options(false));
UsingGpu = false;
}
/// <summary>
/// 阈值
/// </summary>
public void SetThresholds(float conf, float nms)
{
_confThreshold = conf;
_nmsThreshold = nms;
}
/// <summary>
/// 推理一帧(BGR)
/// </summary>
public List<Detection> Detect(Mat bgr)
{
var list = new List<Detection>();
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<float>([1, 3, inputSize, inputSize]);
for (var y = 0; y < inputSize; y++)
{
for (var x = 0; x < inputSize; x++)
{
var px = canvas.At<Vec3b>(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> { NamedOnnxValue.CreateFromTensor(InputName(), tensor) };
using var results = _session!.Run(inputs);
var output = results.FirstOrDefault();
if (output is null) return list;
var t = output.AsTensor<float>();
if (t is null) return list;
// 标准 YOLOv8 输出 [1, 4+nc, anchors];转置版 [1, anchors, 4+nc] 也兼容
var transposed = t.Dimensions.Length == 3 && t.Dimensions[1] == 4 + _classNames.Length;
var candidates = new List<Detection>();
if (transposed)
{
var anchorCount = t.Dimensions[2];
for (var a = 0; a < anchorCount; a++)
{
var best = 0;
var bestScore = 0f;
for (var c = 0; c < _classNames.Length; c++)
{
var score = t[0, 4 + c, a];
if (score > bestScore)
{
bestScore = score;
best = c;
}
}
if (bestScore < _confThreshold) continue;
// DFL 解码:前 4 行是 4×16 个 bin 的 softmax 分布,取期望值得到距四边的距离
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 = bestScore,
Rect = new DetRect(cx - w / 2f, cy - h / 2f, w, h),
});
}
}
else
{
// 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),
});
}
}
list.AddRange(Nms(candidates));
return list;
}
/// <summary>
/// DFL(Distribution Focal Loss)解码:对 4 组 16 bin 做 softmax 取期望,得到边界框
/// </summary>
private static (float Cx, float Cy) DflBox(Tensor<float> 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<float> 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);
}
/// <summary>
/// 把拼接后的锚点索引还原为 (列, 行, stride)。
/// YOLOv8 检测头输出是 P3/P4/P5 三层按 [8,16,32] 顺序拼接,每层内部行优先。
/// </summary>
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]);
}
/// <summary>
/// NMS
/// </summary>
private List<Detection> Nms(List<Detection> list)
{
if (list.Count == 0) return list;
var keep = new List<Detection>();
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;
}
/// <summary>
/// 取模型真实输入节点名(不写死 "input",各家导出不一样)
/// </summary>
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,
};
if (cuda) o.AppendExecutionProvider_CUDA(0);
return o;
}
/// <inheritdoc />
public void Dispose()
{
_session?.Dispose();
_session = null;
}
}