From 061b8cd3be756bc7f829f8720887cde60e690786 Mon Sep 17 00:00:00 2001
From: sophelper <123211521@163.com>
Date: Tue, 3 Nov 2026 00:59:24 +0800
Subject: [PATCH] =?UTF-8?q?feat(Engine):=20UVC=20=E7=9B=B8=E6=9C=BA=20+=20?=
=?UTF-8?q?YOLO/MediaPipe=20=E6=89=8B=E9=83=A8=20ONNX=20=E6=8E=A8=E7=90=86?=
=?UTF-8?q?=20+=20=E6=8A=BD=E5=B8=A7=E7=AE=A1=E7=BA=BF?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
- 不引 YoloDotNet(GPL-3.0),自带 YOLOv8 letterbox + DFL 解码 + NMS
- MediaPipe 两阶段照搬参考项目解析:palm 192 → 方形裁剪 → landmark 224
- 相机 MSMF 优先/回退 DSHOW、DSHOW 进程级串行、不重复开同一索引、取帧后不补 Sleep
- 引擎层只用自有 DetRect,不绑定 SkiaSharp/OpenCvSharp/YoloDotNet 类型
---
src/SopHelper.Engine/Camera/ICameraService.cs | 74 ++++
.../Camera/UvcCameraService.cs | 288 ++++++++++++++
src/SopHelper.Engine/Common/Types.cs | 158 ++++++++
.../Inference/MediaPipeHandDetector.cs | 376 ++++++++++++++++++
.../Inference/YoloDetector.cs | 340 ++++++++++++++++
.../Pipeline/DetectionPipeline.cs | 193 +++++++++
6 files changed, 1429 insertions(+)
create mode 100644 src/SopHelper.Engine/Camera/ICameraService.cs
create mode 100644 src/SopHelper.Engine/Camera/UvcCameraService.cs
create mode 100644 src/SopHelper.Engine/Common/Types.cs
create mode 100644 src/SopHelper.Engine/Inference/MediaPipeHandDetector.cs
create mode 100644 src/SopHelper.Engine/Inference/YoloDetector.cs
create mode 100644 src/SopHelper.Engine/Pipeline/DetectionPipeline.cs
diff --git a/src/SopHelper.Engine/Camera/ICameraService.cs b/src/SopHelper.Engine/Camera/ICameraService.cs
new file mode 100644
index 0000000..6933a30
--- /dev/null
+++ b/src/SopHelper.Engine/Camera/ICameraService.cs
@@ -0,0 +1,74 @@
+using OpenCvSharp;
+
+namespace SopHelper.Engine.Camera;
+
+///
+/// 相机信息
+///
+public class CameraInfo
+{
+ /// 索引(UVC 设备号)
+ public int Index { get; set; }
+
+ /// 名称
+ public string Name { get; set; } = "";
+}
+
+///
+/// 一帧原始图像(BGR Mat,附帧号与实测帧率)
+///
+public class CameraFrame : IDisposable
+{
+ /// 帧号(相机侧累计)
+ public long FrameId { get; set; }
+
+ /// 采集时刻
+ public DateTime Timestamp { get; set; }
+
+ /// BGR 图像(由本类持有,消费方不得跨帧持有)
+ public required Mat Bgr { get; set; }
+
+ ///
+ /// 释放
+ ///
+ public void Dispose()
+ {
+ Bgr.Dispose();
+ }
+}
+
+///
+/// USB(UVC)相机服务。单相机最小版:一个采集线程 + 帧事件。
+///
+public interface ICameraService : IDisposable
+{
+ /// 是否已连接
+ bool IsConnected { get; }
+
+ /// 是否正在采集
+ bool IsGrabbing { get; }
+
+ /// 新帧(在采集线程上触发,消费方用完不得保留 Mat)
+ event Action? FrameArrived;
+
+ /// 连接状态变化
+ event Action? ConnectionChanged;
+
+ /// 错误
+ event Action? Error;
+
+ /// 枚举可用 UVC 相机
+ Task> EnumerateAsync();
+
+ /// 连接相机
+ Task ConnectAsync(CameraInfo camera);
+
+ /// 开始采集
+ Task StartAsync();
+
+ /// 停止采集
+ void Stop();
+
+ /// 断开
+ void Disconnect();
+}
diff --git a/src/SopHelper.Engine/Camera/UvcCameraService.cs b/src/SopHelper.Engine/Camera/UvcCameraService.cs
new file mode 100644
index 0000000..fda84cd
--- /dev/null
+++ b/src/SopHelper.Engine/Camera/UvcCameraService.cs
@@ -0,0 +1,288 @@
+using OpenCvSharp;
+
+namespace SopHelper.Engine.Camera;
+
+///
+/// USB(UVC)相机实现。单相机最小版。
+/// 三个坑照搬参考项目实测结论:MSMF 优先、DSHOW 图必须进程级串行、不可重复打开同一索引。
+///
+public class UvcCameraService : ICameraService
+{
+ ///
+ /// 进程级 DSHOW 互斥锁:DirectShow 原生图不允许并发创建/销毁,
+ /// 旧图还在异步销毁时开新图会触发 AccessViolationException。
+ ///
+ private static readonly object DshowLock = new();
+
+ private readonly object _captureLock = new();
+ private VideoCapture? _capture;
+ private CancellationTokenSource? _cts;
+ private Task? _grabTask;
+ private long _frameId;
+
+ ///
+ public bool IsConnected { get; private set; }
+
+ ///
+ public bool IsGrabbing { get; private set; }
+
+ ///
+ public event Action? FrameArrived;
+
+ ///
+ public event Action? ConnectionChanged;
+
+ ///
+ public event Action? Error;
+
+ /// 当前相机
+ public CameraInfo? Current { get; private set; }
+
+ /// 实测帧率(每 2 秒刷新一次)
+ public double ActualFps { get; private set; }
+
+ ///
+ public Task> EnumerateAsync()
+ {
+ return Task.Run(() =>
+ {
+ var list = new List();
+
+ for (var i = 0; i <= 10; i++)
+ {
+ var index = i;
+
+ // 跳过本进程已占用的索引:对同一设备重复开 DSHOW 图会原生崩溃
+ lock (_captureLock)
+ {
+ if (_capture is not null && Current?.Index == index)
+ {
+ list.Add(new CameraInfo { Index = index, Name = $"Camera {index}(当前已连接)" });
+ continue;
+ }
+ }
+
+ lock (DshowLock)
+ {
+ try
+ {
+ using var probe = new VideoCapture(index, VideoCaptureAPIs.DSHOW);
+ if (!probe.IsOpened()) continue;
+
+ var w = probe.Get(VideoCaptureProperties.FrameWidth);
+ var h = probe.Get(VideoCaptureProperties.FrameHeight);
+ if (w <= 0 || h <= 0) continue;
+
+ list.Add(new CameraInfo { Index = index, Name = $"Camera {index}({w:F0}x{h:F0})" });
+ }
+ catch
+ {
+ // 探测失败的设备跳过即可
+ }
+ }
+ }
+
+ return list;
+ });
+ }
+
+ ///
+ public Task ConnectAsync(CameraInfo camera)
+ {
+ return Task.Run(() =>
+ {
+ lock (DshowLock)
+ {
+ lock (_captureLock)
+ {
+ if (_capture is not null)
+ {
+ _capture.Dispose();
+ _capture = null;
+ }
+
+ // MSMF 优先:DSHOW 后端对"反复开图/关图"存在已知原生缺陷,
+ // 图销毁是系统级异步,紧接的开图仍可能撞上未完成的销毁而崩溃。
+ _capture = TryOpen(camera.Index, VideoCaptureAPIs.MSMF)
+ ?? TryOpen(camera.Index, VideoCaptureAPIs.DSHOW);
+
+ if (_capture is null)
+ {
+ Error?.Invoke($"相机 {camera.Index} 打不开(MSMF 与 DSHOW 均失败)");
+ return false;
+ }
+ }
+ }
+
+ Current = camera;
+ IsConnected = true;
+ ConnectionChanged?.Invoke(true);
+ return true;
+ });
+ }
+
+ ///
+ public Task StartAsync()
+ {
+ return Task.Run(() =>
+ {
+ VideoCapture capture;
+
+ lock (_captureLock)
+ {
+ if (_capture is null) return false;
+ capture = _capture;
+ }
+
+ if (IsGrabbing) return true;
+
+ _cts = new CancellationTokenSource();
+ IsGrabbing = true;
+ _grabTask = Task.Run(() => GrabLoop(capture, _cts.Token));
+
+ return true;
+ });
+ }
+
+ ///
+ /// 采集循环
+ ///
+ private void GrabLoop(VideoCapture capture, CancellationToken token)
+ {
+ var fpsWatch = System.Diagnostics.Stopwatch.StartNew();
+ var framesInWindow = 0;
+
+ while (!token.IsCancellationRequested)
+ {
+ var frame = new Mat();
+
+ bool ok;
+ lock (_captureLock)
+ {
+ if (captureDisposed) break;
+ ok = capture.Read(frame);
+ }
+
+ if (!ok || frame.Empty())
+ {
+ frame.Dispose();
+
+ // 读不到帧时轻微退避,不空转
+ Thread.Sleep(20);
+ continue;
+ }
+
+ // ⚠ 成功取帧后不强制 Sleep:Read 本身按相机帧节拍阻塞,
+ // 补一个 Sleep(33) 会把采集帧率白扣一半(参考项目实测踩过)。
+
+ _frameId++;
+ framesInWindow++;
+
+ if (fpsWatch.ElapsedMilliseconds >= 2000)
+ {
+ ActualFps = framesInWindow * 1000.0 / fpsWatch.ElapsedMilliseconds;
+ fpsWatch.Restart();
+ framesInWindow = 0;
+ }
+
+ var cameraFrame = new CameraFrame
+ {
+ FrameId = _frameId,
+ Timestamp = DateTime.Now,
+ Bgr = frame,
+ };
+
+ try
+ {
+ FrameArrived?.Invoke(cameraFrame);
+ }
+ catch (Exception ex)
+ {
+ Error?.Invoke($"帧回调异常: {ex.Message}");
+ }
+ finally
+ {
+ cameraFrame.Dispose();
+ }
+ }
+
+ IsGrabbing = false;
+ }
+
+ private volatile bool captureDisposed;
+
+ ///
+ public void Stop()
+ {
+ _cts?.Cancel();
+
+ try
+ {
+ _grabTask?.Wait(TimeSpan.FromSeconds(2));
+ }
+ catch
+ {
+ // 取消异常忽略
+ }
+
+ _grabTask = null;
+ _cts?.Dispose();
+ _cts = null;
+ IsGrabbing = false;
+ }
+
+ ///
+ public void Disconnect()
+ {
+ Stop();
+
+ lock (DshowLock)
+ {
+ lock (_captureLock)
+ {
+ if (_capture is not null)
+ {
+ captureDisposed = true;
+ _capture.Dispose();
+ _capture = null;
+ captureDisposed = false;
+ }
+ }
+
+ // 给系统一点时间把原生图销毁干净,紧接的 ConnectAsync 才安全
+ Thread.Sleep(500);
+ }
+
+ IsConnected = false;
+ Current = null;
+ ConnectionChanged?.Invoke(false);
+ }
+
+ ///
+ public void Dispose()
+ {
+ Disconnect();
+ }
+
+ ///
+ /// 用指定后端尝试打开
+ ///
+ private static VideoCapture? TryOpen(int index, VideoCaptureAPIs api)
+ {
+ try
+ {
+ var capture = new VideoCapture(index, api);
+ if (!capture.IsOpened())
+ {
+ capture.Dispose();
+ return null;
+ }
+
+ return capture;
+ }
+ catch
+ {
+ return null;
+ }
+ }
+}
diff --git a/src/SopHelper.Engine/Common/Types.cs b/src/SopHelper.Engine/Common/Types.cs
new file mode 100644
index 0000000..522f064
--- /dev/null
+++ b/src/SopHelper.Engine/Common/Types.cs
@@ -0,0 +1,158 @@
+namespace SopHelper.Engine.Common;
+
+///
+/// 轻量矩形。引擎层只用这个,不绑定 OpenCvSharp / SkiaSharp 类型
+/// (参考项目把 SkiaSharp 和 YoloDotNet.Models 写进了判定层,导致那一层无法单独抽走)
+///
+public struct DetRect
+{
+ /// X
+ public float X;
+
+ /// Y
+ public float Y;
+
+ /// W
+ public float W;
+
+ /// H
+ public float H;
+
+ ///
+ /// 轻量矩形
+ ///
+ public DetRect(float x, float y, float w, float h)
+ {
+ X = x; Y = y; W = w; H = h;
+ }
+
+ /// 右边界
+ public float Right => X + W;
+
+ /// 下边界
+ public float Bottom => Y + H;
+
+ /// 中心点
+ public (float Cx, float Cy) Center => ((X + Right) / 2f, (Y + Bottom) / 2f);
+
+ ///
+ /// 点是否落在矩形内(pad 为外扩像素,负数=内缩)
+ ///
+ public bool Contains(float px, float py, float pad = 0f)
+ => px >= X - pad && px <= Right + pad && py >= Y - pad && py <= Bottom + pad;
+
+ ///
+ /// 两矩形是否相交(pad 为其中一个的外扩像素)
+ ///
+ public bool Intersects(DetRect other, float pad = 0f)
+ {
+ var x1 = X - pad;
+ var y1 = Y - pad;
+ var x2 = Right + pad;
+ var y2 = Bottom + pad;
+ return x1 < other.Right && x2 > other.X && y1 < other.Bottom && y2 > other.Y;
+ }
+}
+
+///
+/// 一次目标检测结果
+///
+public class Detection
+{
+ /// 类别名(模型输出顺序映射而来)
+ public string Label { get; set; } = "";
+
+ /// 置信度
+ public float Confidence { get; set; }
+
+ /// 像素坐标框
+ public DetRect Rect { get; set; }
+}
+
+///
+/// 手部类型
+///
+public enum HandType
+{
+ /// 未知
+ Unknown = 0,
+
+ /// 左手
+ Left = 1,
+
+ /// 右手
+ Right = 2,
+}
+
+///
+/// 一个手部关键点(MediaPipe 21 点之一)
+///
+public class HandPoint
+{
+ /// 关键点序号 0-20(0=手腕)
+ public int Index { get; set; }
+
+ /// 像素坐标 X
+ public float X { get; set; }
+
+ /// 像素坐标 Y
+ public float Y { get; set; }
+
+ /// 相对深度
+ public float Z { get; set; }
+
+ /// 该点置信度(部分 ONNX 导出无逐点置信度,由上层填固定值)
+ public float Confidence { get; set; } = 1f;
+}
+
+///
+/// 一只手的结果
+///
+public class Hand
+{
+ /// 左右手判定
+ public HandType HandType { get; set; } = HandType.Unknown;
+
+ /// 手部(手掌)框
+ public DetRect Rect { get; set; }
+
+ /// 21 个关键点,已映射回原图像素坐标
+ public List Keypoints { get; set; } = [];
+
+ /// 手掌检测置信度
+ public float Confidence { get; set; }
+
+ /// 所有关键点的几何中心(判定"手在哪个区域"就用它)
+ public (float Cx, float Cy) Center
+ {
+ get
+ {
+ if (Keypoints.Count == 0) return Rect.Center;
+ return (Keypoints.Average(k => k.X), Keypoints.Average(k => k.Y));
+ }
+ }
+}
+
+///
+/// 一帧的完整推理结果,喂给 SOP 引擎的就是它
+///
+public class FrameResult
+{
+ /// 帧号
+ public long FrameId { get; set; }
+
+ /// 帧时间戳
+ public DateTime Timestamp { get; set; }
+
+ /// 原图像素尺寸
+ public (int W, int H) Size { get; set; }
+
+ /// YOLO 检出目标
+ public List Detections { get; set; } = [];
+
+ /// 检出的手
+ public List Hands { get; set; } = [];
+
+ /// 本帧推理耗时(毫秒)
+ public double InferenceMs { get; set; }
+}
diff --git a/src/SopHelper.Engine/Inference/MediaPipeHandDetector.cs b/src/SopHelper.Engine/Inference/MediaPipeHandDetector.cs
new file mode 100644
index 0000000..be4a12e
--- /dev/null
+++ b/src/SopHelper.Engine/Inference/MediaPipeHandDetector.cs
@@ -0,0 +1,376 @@
+using Microsoft.ML.OnnxRuntime;
+using Microsoft.ML.OnnxRuntime.Tensors;
+using OpenCvSharp;
+using SopHelper.Engine.Common;
+
+namespace SopHelper.Engine.Inference;
+
+///
+/// MediaPipe 手部(两阶段 ONNX,纯 C# 实现,照搬参考项目的解析逻辑)。
+/// 第一阶段手掌检测 → 方形裁剪 → 第二阶段 21 关键点。
+///
+public class MediaPipeHandDetector : IDisposable
+{
+ private const int PalmInputSize = 192;
+ private const int LandmarkInputSize = 224;
+
+ private InferenceSession? _palm;
+ private InferenceSession? _landmark;
+
+ private float _palmThreshold = 0.5f;
+ private float _keypointThreshold = 0.5f;
+ private int _maxHands = 2;
+
+ /// 模型是否就绪(缺文件时上层跳过手部判定,不报错)
+ public bool IsReady => _palm is not null && _landmark is not null;
+
+ /// 实际使用的设备(CUDA 不可用时回退 CPU)
+ public bool UsingGpu { get; private set; }
+
+ ///
+ /// 加载两个模型。任缺其一则整个手部检测不启用。
+ ///
+ public void Load(string palmModelPath, string landmarkModelPath, bool preferGpu = false)
+ {
+ if (!File.Exists(palmModelPath) || !File.Exists(landmarkModelPath))
+ return;
+
+ if (preferGpu)
+ {
+ try
+ {
+ _palm = new InferenceSession(palmModelPath, Options(true));
+ _landmark = new InferenceSession(landmarkModelPath, Options(true));
+ UsingGpu = true;
+ return;
+ }
+ catch
+ {
+ // CUDA 不可用,回退 CPU
+ }
+ }
+
+ _palm = new InferenceSession(palmModelPath, Options(false));
+ _landmark = new InferenceSession(landmarkModelPath, Options(false));
+ UsingGpu = false;
+ }
+
+ ///
+ /// 阈值
+ ///
+ public void SetThresholds(float palm, float keypoint, int maxHands)
+ {
+ _palmThreshold = palm;
+ _keypointThreshold = keypoint;
+ _maxHands = Math.Max(1, maxHands);
+ }
+
+ ///
+ /// 检测一帧(BGR)里的所有手
+ ///
+ public List Detect(Mat bgr)
+ {
+ var hands = new List();
+ if (!IsReady) return hands;
+
+ // 涂黑副本:检出一只手后把该区域抹掉,再跑下一遍,避免重复选中同一只手
+ using var working = bgr.Clone();
+ var taken = new List();
+
+ for (var pass = 0; pass < _maxHands; pass++)
+ {
+ var palms = DetectPalms(working);
+ if (palms.Count == 0) break;
+
+ // 取置信度最高、且不与已检出手重叠(IoU>0.3)的候选
+ DetRect? best = null;
+ float bestScore = 0f;
+
+ foreach (var p in palms.OrderByDescending(p => p.Score))
+ {
+ if (taken.Any(t => IoU(t, p.Rect) > 0.3f)) continue;
+ best = p.Rect;
+ bestScore = p.Score;
+ break;
+ }
+
+ if (best is null) break;
+
+ // 无论本遍是否成功都要涂黑,否则下一遍会重复选中同一只手
+ var hand = DetectLandmarks(working, best.Value);
+ if (hand is not null && hand.Keypoints.Count > 0)
+ {
+ var avg = hand.Keypoints.Average(k => k.Confidence);
+ if (avg >= _keypointThreshold)
+ {
+ hand.Confidence = bestScore;
+ hands.Add(hand);
+ taken.Add(best.Value);
+ }
+ }
+
+ MaskRegion(working, best.Value);
+
+ if (hands.Count >= _maxHands) break;
+ }
+
+ return hands;
+ }
+
+ ///
+ /// 第一阶段:手掌检测
+ ///
+ private List<(DetRect Rect, float Score)> DetectPalms(Mat bgr)
+ {
+ var list = new List<(DetRect, float)>();
+
+ var tensor = ToTensor(bgr, PalmInputSize);
+ var inputs = new List { NamedOnnxValue.CreateFromTensor("input", tensor) };
+
+ using var results = _palm!.Run(inputs);
+ var items = results.ToList();
+ if (items.Count == 0) return list;
+
+ // 标准两阶段格式:[0]=boxes [1]=scores
+ if (items.Count >= 2)
+ {
+ var boxesT = TryTensor(items[0]);
+ var scoresT = TryTensor(items[1]);
+
+ if (boxesT is not null && scoresT is not null)
+ {
+ // scores [1, N],boxes [1, N, 4](归一化到原图)
+ var n = scoresT.Dimensions[1];
+
+ for (var i = 0; i < n; i++)
+ {
+ var score = scoresT[0, i];
+ if (score <= _palmThreshold) continue;
+
+ var x1 = boxesT[0, i, 0] * bgr.Width;
+ var y1 = boxesT[0, i, 1] * bgr.Height;
+ var x2 = boxesT[0, i, 2] * bgr.Width;
+ var y2 = boxesT[0, i, 3] * bgr.Height;
+
+ list.Add((new DetRect(x1, y1, x2 - x1, y2 - y1), score));
+ }
+
+ return list;
+ }
+ }
+
+ // 单阶段格式:每行 [score, cx, cy, w, ...](归一化到 192)
+ var flat = TryTensor(items[0]);
+ if (flat is null) return list;
+
+ var rows = flat.Dimensions[0];
+ var cols = flat.Dimensions.Length > 1 ? flat.Dimensions[1] : 0;
+ if (cols < 4) return list;
+
+ for (var i = 0; i < rows; i++)
+ {
+ var score = flat[i, 0];
+ if (score <= _palmThreshold) continue;
+
+ var cx = flat[i, 1] * bgr.Width;
+ var cy = flat[i, 2] * bgr.Height;
+ var w = flat[i, 3] * bgr.Width;
+
+ list.Add((new DetRect(cx - w / 2f, cy - w / 2f, w, w), score));
+ }
+
+ return list;
+ }
+
+ ///
+ /// 第二阶段:对手掌框做 21 关键点
+ ///
+ private Hand? DetectLandmarks(Mat bgr, DetRect palm)
+ {
+ // 方形裁剪:关键点模型要求方形输入,直接裁非方形再拉伸会破坏长宽比,
+ // 把指尖坐标拉歪(表现为手指点"堆在手掌/手腕")。
+ const float margin = 20f;
+ var side = Math.Max(palm.W + margin * 2f, palm.H + margin * 2f);
+ var (cx, cy) = palm.Center;
+
+ var x = cx - side / 2f;
+ var y = cy - side / 2f;
+
+ if (x + side > bgr.Width) x = bgr.Width - side;
+ if (y + side > bgr.Height) y = bgr.Height - side;
+ if (x < 0) x = 0;
+ if (y < 0) y = 0;
+ side = Math.Min(side, bgr.Width);
+ side = Math.Min(side, bgr.Height);
+ if (side <= 0) return null;
+
+ using var crop = new Mat(bgr, new Rect((int)Math.Round(x), (int)Math.Round(y), (int)Math.Round(side), (int)Math.Round(side)));
+ if (crop.Empty()) return null;
+
+ var tensor = ToTensor(crop, LandmarkInputSize);
+ var inputs = new List { NamedOnnxValue.CreateFromTensor("input", tensor) };
+
+ using var results = _landmark!.Run(inputs);
+ var first = results.FirstOrDefault();
+ if (first is null) return null;
+
+ var t = TryTensor(first);
+ if (t is null) return null;
+
+ // 输出格式适配:[1,21,3] / [21,3] / [1,63] / [63]
+ var pts = new List();
+
+ for (var i = 0; i < 21; i++)
+ {
+ float nx, ny, z;
+
+ if (t.Dimensions.Length == 3)
+ {
+ nx = t[0, i, 0]; ny = t[0, i, 1]; z = t[0, i, 2];
+ }
+ else if (t.Dimensions.Length == 2 && t.Dimensions[1] >= 63)
+ {
+ nx = t[0, i * 3]; ny = t[0, i * 3 + 1]; z = t[0, i * 3 + 2];
+ }
+ else if (t.Dimensions.Length == 2 && t.Dimensions[1] >= 3)
+ {
+ nx = t[i, 0]; ny = t[i, 1]; z = t[i, 2];
+ }
+ else
+ {
+ nx = t[i * 3]; ny = t[i * 3 + 1]; z = t[i * 3 + 2];
+ }
+
+ // 输出坐标相对 224×224 输入(0-1),映射回方形裁剪区再加裁剪偏移
+ float px, py;
+
+ if (nx > 1f || ny > 1f)
+ {
+ px = nx / LandmarkInputSize;
+ py = ny / LandmarkInputSize;
+ }
+ else
+ {
+ px = nx;
+ py = ny;
+ }
+
+ pts.Add(new HandPoint
+ {
+ Index = i,
+ X = x + px * side,
+ Y = y + py * side,
+ Z = z,
+ Confidence = 0.9f, // 该 ONNX 导出无逐点置信度,参考项目同样给定值
+ });
+ }
+
+ return new Hand
+ {
+ HandType = GuessHandType(pts),
+ Rect = palm,
+ Keypoints = pts,
+ };
+ }
+
+ ///
+ /// 手型判定:该 ONNX 导出无 handedness 输出,用拇指尖相对其余指心的位置粗判
+ /// (MediaPipe 官方 handedness 在镜像图上会互换,故此处只做提示,不参与判定门控)。
+ ///
+ private static HandType GuessHandType(List pts)
+ {
+ if (pts.Count < 21) return HandType.Unknown;
+
+ var wrist = pts[0];
+ var thumbTip = pts[4];
+ var midTip = pts[12];
+
+ // 拇指尖在中指尖左侧 → 倾向右手(未镜像视角)
+ return thumbTip.X < midTip.X ? HandType.Right : HandType.Left;
+ }
+
+ ///
+ /// BGR → RGB float [1,3,size,size],归一化 [0,1]
+ ///
+ private static DenseTensor ToTensor(Mat bgr, int size)
+ {
+ using var rgb = new Mat();
+ Cv2.CvtColor(bgr, rgb, ColorConversionCodes.BGR2RGB);
+ using var resized = new Mat();
+ Cv2.Resize(rgb, resized, new Size(size, size), 0, 0, InterpolationFlags.Area);
+
+ var tensor = new DenseTensor([1, 3, size, size]);
+
+ for (var yy = 0; yy < size; yy++)
+ {
+ for (var xx = 0; xx < size; xx++)
+ {
+ var px = resized.At(yy, xx);
+ tensor[0, 0, yy, xx] = px.Item0 / 255f;
+ tensor[0, 1, yy, xx] = px.Item1 / 255f;
+ tensor[0, 2, yy, xx] = px.Item2 / 255f;
+ }
+ }
+
+ return tensor;
+ }
+
+ ///
+ /// 把区域涂黑(从副本上"拿走"这只手)
+ ///
+ private static void MaskRegion(Mat working, DetRect rect)
+ {
+ var r = new Rect((int)rect.X, (int)rect.Y, (int)rect.W, (int)rect.H);
+ r.Intersect(new Rect(0, 0, working.Width, working.Height));
+ if (r.Width <= 0 || r.Height <= 0) return;
+
+ using var roi = new Mat(working, r);
+ roi.SetTo(new Scalar(0, 0, 0));
+ }
+
+ 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;
+ }
+
+ private static Tensor? TryTensor(DisposableNamedOnnxValue v)
+ {
+ try
+ {
+ return v.AsTensor();
+ }
+ catch
+ {
+ return null;
+ }
+ }
+
+ private static SessionOptions Options(bool cuda)
+ {
+ var o = new SessionOptions
+ {
+ GraphOptimizationLevel = GraphOptimizationLevel.ORT_ENABLE_ALL,
+ };
+
+ if (cuda) o.AppendExecutionProvider_CUDA(0);
+
+ return o;
+ }
+
+ ///
+ public void Dispose()
+ {
+ _palm?.Dispose();
+ _landmark?.Dispose();
+ _palm = null;
+ _landmark = null;
+ }
+}
diff --git a/src/SopHelper.Engine/Inference/YoloDetector.cs b/src/SopHelper.Engine/Inference/YoloDetector.cs
new file mode 100644
index 0000000..df3af0a
--- /dev/null
+++ b/src/SopHelper.Engine/Inference/YoloDetector.cs
@@ -0,0 +1,340 @@
+using Microsoft.ML.OnnxRuntime;
+using Microsoft.ML.OnnxRuntime.Tensors;
+using OpenCvSharp;
+using SopHelper.Engine.Common;
+
+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 bool IsReady => _session is not null;
+
+ /// 实际使用的设备
+ public bool UsingGpu { get; private set; }
+
+ ///
+ /// 加载模型。classNames 顺序必须与训练时一致(decoding 出来的类别索引直接按它取名)。
+ ///
+ public void Load(string modelPath, IReadOnlyList 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;
+ }
+
+ ///
+ /// 阈值
+ ///
+ 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 输出 [1, 4+nc, anchors];转置版 [1, anchors, 4+nc] 也兼容
+ var transposed = t.Dimensions.Length == 3 && t.Dimensions[1] == 4 + _classNames.Length;
+
+ var candidates = new List();
+
+ 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;
+ }
+
+ ///
+ /// 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);
+ }
+
+ ///
+ /// 把拼接后的锚点索引还原为 (列, 行, 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]);
+ }
+
+ ///
+ /// 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,
+ };
+
+ if (cuda) o.AppendExecutionProvider_CUDA(0);
+
+ return o;
+ }
+
+ ///
+ public void Dispose()
+ {
+ _session?.Dispose();
+ _session = null;
+ }
+}
diff --git a/src/SopHelper.Engine/Pipeline/DetectionPipeline.cs b/src/SopHelper.Engine/Pipeline/DetectionPipeline.cs
new file mode 100644
index 0000000..93dfa76
--- /dev/null
+++ b/src/SopHelper.Engine/Pipeline/DetectionPipeline.cs
@@ -0,0 +1,193 @@
+using OpenCvSharp;
+using SopHelper.Engine.Camera;
+using SopHelper.Engine.Common;
+using SopHelper.Engine.Inference;
+
+namespace SopHelper.Engine.Pipeline;
+
+///
+/// 管线配置
+///
+public class PipelineOptions
+{
+ /// YOLO 模型路径(可空:纯手部配方不需要)
+ public string? YoloModelPath { get; set; }
+
+ /// 类别名,顺序必须与训练一致
+ public List YoloClasses { get; set; } = [];
+
+ /// YOLO 输入尺寸
+ public int YoloInputSize { get; set; } = 640;
+
+ /// MediaPipe 手掌模型(可空:不需要手部的配方不加载)
+ public string? PalmModelPath { get; set; }
+
+ /// MediaPipe 关键点模型
+ public string? LandmarkModelPath { get; set; }
+
+ /// 检测到的手最多几只
+ public int MaxHands { get; set; } = 2;
+
+ /// 允许 GPU(CUDA 不可用自动回退 CPU)
+ public bool PreferGpu { get; set; }
+
+ ///
+ /// 抽帧间隔:推理跟不上时丢弃中间帧,绝不排队堆积。
+ /// 1 = 每帧都处理;2 = 每 2 帧处理 1 帧。
+ ///
+ public int FrameStride { get; set; } = 1;
+}
+
+///
+/// 采集 → 推理 → 结果。管线只做这一件事,SOP 判定在引擎层(解耦,可单测)。
+///
+public class DetectionPipeline : IDisposable
+{
+ private readonly ICameraService _camera;
+ private readonly YoloDetector _yolo = new();
+ private readonly MediaPipeHandDetector _hand = new();
+
+ private PipelineOptions _options = new();
+ private long _seen;
+ private long _processed;
+
+ /// 管线就绪度(缺哪个模型就在这里报告,界面据此提示)
+ public List Warnings { get; private set; } = [];
+
+ /// 实际帧率(处理后的结果帧率)
+ public double ResultFps { get; private set; }
+
+ /// 推理平均耗时(毫秒)
+ public double AvgInferenceMs { get; private set; }
+
+ /// 结果帧(在管线线程上触发)
+ public event Action? ResultArrived;
+
+ ///
+ /// 采集 → 推理 → 结果
+ ///
+ public DetectionPipeline(ICameraService camera)
+ {
+ _camera = camera;
+ _camera.FrameArrived += OnFrame;
+ }
+
+ ///
+ /// 加载模型。缺文件不抛异常——记进 Warnings,让界面提示,程序照常起。
+ ///
+ public void LoadModels(PipelineOptions options)
+ {
+ _options = options;
+ Warnings = [];
+
+ if (options.YoloModelPath is not null)
+ {
+ if (File.Exists(options.YoloModelPath))
+ {
+ _yolo.Load(options.YoloModelPath, options.YoloClasses, options.YoloInputSize, options.PreferGpu);
+ }
+ else
+ {
+ Warnings.Add($"YOLO 模型不存在:{options.YoloModelPath}(目标类条件不会判定)");
+ }
+ }
+
+ if (options.PalmModelPath is not null && options.LandmarkModelPath is not null)
+ {
+ if (File.Exists(options.PalmModelPath) && File.Exists(options.LandmarkModelPath))
+ {
+ _hand.Load(options.PalmModelPath, options.LandmarkModelPath, options.PreferGpu);
+ }
+ else
+ {
+ Warnings.Add("MediaPipe 手部模型缺失,手部类条件不会判定");
+ }
+ }
+
+ _hand.SetThresholds(0.5f, 0.5f, Math.Max(1, options.MaxHands));
+ }
+
+ ///
+ /// 阈值透传给检测器(界面上的 YOLO 阈值滑条走这里)
+ ///
+ public void SetThresholds(float yoloConf, float yoloNms)
+ {
+ _yolo.SetThresholds(yoloConf, yoloNms);
+ }
+
+ ///
+ /// 启动(相机需已连接)
+ ///
+ public async Task StartAsync()
+ {
+ _seen = 0;
+ _processed = 0;
+
+ return await _camera.StartAsync();
+ }
+
+ ///
+ /// 停止
+ ///
+ public void Stop()
+ {
+ _camera.Stop();
+ }
+
+ ///
+ /// 处理一帧:按 stride 抽帧,跑 YOLO + 手部,合成 FrameResult
+ ///
+ private void OnFrame(CameraFrame frame)
+ {
+ _seen++;
+
+ var stride = Math.Max(1, _options.FrameStride);
+ if (_seen % stride != 0) return;
+
+ var watch = System.Diagnostics.Stopwatch.StartNew();
+
+ var result = new FrameResult
+ {
+ FrameId = frame.FrameId,
+ Timestamp = frame.Timestamp,
+ Size = (frame.Bgr.Width, frame.Bgr.Height),
+ };
+
+ try
+ {
+ if (_yolo.IsReady)
+ {
+ result.Detections = _yolo.Detect(frame.Bgr);
+ }
+
+ if (_hand.IsReady)
+ {
+ result.Hands = _hand.Detect(frame.Bgr);
+ }
+ }
+ catch (Exception ex)
+ {
+ Warnings.Add($"推理异常:{ex.Message}");
+ }
+
+ watch.Stop();
+
+ result.InferenceMs = watch.Elapsed.TotalMilliseconds;
+ _processed++;
+
+ // 累计平均(结果帧率按处理过的帧算)
+ var ms = result.InferenceMs;
+ AvgInferenceMs = AvgInferenceMs <= 0 ? ms : AvgInferenceMs * 0.9 + ms * 0.1;
+ ResultFps = AvgInferenceMs <= 0 ? 0 : 1000.0 / AvgInferenceMs;
+
+ ResultArrived?.Invoke(result);
+ }
+
+ ///
+ public void Dispose()
+ {
+ _camera.FrameArrived -= OnFrame;
+ _yolo.Dispose();
+ _hand.Dispose();
+ }
+}