恢复独立的 YOLO 单帧推理组件

This commit is contained in:
wanglei 2026-12-06 18:29:59 +08:00
parent 22fdbdcc5a
commit eb4b0a1c7b
2 changed files with 441 additions and 2 deletions

View File

@ -0,0 +1,440 @@
using Microsoft.ML.OnnxRuntime;
using Microsoft.ML.OnnxRuntime.Tensors;
using OpenCvSharp;
using SopHelper.Engine.Common;
using YamlDotNet.Serialization;
namespace SopHelper.Engine.Inference;
/// <summary>
/// 按调用执行单帧 ONNX 物体检测,对检测框解码并做同类非极大值抑制。
/// 调用方负责决定何时推理,并在结束时释放模型会话。
/// </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;
public IReadOnlyList<string> ClassNames => _classNames;
/// <summary>模型是否就绪</summary>
public bool IsReady => _session is not null;
/// <summary>实际使用的设备</summary>
public bool UsingGpu { get; private set; }
private string _gpuBackend = "CPU";
public string Backend => !IsReady ? "未加载" : UsingGpu ? _gpuBackend : "CPU";
public string? GpuFallbackReason { get; private set; }
/// <summary>
/// 加载模型。classNames 顺序必须与训练时一致(decoding 出来的类别索引直接按它取名)。
/// </summary>
public void Load(string modelPath, IReadOnlyList<string> classNames, int inputSize = 640, bool preferGpu = true, bool requireGpu = false)
{
Dispose();
UsingGpu = false;
GpuFallbackReason = null;
if (requireGpu && !preferGpu) throw new ArgumentException("要求 GPU 推理时必须启用 preferGpu");
if (!File.Exists(modelPath)) return;
_classNames = classNames.ToArray();
_inputSize = inputSize;
if (preferGpu)
{
try
{
using var options = InferenceSessionOptions.Create(true, "yolo", out _gpuBackend);
_session = new InferenceSession(modelPath, options);
UsingGpu = true;
}
catch (Exception ex)
{
GpuFallbackReason = ex.Message;
if (requireGpu) throw new InvalidOperationException("YOLO GPU 推理初始化失败:" + ex.Message, ex);
}
}
try
{
if (_session is null)
{
using var cpuOptions = InferenceSessionOptions.Create(false, "yolo", out _);
_session = new InferenceSession(modelPath, cpuOptions);
UsingGpu = false;
}
// 固定尺寸 ONNX 的真实输入优先于配方中可能过期的尺寸。
var dimensions = _session.InputMetadata.First().Value.Dimensions;
if (dimensions.Length != 4 || (dimensions[1] > 0 && dimensions[1] != 3))
throw new InvalidDataException("YOLO 输入需要 NCHW 三通道图像");
if (dimensions[2] > 0 && dimensions[3] > 0)
{
if (dimensions[2] != dimensions[3])
throw new InvalidDataException("当前 YOLO 检测器仅支持正方形模型输入");
_inputSize = dimensions[2];
}
else if (_inputSize < 1)
throw new InvalidDataException("动态尺寸模型需要配置有效的输入尺寸");
var metadata = _session.ModelMetadata.CustomMetadataMap;
if (metadata.TryGetValue("names", out var names))
{
var labels = new DeserializerBuilder().Build().Deserialize<Dictionary<int, string>>(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; }
}
/// <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 = Math.Max(1, (int)Math.Round(bgr.Width * scale));
var newH = Math.Max(1, (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 = TensorPreprocessing.FromRgb(canvas);
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 / 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<Detection>();
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;
}
/// <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>
/// 类别通道是 logits,必须先过 sigmoid 才能和置信度阈值比
/// (之前 conf=68 那种数就是因为漏了这步,直接把 logits 当概率)
/// </summary>
private static float Sigmoid(float x) => (float)(1.0 / (1.0 + Math.Exp(-x)));
/// <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>
/// 类别块是 logits(要 sigmoid)还是已烘好的概率(不能再见 sigmoid):
/// 只看类别块自己有没有负值(坐标行在暗帧上会出负值,不能拿来当判据)。
/// </summary>
private bool ClassChannelsAreLogits(Tensor<float> 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;
}
/// <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";
}
}
/// <inheritdoc />
public void Dispose()
{
_session?.Dispose();
_session = null;
UsingGpu = false;
}
}

View File

@ -1,4 +1,4 @@
using System.Net;
using System.Net;
using System.Text;
using System.Text.Json;
using SopHelper.Engine.Common;
@ -8,7 +8,6 @@ if (args.Contains("--dlite-audit")) { await DliteAudit.RunAsync(args); return; }
SettingsMigrationChecks.Run();
static void Check(bool value, string message) { if (!value) throw new Exception(message); }
Check(typeof(SopEngine).Assembly.GetType("SopHelper.Engine.Inference.YoloDetector") is null, "运行程序集必须移除 YOLO 检测器");
var retired = SopConfigLoader.Parse("""
sop:
name: 旧物体规则