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 类型
This commit is contained in:
parent
e55bd9348a
commit
061b8cd3be
74
src/SopHelper.Engine/Camera/ICameraService.cs
Normal file
74
src/SopHelper.Engine/Camera/ICameraService.cs
Normal file
@ -0,0 +1,74 @@
|
||||
using OpenCvSharp;
|
||||
|
||||
namespace SopHelper.Engine.Camera;
|
||||
|
||||
/// <summary>
|
||||
/// 相机信息
|
||||
/// </summary>
|
||||
public class CameraInfo
|
||||
{
|
||||
/// <summary>索引(UVC 设备号)</summary>
|
||||
public int Index { get; set; }
|
||||
|
||||
/// <summary>名称</summary>
|
||||
public string Name { get; set; } = "";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 一帧原始图像(BGR Mat,附帧号与实测帧率)
|
||||
/// </summary>
|
||||
public class CameraFrame : IDisposable
|
||||
{
|
||||
/// <summary>帧号(相机侧累计)</summary>
|
||||
public long FrameId { get; set; }
|
||||
|
||||
/// <summary>采集时刻</summary>
|
||||
public DateTime Timestamp { get; set; }
|
||||
|
||||
/// <summary>BGR 图像(由本类持有,消费方不得跨帧持有)</summary>
|
||||
public required Mat Bgr { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 释放
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
Bgr.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// USB(UVC)相机服务。单相机最小版:一个采集线程 + 帧事件。
|
||||
/// </summary>
|
||||
public interface ICameraService : IDisposable
|
||||
{
|
||||
/// <summary>是否已连接</summary>
|
||||
bool IsConnected { get; }
|
||||
|
||||
/// <summary>是否正在采集</summary>
|
||||
bool IsGrabbing { get; }
|
||||
|
||||
/// <summary>新帧(在采集线程上触发,消费方用完不得保留 Mat)</summary>
|
||||
event Action<CameraFrame>? FrameArrived;
|
||||
|
||||
/// <summary>连接状态变化</summary>
|
||||
event Action<bool>? ConnectionChanged;
|
||||
|
||||
/// <summary>错误</summary>
|
||||
event Action<string>? Error;
|
||||
|
||||
/// <summary>枚举可用 UVC 相机</summary>
|
||||
Task<List<CameraInfo>> EnumerateAsync();
|
||||
|
||||
/// <summary>连接相机</summary>
|
||||
Task<bool> ConnectAsync(CameraInfo camera);
|
||||
|
||||
/// <summary>开始采集</summary>
|
||||
Task<bool> StartAsync();
|
||||
|
||||
/// <summary>停止采集</summary>
|
||||
void Stop();
|
||||
|
||||
/// <summary>断开</summary>
|
||||
void Disconnect();
|
||||
}
|
||||
288
src/SopHelper.Engine/Camera/UvcCameraService.cs
Normal file
288
src/SopHelper.Engine/Camera/UvcCameraService.cs
Normal file
@ -0,0 +1,288 @@
|
||||
using OpenCvSharp;
|
||||
|
||||
namespace SopHelper.Engine.Camera;
|
||||
|
||||
/// <summary>
|
||||
/// USB(UVC)相机实现。单相机最小版。
|
||||
/// 三个坑照搬参考项目实测结论:MSMF 优先、DSHOW 图必须进程级串行、不可重复打开同一索引。
|
||||
/// </summary>
|
||||
public class UvcCameraService : ICameraService
|
||||
{
|
||||
/// <summary>
|
||||
/// 进程级 DSHOW 互斥锁:DirectShow 原生图不允许并发创建/销毁,
|
||||
/// 旧图还在异步销毁时开新图会触发 AccessViolationException。
|
||||
/// </summary>
|
||||
private static readonly object DshowLock = new();
|
||||
|
||||
private readonly object _captureLock = new();
|
||||
private VideoCapture? _capture;
|
||||
private CancellationTokenSource? _cts;
|
||||
private Task? _grabTask;
|
||||
private long _frameId;
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsConnected { get; private set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsGrabbing { get; private set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public event Action<CameraFrame>? FrameArrived;
|
||||
|
||||
/// <inheritdoc />
|
||||
public event Action<bool>? ConnectionChanged;
|
||||
|
||||
/// <inheritdoc />
|
||||
public event Action<string>? Error;
|
||||
|
||||
/// <summary>当前相机</summary>
|
||||
public CameraInfo? Current { get; private set; }
|
||||
|
||||
/// <summary>实测帧率(每 2 秒刷新一次)</summary>
|
||||
public double ActualFps { get; private set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<List<CameraInfo>> EnumerateAsync()
|
||||
{
|
||||
return Task.Run(() =>
|
||||
{
|
||||
var list = new List<CameraInfo>();
|
||||
|
||||
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;
|
||||
});
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<bool> 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;
|
||||
});
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<bool> 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;
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 采集循环
|
||||
/// </summary>
|
||||
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;
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Stop()
|
||||
{
|
||||
_cts?.Cancel();
|
||||
|
||||
try
|
||||
{
|
||||
_grabTask?.Wait(TimeSpan.FromSeconds(2));
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 取消异常忽略
|
||||
}
|
||||
|
||||
_grabTask = null;
|
||||
_cts?.Dispose();
|
||||
_cts = null;
|
||||
IsGrabbing = false;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
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);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Dispose()
|
||||
{
|
||||
Disconnect();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 用指定后端尝试打开
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
158
src/SopHelper.Engine/Common/Types.cs
Normal file
158
src/SopHelper.Engine/Common/Types.cs
Normal file
@ -0,0 +1,158 @@
|
||||
namespace SopHelper.Engine.Common;
|
||||
|
||||
/// <summary>
|
||||
/// 轻量矩形。引擎层只用这个,不绑定 OpenCvSharp / SkiaSharp 类型
|
||||
/// (参考项目把 SkiaSharp 和 YoloDotNet.Models 写进了判定层,导致那一层无法单独抽走)
|
||||
/// </summary>
|
||||
public struct DetRect
|
||||
{
|
||||
/// <summary>X</summary>
|
||||
public float X;
|
||||
|
||||
/// <summary>Y</summary>
|
||||
public float Y;
|
||||
|
||||
/// <summary>W</summary>
|
||||
public float W;
|
||||
|
||||
/// <summary>H</summary>
|
||||
public float H;
|
||||
|
||||
/// <summary>
|
||||
/// 轻量矩形
|
||||
/// </summary>
|
||||
public DetRect(float x, float y, float w, float h)
|
||||
{
|
||||
X = x; Y = y; W = w; H = h;
|
||||
}
|
||||
|
||||
/// <summary>右边界</summary>
|
||||
public float Right => X + W;
|
||||
|
||||
/// <summary>下边界</summary>
|
||||
public float Bottom => Y + H;
|
||||
|
||||
/// <summary>中心点</summary>
|
||||
public (float Cx, float Cy) Center => ((X + Right) / 2f, (Y + Bottom) / 2f);
|
||||
|
||||
/// <summary>
|
||||
/// 点是否落在矩形内(pad 为外扩像素,负数=内缩)
|
||||
/// </summary>
|
||||
public bool Contains(float px, float py, float pad = 0f)
|
||||
=> px >= X - pad && px <= Right + pad && py >= Y - pad && py <= Bottom + pad;
|
||||
|
||||
/// <summary>
|
||||
/// 两矩形是否相交(pad 为其中一个的外扩像素)
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 一次目标检测结果
|
||||
/// </summary>
|
||||
public class Detection
|
||||
{
|
||||
/// <summary>类别名(模型输出顺序映射而来)</summary>
|
||||
public string Label { get; set; } = "";
|
||||
|
||||
/// <summary>置信度</summary>
|
||||
public float Confidence { get; set; }
|
||||
|
||||
/// <summary>像素坐标框</summary>
|
||||
public DetRect Rect { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 手部类型
|
||||
/// </summary>
|
||||
public enum HandType
|
||||
{
|
||||
/// <summary>未知</summary>
|
||||
Unknown = 0,
|
||||
|
||||
/// <summary>左手</summary>
|
||||
Left = 1,
|
||||
|
||||
/// <summary>右手</summary>
|
||||
Right = 2,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 一个手部关键点(MediaPipe 21 点之一)
|
||||
/// </summary>
|
||||
public class HandPoint
|
||||
{
|
||||
/// <summary>关键点序号 0-20(0=手腕)</summary>
|
||||
public int Index { get; set; }
|
||||
|
||||
/// <summary>像素坐标 X</summary>
|
||||
public float X { get; set; }
|
||||
|
||||
/// <summary>像素坐标 Y</summary>
|
||||
public float Y { get; set; }
|
||||
|
||||
/// <summary>相对深度</summary>
|
||||
public float Z { get; set; }
|
||||
|
||||
/// <summary>该点置信度(部分 ONNX 导出无逐点置信度,由上层填固定值)</summary>
|
||||
public float Confidence { get; set; } = 1f;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 一只手的结果
|
||||
/// </summary>
|
||||
public class Hand
|
||||
{
|
||||
/// <summary>左右手判定</summary>
|
||||
public HandType HandType { get; set; } = HandType.Unknown;
|
||||
|
||||
/// <summary>手部(手掌)框</summary>
|
||||
public DetRect Rect { get; set; }
|
||||
|
||||
/// <summary>21 个关键点,已映射回原图像素坐标</summary>
|
||||
public List<HandPoint> Keypoints { get; set; } = [];
|
||||
|
||||
/// <summary>手掌检测置信度</summary>
|
||||
public float Confidence { get; set; }
|
||||
|
||||
/// <summary>所有关键点的几何中心(判定"手在哪个区域"就用它)</summary>
|
||||
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));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 一帧的完整推理结果,喂给 SOP 引擎的就是它
|
||||
/// </summary>
|
||||
public class FrameResult
|
||||
{
|
||||
/// <summary>帧号</summary>
|
||||
public long FrameId { get; set; }
|
||||
|
||||
/// <summary>帧时间戳</summary>
|
||||
public DateTime Timestamp { get; set; }
|
||||
|
||||
/// <summary>原图像素尺寸</summary>
|
||||
public (int W, int H) Size { get; set; }
|
||||
|
||||
/// <summary>YOLO 检出目标</summary>
|
||||
public List<Detection> Detections { get; set; } = [];
|
||||
|
||||
/// <summary>检出的手</summary>
|
||||
public List<Hand> Hands { get; set; } = [];
|
||||
|
||||
/// <summary>本帧推理耗时(毫秒)</summary>
|
||||
public double InferenceMs { get; set; }
|
||||
}
|
||||
376
src/SopHelper.Engine/Inference/MediaPipeHandDetector.cs
Normal file
376
src/SopHelper.Engine/Inference/MediaPipeHandDetector.cs
Normal file
@ -0,0 +1,376 @@
|
||||
using Microsoft.ML.OnnxRuntime;
|
||||
using Microsoft.ML.OnnxRuntime.Tensors;
|
||||
using OpenCvSharp;
|
||||
using SopHelper.Engine.Common;
|
||||
|
||||
namespace SopHelper.Engine.Inference;
|
||||
|
||||
/// <summary>
|
||||
/// MediaPipe 手部(两阶段 ONNX,纯 C# 实现,照搬参考项目的解析逻辑)。
|
||||
/// 第一阶段手掌检测 → 方形裁剪 → 第二阶段 21 关键点。
|
||||
/// </summary>
|
||||
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;
|
||||
|
||||
/// <summary>模型是否就绪(缺文件时上层跳过手部判定,不报错)</summary>
|
||||
public bool IsReady => _palm is not null && _landmark is not null;
|
||||
|
||||
/// <summary>实际使用的设备(CUDA 不可用时回退 CPU)</summary>
|
||||
public bool UsingGpu { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// 加载两个模型。任缺其一则整个手部检测不启用。
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 阈值
|
||||
/// </summary>
|
||||
public void SetThresholds(float palm, float keypoint, int maxHands)
|
||||
{
|
||||
_palmThreshold = palm;
|
||||
_keypointThreshold = keypoint;
|
||||
_maxHands = Math.Max(1, maxHands);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 检测一帧(BGR)里的所有手
|
||||
/// </summary>
|
||||
public List<Hand> Detect(Mat bgr)
|
||||
{
|
||||
var hands = new List<Hand>();
|
||||
if (!IsReady) return hands;
|
||||
|
||||
// 涂黑副本:检出一只手后把该区域抹掉,再跑下一遍,避免重复选中同一只手
|
||||
using var working = bgr.Clone();
|
||||
var taken = new List<DetRect>();
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 第一阶段:手掌检测
|
||||
/// </summary>
|
||||
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> { 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 第二阶段:对手掌框做 21 关键点
|
||||
/// </summary>
|
||||
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> { 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<HandPoint>();
|
||||
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 手型判定:该 ONNX 导出无 handedness 输出,用拇指尖相对其余指心的位置粗判
|
||||
/// (MediaPipe 官方 handedness 在镜像图上会互换,故此处只做提示,不参与判定门控)。
|
||||
/// </summary>
|
||||
private static HandType GuessHandType(List<HandPoint> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// BGR → RGB float [1,3,size,size],归一化 [0,1]
|
||||
/// </summary>
|
||||
private static DenseTensor<float> 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<float>([1, 3, size, size]);
|
||||
|
||||
for (var yy = 0; yy < size; yy++)
|
||||
{
|
||||
for (var xx = 0; xx < size; xx++)
|
||||
{
|
||||
var px = resized.At<Vec3b>(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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 把区域涂黑(从副本上"拿走"这只手)
|
||||
/// </summary>
|
||||
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<float>? TryTensor(DisposableNamedOnnxValue v)
|
||||
{
|
||||
try
|
||||
{
|
||||
return v.AsTensor<float>();
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Dispose()
|
||||
{
|
||||
_palm?.Dispose();
|
||||
_landmark?.Dispose();
|
||||
_palm = null;
|
||||
_landmark = null;
|
||||
}
|
||||
}
|
||||
340
src/SopHelper.Engine/Inference/YoloDetector.cs
Normal file
340
src/SopHelper.Engine/Inference/YoloDetector.cs
Normal file
@ -0,0 +1,340 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
193
src/SopHelper.Engine/Pipeline/DetectionPipeline.cs
Normal file
193
src/SopHelper.Engine/Pipeline/DetectionPipeline.cs
Normal file
@ -0,0 +1,193 @@
|
||||
using OpenCvSharp;
|
||||
using SopHelper.Engine.Camera;
|
||||
using SopHelper.Engine.Common;
|
||||
using SopHelper.Engine.Inference;
|
||||
|
||||
namespace SopHelper.Engine.Pipeline;
|
||||
|
||||
/// <summary>
|
||||
/// 管线配置
|
||||
/// </summary>
|
||||
public class PipelineOptions
|
||||
{
|
||||
/// <summary>YOLO 模型路径(可空:纯手部配方不需要)</summary>
|
||||
public string? YoloModelPath { get; set; }
|
||||
|
||||
/// <summary>类别名,顺序必须与训练一致</summary>
|
||||
public List<string> YoloClasses { get; set; } = [];
|
||||
|
||||
/// <summary>YOLO 输入尺寸</summary>
|
||||
public int YoloInputSize { get; set; } = 640;
|
||||
|
||||
/// <summary>MediaPipe 手掌模型(可空:不需要手部的配方不加载)</summary>
|
||||
public string? PalmModelPath { get; set; }
|
||||
|
||||
/// <summary>MediaPipe 关键点模型</summary>
|
||||
public string? LandmarkModelPath { get; set; }
|
||||
|
||||
/// <summary>检测到的手最多几只</summary>
|
||||
public int MaxHands { get; set; } = 2;
|
||||
|
||||
/// <summary>允许 GPU(CUDA 不可用自动回退 CPU)</summary>
|
||||
public bool PreferGpu { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 抽帧间隔:推理跟不上时丢弃中间帧,绝不排队堆积。
|
||||
/// 1 = 每帧都处理;2 = 每 2 帧处理 1 帧。
|
||||
/// </summary>
|
||||
public int FrameStride { get; set; } = 1;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 采集 → 推理 → 结果。管线只做这一件事,SOP 判定在引擎层(解耦,可单测)。
|
||||
/// </summary>
|
||||
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;
|
||||
|
||||
/// <summary>管线就绪度(缺哪个模型就在这里报告,界面据此提示)</summary>
|
||||
public List<string> Warnings { get; private set; } = [];
|
||||
|
||||
/// <summary>实际帧率(处理后的结果帧率)</summary>
|
||||
public double ResultFps { get; private set; }
|
||||
|
||||
/// <summary>推理平均耗时(毫秒)</summary>
|
||||
public double AvgInferenceMs { get; private set; }
|
||||
|
||||
/// <summary>结果帧(在管线线程上触发)</summary>
|
||||
public event Action<FrameResult>? ResultArrived;
|
||||
|
||||
/// <summary>
|
||||
/// 采集 → 推理 → 结果
|
||||
/// </summary>
|
||||
public DetectionPipeline(ICameraService camera)
|
||||
{
|
||||
_camera = camera;
|
||||
_camera.FrameArrived += OnFrame;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 加载模型。缺文件不抛异常——记进 Warnings,让界面提示,程序照常起。
|
||||
/// </summary>
|
||||
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));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 阈值透传给检测器(界面上的 YOLO 阈值滑条走这里)
|
||||
/// </summary>
|
||||
public void SetThresholds(float yoloConf, float yoloNms)
|
||||
{
|
||||
_yolo.SetThresholds(yoloConf, yoloNms);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 启动(相机需已连接)
|
||||
/// </summary>
|
||||
public async Task<bool> StartAsync()
|
||||
{
|
||||
_seen = 0;
|
||||
_processed = 0;
|
||||
|
||||
return await _camera.StartAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 停止
|
||||
/// </summary>
|
||||
public void Stop()
|
||||
{
|
||||
_camera.Stop();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 处理一帧:按 stride 抽帧,跑 YOLO + 手部,合成 FrameResult
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Dispose()
|
||||
{
|
||||
_camera.FrameArrived -= OnFrame;
|
||||
_yolo.Dispose();
|
||||
_hand.Dispose();
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user