From 62bfbd700b865186091e0c71eb1a66e593c49b04 Mon Sep 17 00:00:00 2001 From: wanglei Date: Sun, 6 Dec 2026 18:35:14 +0800 Subject: [PATCH] =?UTF-8?q?=E5=B0=86=E6=8C=89=E9=9C=80=20YOLO=20=E6=8E=A8?= =?UTF-8?q?=E7=90=86=E6=8E=A5=E5=85=A5=E7=9B=B8=E6=9C=BA=E4=B8=8E=E8=A7=86?= =?UTF-8?q?=E9=A2=91=E5=9B=9E=E6=B5=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Presentation/DesktopPlatform.cs | 9 ++++ .../SopVideo/CameraFlowTest.cs | 2 + .../SopVideo/SopVideoFlowTest.cs | 40 +++++++++++------ .../VVMs/SopPage/SopPageViewModel.cs | 5 ++- .../Inference/YoloDetector.cs | 17 +++++++ .../Inference/YoloInferenceOptions.cs | 27 +++++++++++ .../Pipeline/DetectionPipeline.cs | 37 ++++++++++++++- tests/Pipeline.Smoke/Program.cs | 45 +++++++++++++++++++ 8 files changed, 167 insertions(+), 15 deletions(-) create mode 100644 src/SopHelper.CrossPlatform.Engine/Inference/YoloInferenceOptions.cs diff --git a/src/SopHelper.Avalonia/Presentation/DesktopPlatform.cs b/src/SopHelper.Avalonia/Presentation/DesktopPlatform.cs index 9c78b16..7b5135e 100644 --- a/src/SopHelper.Avalonia/Presentation/DesktopPlatform.cs +++ b/src/SopHelper.Avalonia/Presentation/DesktopPlatform.cs @@ -29,6 +29,15 @@ internal static class DesktopPlatform } } public static string ApplicationRoot => AppContext.BaseDirectory; + /// 先查工作区模型,再按旧配方约定查程序目录。文件缺失时保留工作区路径用于诊断。 + 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 diff --git a/src/SopHelper.Avalonia/SopVideo/CameraFlowTest.cs b/src/SopHelper.Avalonia/SopVideo/CameraFlowTest.cs index 594bb98..30bb11b 100644 --- a/src/SopHelper.Avalonia/SopVideo/CameraFlowTest.cs +++ b/src/SopHelper.Avalonia/SopVideo/CameraFlowTest.cs @@ -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 = "正在播放标准视频并检测流程(使用当前编辑配置)"; diff --git a/src/SopHelper.Avalonia/SopVideo/SopVideoFlowTest.cs b/src/SopHelper.Avalonia/SopVideo/SopVideoFlowTest.cs index 3f71029..53fdddd 100644 --- a/src/SopHelper.Avalonia/SopVideo/SopVideoFlowTest.cs +++ b/src/SopHelper.Avalonia/SopVideo/SopVideoFlowTest.cs @@ -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 _steps = []; private readonly int _stride; @@ -74,14 +75,21 @@ public sealed class SopVideoFlowTest : IDisposable public void Start() => _engine.Start(); - /// 根据回测配方加载手部模型,供视频帧使用与运行流程一致的检测实现。 + /// 按配方加载回测所需模型,与在线检测共用物品模型配置。 public void LoadModels() { - // 视频回测与实时运行按相同的取图需求加载手部模型。 - 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 目录"); + // 加载与逐帧推理、销毁互斥,停止回测后不能再创建新会话。 + 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) }; - if (_hands.IsReady) result.Hands = _hands.Detect(image); - FrameObserved?.Invoke(result, seconds); - ProcessResult(result, image); - return result; + // 与 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; + } } - /// 使用与正式运行相同的原帧裁剪、手部门控和 AI 完成判定。 + /// 使用与正式运行相同的原帧裁剪、触发门控和 AI 完成判定。 /// 将已完成推理的帧及对应图像交给 SOP 引擎,用同一幅原图完成取证。 public void ProcessResult(FrameResult result, Mat image) { @@ -144,6 +158,6 @@ public sealed class SopVideoFlowTest : IDisposable /// 停止回测状态机并释放本回测实例的模型资源。 public void Dispose() { - lock (_gate) { _disposed = true; _engine.Stop(); _hands.Dispose(); } + lock (_gate) { _disposed = true; _engine.Stop(); _hands.Dispose(); _objects.Dispose(); } } } diff --git a/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs b/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs index 94128dc..e3c1ad2 100644 --- a/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs +++ b/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs @@ -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(); diff --git a/src/SopHelper.CrossPlatform.Engine/Inference/YoloDetector.cs b/src/SopHelper.CrossPlatform.Engine/Inference/YoloDetector.cs index f4fc77e..ebdd4f2 100644 --- a/src/SopHelper.CrossPlatform.Engine/Inference/YoloDetector.cs +++ b/src/SopHelper.CrossPlatform.Engine/Inference/YoloDetector.cs @@ -97,6 +97,15 @@ public class YoloDetector : IDisposable catch { Dispose(); throw; } } + /// 加载配方模型并设置预过滤阈值。缺少文件或模型格式无效时抛出,调用方负责提示。 + 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); + } + /// /// 阈值 /// @@ -270,6 +279,14 @@ public class YoloDetector : IDisposable return list; } + /// 把本帧推理结果附在原图对应的结果对象上;成功返回空列表也表示推理已执行。 + public void DetectInto(Mat bgr, FrameResult frame) + { + if (!IsReady) return; + frame.Detections = Detect(bgr); + frame.ObjectDetectionRan = true; + } + /// /// DFL(Distribution Focal Loss)解码:对 4 组 16 bin 做 softmax 取期望,得到边界框 /// diff --git a/src/SopHelper.CrossPlatform.Engine/Inference/YoloInferenceOptions.cs b/src/SopHelper.CrossPlatform.Engine/Inference/YoloInferenceOptions.cs new file mode 100644 index 0000000..90bc196 --- /dev/null +++ b/src/SopHelper.CrossPlatform.Engine/Inference/YoloInferenceOptions.cs @@ -0,0 +1,27 @@ +using SopHelper.Engine.Sop; + +namespace SopHelper.Engine.Inference; + +/// 相机与视频回测共用的 YOLO 模型配置,按配方中实际使用的规则保留所需置信度范围。 +public sealed record YoloInferenceOptions(string Path, IReadOnlyList Classes, int InputSize, float MinConfidence) +{ + /// 没有物品规则时返回空。保留缺失路径以便加载阶段给出明确错误。 + public static YoloInferenceOptions? FromRecipe(SopConfig config, Func resolvePath) + { + var conditions = config.Sop.Steps + .Select(step => step.Detection) + .OfType() + .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); + } +} diff --git a/src/SopHelper.CrossPlatform.Engine/Pipeline/DetectionPipeline.cs b/src/SopHelper.CrossPlatform.Engine/Pipeline/DetectionPipeline.cs index d3a3d87..4f9cd44 100644 --- a/src/SopHelper.CrossPlatform.Engine/Pipeline/DetectionPipeline.cs +++ b/src/SopHelper.CrossPlatform.Engine/Pipeline/DetectionPipeline.cs @@ -18,6 +18,9 @@ public class PipelineOptions /// MediaPipe 关键点模型 public string? LandmarkModelPath { get; set; } + /// 物品触发配方使用的模型。未配置时不建立 YOLO 会话。 + public YoloInferenceOptions? ObjectModel { get; set; } + /// 检测到的手最多几只 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; + /// 当前配方物品模型实际使用的推理设备。 + public string ObjectBackend => _objects.Backend; + /// 每帧查询当前步骤是否需要手部;未设置时保持独立管线的默认检测行为。 public Func? ShouldDetectHands { get; set; } + /// 在后台逐帧查询物品检测需求,默认关闭。即使模型已加载也必须经此门控。 + public Func? ShouldDetectObjects { get; set; } + /// 结果帧(在管线线程上触发) public event Action? 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(); 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(); } /// @@ -243,7 +271,7 @@ public class DetectionPipeline : IDisposable } } - /// 按当前步骤需求运行手部检测,更新推理耗时,并在未取消时发布本帧结果及原图。 + /// 按步骤需求执行手部和物品推理;两者复用同一原帧,未取消时发布对应结果。 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(); } } diff --git a/tests/Pipeline.Smoke/Program.cs b/tests/Pipeline.Smoke/Program.cs index 9f77287..5391d2f 100644 --- a/tests/Pipeline.Smoke/Program.cs +++ b/tests/Pipeline.Smoke/Program.cs @@ -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(); + 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;