将按需 YOLO 推理接入相机与视频回测

This commit is contained in:
wanglei 2026-12-06 18:35:14 +08:00
parent 65913be0c2
commit 62bfbd700b
8 changed files with 167 additions and 15 deletions

View File

@ -29,6 +29,15 @@ internal static class DesktopPlatform
}
}
public static string ApplicationRoot => AppContext.BaseDirectory;
/// <summary>先查工作区模型,再按旧配方约定查程序目录。文件缺失时保留工作区路径用于诊断。</summary>
public static string ResolveYoloModel(string path)
{
if (Path.IsPathFullyQualified(path)) return path;
var workspacePath = Path.Combine(WorkspaceRoot, path);
var applicationPath = Path.Combine(ApplicationRoot, path);
return File.Exists(workspacePath) || !File.Exists(applicationPath) ? workspacePath : applicationPath;
}
private static string? LegacySourceRoot
{
get

View File

@ -93,6 +93,8 @@ public sealed partial class CameraViewModel
FlowTestVideoResult = $"步骤 {request.StepId} · 送检帧 {request.FrameId}\n检查{(accepted ? "通过" : "未通过")} · {probability}";
});
await Task.Run(test.LoadModels);
// 载入模型期间可能已停止测试,旧回测不能重新绑定播放器。
if (!ReferenceEquals(_flowTest, test) || _closing) return;
test.Start();
FlowTestDetails = test.Details;
FlowTestStatus = "正在播放标准视频并检测流程(使用当前编辑配置)";

View File

@ -1,4 +1,4 @@
// 标准视频流程回测:把视频帧送入手部推理与 SOP 引擎,记录触发、送检及完成结果。
// 标准视频流程回测:把视频帧送入按需推理与 SOP 引擎,记录触发、送检及完成结果。
using System.Net.Http;
using OpenCvSharp;
@ -13,6 +13,7 @@ public sealed class SopVideoFlowTest : IDisposable
{
private static readonly HttpClient VisionHttp = new() { Timeout = Timeout.InfiniteTimeSpan };
private readonly MediaPipeHandDetector _hands = new();
private readonly YoloDetector _objects = new();
private readonly SopEngine _engine = new();
private readonly Dictionary<int, StepSnapshot> _steps = [];
private readonly int _stride;
@ -74,15 +75,22 @@ public sealed class SopVideoFlowTest : IDisposable
public void Start() => _engine.Start();
/// <summary>根据回测配方加载手部模型,供视频帧使用与运行流程一致的检测实现。</summary>
/// <summary>按配方加载回测所需模型,与在线检测共用物品模型配置。</summary>
public void LoadModels()
{
// 视频回测与实时运行按相同的取图需求加载手部模型。
// 加载与逐帧推理、销毁互斥,停止回测后不能再创建新会话。
lock (_gate)
{
if (_disposed) return;
if (YoloInferenceOptions.FromRecipe(_engine.Config, SopHelper.Presentation.DesktopPlatform.ResolveYoloModel) is { } model)
_objects.Load(model, preferGpu: true, requireGpu: OperatingSystem.IsLinux());
if (!_engine.Config.Sop.Steps.Any(step => step.NeedsHandDetection())) return;
_hands.Load(Path.Combine(AppContext.BaseDirectory, "models/palm_detection_full_Nx3x192x192_post.onnx"),
Path.Combine(AppContext.BaseDirectory, "models/hand_landmark_sparse_Nx3x224x224.onnx"), requireGpu: OperatingSystem.IsLinux());
if (!_hands.IsReady) throw new InvalidOperationException("手部模型缺失,无法测试流程,请检查 models 目录");
}
}
public void ProcessFrame(Mat image, long frameId, double seconds)
{
@ -94,13 +102,19 @@ public sealed class SopVideoFlowTest : IDisposable
{
if (++_seen % _stride != 0) return null;
var result = new FrameResult { FrameId = frameId, Timestamp = DateTime.Now, SourceSeconds = seconds, Size = (image.Width, image.Height) };
// 与 Dispose 使用同一把锁,避免停止回测时释放仍在执行的原生模型会话。
lock (_gate)
{
if (_disposed) return null;
if (_hands.IsReady) result.Hands = _hands.Detect(image);
if (_engine.RequiresObjectDetection) _objects.DetectInto(image, result);
FrameObserved?.Invoke(result, seconds);
ProcessResult(result, image);
return result;
}
}
/// <summary>使用与正式运行相同的原帧裁剪、手部门控和 AI 完成判定。</summary>
/// <summary>使用与正式运行相同的原帧裁剪、触发门控和 AI 完成判定。</summary>
/// <remarks>将已完成推理的帧及对应图像交给 SOP 引擎,用同一幅原图完成取证。</remarks>
public void ProcessResult(FrameResult result, Mat image)
{
@ -144,6 +158,6 @@ public sealed class SopVideoFlowTest : IDisposable
/// <summary>停止回测状态机并释放本回测实例的模型资源。</summary>
public void Dispose()
{
lock (_gate) { _disposed = true; _engine.Stop(); _hands.Dispose(); }
lock (_gate) { _disposed = true; _engine.Stop(); _hands.Dispose(); _objects.Dispose(); }
}
}

View File

@ -129,6 +129,7 @@ public class SopPageViewModel : ViewModelBase
_engine.StepCountStore ??= SopHelper.Models.StepCountsStore.Current;
_engine.VisionDecisionClient ??= new ConfiguredVisionDecisionClient(VisionHttp);
_pipeline.ShouldDetectHands = () => _engine.RequiresHandDetection;
_pipeline.ShouldDetectObjects = () => _engine.RequiresObjectDetection;
_dialogs = dialogs;
_dispatcher = Dispatcher.CurrentDispatcher;
_runtimeOptions = _runtimeStore.Read() ?? new();
@ -1072,6 +1073,7 @@ public class SopPageViewModel : ViewModelBase
// 文件名必须和 models/ 下实际一致,否则 ResolveModel 返回 null、手部链路静默不跑
PalmModelPath = needsHands ? ResolveModel("models/palm_detection_full_Nx3x192x192_post.onnx") : null,
LandmarkModelPath = needsHands ? ResolveModel("models/hand_landmark_sparse_Nx3x224x224.onnx") : null,
ObjectModel = SopHelper.Engine.Inference.YoloInferenceOptions.FromRecipe(config, DesktopPlatform.ResolveYoloModel),
FrameStride = Math.Max(1, config.Sop.Settings.FrameStride),
RequireGpu = OperatingSystem.IsLinux(),
};
@ -1083,7 +1085,8 @@ public class SopPageViewModel : ViewModelBase
ActiveRecipe = selected;
RaisePropertyChanged(nameof(InferenceBackendText));
RaisePropertyChanged(nameof(FrameStride)); RaisePropertyChanged(nameof(AutoResetOnComplete)); RaisePropertyChanged(nameof(ResetDelaySec));
Log("info", $"推理设备:手部={_pipeline.HandBackend},步骤确认={VisionProviderName}");
var objectBackend = options.ObjectModel is null ? "" : $",物品={_pipeline.ObjectBackend}";
Log("info", $"推理设备:手部={_pipeline.HandBackend}{objectBackend},步骤确认={VisionProviderName}");
ClearProcessImages();
StepCards.Clear();

View File

@ -97,6 +97,15 @@ public class YoloDetector : IDisposable
catch { Dispose(); throw; }
}
/// <summary>加载配方模型并设置预过滤阈值。缺少文件或模型格式无效时抛出,调用方负责提示。</summary>
public void Load(YoloInferenceOptions options, bool preferGpu, bool requireGpu)
{
if (string.IsNullOrWhiteSpace(options.Path)) throw new InvalidOperationException("请在配方中配置 YOLO ONNX 模型路径");
Load(options.Path, options.Classes, options.InputSize, preferGpu, requireGpu);
if (!IsReady) throw new FileNotFoundException($"找不到 YOLO 模型:{options.Path}", options.Path);
SetThresholds(options.MinConfidence, 0.45f);
}
/// <summary>
/// 阈值
/// </summary>
@ -270,6 +279,14 @@ public class YoloDetector : IDisposable
return list;
}
/// <summary>把本帧推理结果附在原图对应的结果对象上;成功返回空列表也表示推理已执行。</summary>
public void DetectInto(Mat bgr, FrameResult frame)
{
if (!IsReady) return;
frame.Detections = Detect(bgr);
frame.ObjectDetectionRan = true;
}
/// <summary>
/// DFL(Distribution Focal Loss)解码:对 4 组 16 bin 做 softmax 取期望,得到边界框
/// </summary>

View File

@ -0,0 +1,27 @@
using SopHelper.Engine.Sop;
namespace SopHelper.Engine.Inference;
/// <summary>相机与视频回测共用的 YOLO 模型配置,按配方中实际使用的规则保留所需置信度范围。</summary>
public sealed record YoloInferenceOptions(string Path, IReadOnlyList<string> Classes, int InputSize, float MinConfidence)
{
/// <summary>没有物品规则时返回空。保留缺失路径以便加载阶段给出明确错误。</summary>
public static YoloInferenceOptions? FromRecipe(SopConfig config, Func<string, string> resolvePath)
{
var conditions = config.Sop.Steps
.Select(step => step.Detection)
.OfType<StepCondition>()
.Where(condition => ConditionMethod.RequiresObjectDetection(condition.Method))
.ToArray();
if (conditions.Length == 0) return null;
var model = config.Sop.Model ?? new ModelDef();
// 模型只提前过滤低于所有步骤要求的结果,各步骤仍按自己的阈值判定。
var minConfidence = conditions.Select(condition => condition.MinConfidence)
.Where(confidence => float.IsFinite(confidence) && confidence is >= 0 and <= 1)
.DefaultIfEmpty(0.7f)
.Min();
var path = string.IsNullOrWhiteSpace(model.Path) ? "" : resolvePath(model.Path.Trim());
return new(path, model.Classes ?? [], model.InputSize, minConfidence);
}
}

View File

@ -18,6 +18,9 @@ public class PipelineOptions
/// <summary>MediaPipe 关键点模型</summary>
public string? LandmarkModelPath { get; set; }
/// <summary>物品触发配方使用的模型。未配置时不建立 YOLO 会话。</summary>
public YoloInferenceOptions? ObjectModel { get; set; }
/// <summary>检测到的手最多几只</summary>
public int MaxHands { get; set; } = 2;
@ -40,6 +43,7 @@ public class DetectionPipeline : IDisposable
{
private readonly ICameraService _camera;
private MediaPipeHandDetector _hand = new();
private YoloDetector _objects = new();
private PipelineOptions _options = new();
private long _seen;
@ -64,9 +68,15 @@ public class DetectionPipeline : IDisposable
public string HandBackend => _hand.Backend;
/// <summary>当前配方物品模型实际使用的推理设备。</summary>
public string ObjectBackend => _objects.Backend;
/// <summary>每帧查询当前步骤是否需要手部;未设置时保持独立管线的默认检测行为。</summary>
public Func<bool>? ShouldDetectHands { get; set; }
/// <summary>在后台逐帧查询物品检测需求,默认关闭。即使模型已加载也必须经此门控。</summary>
public Func<bool>? ShouldDetectObjects { get; set; }
/// <summary>结果帧(在管线线程上触发)</summary>
public event Action<FrameResult>? ResultArrived;
@ -87,6 +97,7 @@ public class DetectionPipeline : IDisposable
public void LoadModels(PipelineOptions options)
{
var next = new MediaPipeHandDetector();
var nextObjects = new YoloDetector();
var warnings = new List<string>();
try
{
@ -113,20 +124,37 @@ public class DetectionPipeline : IDisposable
next.SetThresholds(MediaPipeHandDetector.DefaultPalmThreshold,
MediaPipeHandDetector.DefaultKeypointThreshold, Math.Max(1, options.MaxHands));
if (options.ObjectModel is { } objectModel)
{
try
{
nextObjects.Load(objectModel, options.PreferGpu, options.RequireGpu);
if (nextObjects.GpuFallbackReason is { } reason) warnings.Add($"YOLO GPU 不可用,已回退 CPU:{reason}");
}
catch (Exception ex) when (!options.RequireGpu || nextObjects.GpuFallbackReason is null)
{
warnings.Add("YOLO 模型加载失败:" + ex.Message);
}
}
StopProcessing();
}
catch
{
next.Dispose();
nextObjects.Dispose();
throw;
}
// 旧工作线程退出后,交接模型所有权并释放旧会话。
var previous = _hand;
var previousObjects = _objects;
_hand = next;
_objects = nextObjects;
_options = options;
Warnings = warnings;
previous.Dispose();
previousObjects.Dispose();
}
/// <summary>
@ -243,7 +271,7 @@ public class DetectionPipeline : IDisposable
}
}
/// <summary>按当前步骤需求运行手部检测,更新推理耗时,并在未取消时发布本帧结果及原图。</summary>
/// <summary>按步骤需求执行手部和物品推理;两者复用同一原帧,未取消时发布对应结果。</summary>
private void ProcessFrame(CameraFrame frame, CancellationToken token)
{
var watch = System.Diagnostics.Stopwatch.StartNew();
@ -261,6 +289,12 @@ public class DetectionPipeline : IDisposable
catch (Exception ex) { ReportInferenceWarning("手部推理异常:" + ex.Message); }
}
if (_objects.IsReady && ShouldDetectObjects?.Invoke() == true)
{
try { _objects.DetectInto(frame.Bgr, result); }
catch (Exception ex) { ReportInferenceWarning("YOLO 推理异常:" + ex.Message); }
}
watch.Stop();
result.InferenceMs = watch.Elapsed.TotalMilliseconds;
@ -295,5 +329,6 @@ public class DetectionPipeline : IDisposable
StopProcessing();
_frameSignal.Dispose();
_hand.Dispose();
_objects.Dispose();
}
}

View File

@ -2,6 +2,7 @@ using System.Collections.Concurrent;
using OpenCvSharp;
using SopHelper.Engine.Camera;
using SopHelper.Engine.Pipeline;
using SopHelper.Engine.Inference;
using SopHelper.Engine.Sop;
using SopHelper.Engine.Common;
@ -117,6 +118,50 @@ if (results.Count != 5 || results.Last() != 17 || !imageResults.SequenceEqual(re
throw new Exception("Video input did not isolate sources or preserve stride and frame ownership");
Console.WriteLine("PASS: Video input isolates sources and uses the regular inference worker");
// 1×5×1 的微型 ONNX 模型固定返回一个 box 检测框,用真实 ORT 会话验证门控及原图坐标。
var modelDirectory = Path.Combine("scratch", "test-results");
Directory.CreateDirectory(modelDirectory);
var objectModel = Path.GetFullPath(Path.Combine(modelDirectory, "pipeline-object-test.onnx"));
File.WriteAllBytes(objectModel, Convert.FromBase64String(
"CAg6lgEKQhIKZGV0ZWN0aW9ucyIIQ29uc3RhbnQqKgoFdmFsdWUqHggBCAUIARABShQAAIBBAACAQQAAQEEAAEBBZmZmP6ABBBIMdGVzdF9vYmplY3RzWiAKBmltYWdlcxIWChQIARIQCgIIAQoCCAMKAgggCgIIIGIgCgpkZXRlY3Rpb25zEhIKEAgBEgwKAggBCgIIBQoCCAFCAhANchEKBW5hbWVzEgh7MDogYm94fQ=="));
try
{
using var objectCamera = new TestCamera();
using var objectPipeline = new DetectionPipeline(objectCamera);
using var objectFrames = new BlockingCollection<FrameResult>();
objectPipeline.ResultArrived += objectFrames.Add;
objectPipeline.LoadModels(new PipelineOptions
{
PreferGpu = false,
ObjectModel = new YoloInferenceOptions(objectModel, [], 640, .8f),
});
if (objectPipeline.Warnings.Count != 0 || objectPipeline.ObjectBackend != "CPU")
throw new Exception("物品模型加载失败:" + string.Join(";", objectPipeline.Warnings));
var demand = 0;
objectPipeline.ShouldDetectObjects = () => Volatile.Read(ref demand) == 1;
objectPipeline.StartVideoInput();
using var image = new Mat(16, 32, MatType.CV_8UC3, Scalar.Black);
FrameResult ReadFrame(int id, int requested)
{
Volatile.Write(ref demand, requested);
objectPipeline.SubmitVideoFrame(image, id);
if (!objectFrames.TryTake(out var result, TimeSpan.FromSeconds(5)) || result.FrameId != id)
throw new Exception($"未收到物品检测测试帧 {id}");
return result;
}
var idle = ReadFrame(1, 0);
var detected = ReadFrame(2, 1);
var after = ReadFrame(3, 0);
objectPipeline.StopVideoInput();
if (idle.ObjectDetectionRan || after.ObjectDetectionRan || after.Detections.Count != 0)
throw new Exception("没有检测需求时不应执行 YOLO 或复用历史结果");
var item = detected.Detections.Single();
if (!detected.ObjectDetectionRan || item.Label != "box" || item.Rect.Center != (16f, 8f))
throw new Exception("物品检测结果未映射回当前帧的原图坐标");
Console.WriteLine("PASS: YOLO 仅在有需求时执行真实推理,结果属于当前帧并使用原图坐标");
}
finally { File.Delete(objectModel); }
internal sealed class TestCamera : ICameraService
{
public bool IsConnected => true;