From 0596727b74304e5d570df5fc2bc8d885b417cc60 Mon Sep 17 00:00:00 2001
From: tfarcraw <123211521@163.com>
Date: Tue, 10 Nov 2026 19:00:26 +0800
Subject: [PATCH] =?UTF-8?q?=E4=BB=85=E5=9C=A8=E5=BD=93=E5=89=8D=E6=AD=A5?=
=?UTF-8?q?=E9=AA=A4=E9=9C=80=E8=A6=81=E6=97=B6=E6=89=A7=E8=A1=8C=E6=89=8B?=
=?UTF-8?q?=E9=83=A8=E6=A3=80=E6=B5=8B?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.../VVMs/SopPage/SopPageViewModel.cs | 8 ++--
.../Pipeline/DetectionPipeline.cs | 5 +-
.../Sop/SopConfig.cs | 4 ++
.../Sop/SopEngine.cs | 4 ++
tests/Pipeline.Smoke/Program.cs | 48 +++++++++++++++++++
5 files changed, 65 insertions(+), 4 deletions(-)
diff --git a/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs b/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs
index ab50270..73f1e88 100644
--- a/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs
+++ b/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs
@@ -91,6 +91,7 @@ public class SopPageViewModel : ViewModelBase
_camera = camera;
_pipeline = pipeline;
_engine = engine;
+ _pipeline.ShouldDetectHands = () => _engine.RequiresHandDetection;
_dialogs = dialogs;
_dispatcher = Dispatcher.CurrentDispatcher;
@@ -736,6 +737,7 @@ public class SopPageViewModel : ViewModelBase
LoadTrainedRecipeModel(config);
_engine.Load(config);
+ var needsHands = config.Sop.Steps.Any(step => ConditionMethod.RequiresHandDetection(step.Detection?.Method));
// 仅使用本配方训练发布的 ONNX。
var options = new PipelineOptions
{
@@ -743,8 +745,8 @@ public class SopPageViewModel : ViewModelBase
YoloClasses = config.Sop.Model?.Classes ?? [],
YoloInputSize = config.Sop.Model?.InputSize ?? 640,
// 文件名必须和 models/ 下实际一致,否则 ResolveModel 返回 null、手部链路静默不跑
- PalmModelPath = ResolveModel("models/palm_detection_full_Nx3x192x192_post.onnx"),
- LandmarkModelPath = ResolveModel("models/hand_landmark_sparse_Nx3x224x224.onnx"),
+ PalmModelPath = needsHands ? ResolveModel("models/palm_detection_full_Nx3x192x192_post.onnx") : null,
+ LandmarkModelPath = needsHands ? ResolveModel("models/hand_landmark_sparse_Nx3x224x224.onnx") : null,
FrameStride = Math.Max(1, config.Sop.Settings.FrameStride),
RequireGpu = OperatingSystem.IsLinux(),
};
@@ -773,7 +775,7 @@ public class SopPageViewModel : ViewModelBase
foreach (var warning in _pipeline.Warnings)
Log("warn", warning);
- if (options.PalmModelPath is null || options.LandmarkModelPath is null)
+ if (needsHands && (options.PalmModelPath is null || options.LandmarkModelPath is null))
Log("warn", "手部模型缺失,手部检测及画面标记不可用,请检查 models 目录中的 palm / landmark ONNX 文件");
}
diff --git a/src/SopHelper.CrossPlatform.Engine/Pipeline/DetectionPipeline.cs b/src/SopHelper.CrossPlatform.Engine/Pipeline/DetectionPipeline.cs
index 96ac503..76e7fec 100644
--- a/src/SopHelper.CrossPlatform.Engine/Pipeline/DetectionPipeline.cs
+++ b/src/SopHelper.CrossPlatform.Engine/Pipeline/DetectionPipeline.cs
@@ -72,6 +72,9 @@ public class DetectionPipeline : IDisposable
public string HandBackend => _hand.Backend;
public string YoloBackend => _yolo.Backend;
+ /// 每帧查询当前步骤是否需要手部;未设置时保持独立管线的默认检测行为。
+ public Func? ShouldDetectHands { get; set; }
+
/// 结果帧(在管线线程上触发)
public event Action? ResultArrived;
@@ -254,7 +257,7 @@ public class DetectionPipeline : IDisposable
try { result.Detections = _yolo.Detect(frame.Bgr); }
catch (Exception ex) { ReportInferenceWarning("YOLO 推理异常:" + ex.Message); }
}
- if (_hand.IsReady)
+ if (_hand.IsReady && (ShouldDetectHands?.Invoke() ?? true))
{
try { result.Hands = _hand.Detect(frame.Bgr); }
catch (Exception ex) { ReportInferenceWarning("手部推理异常:" + ex.Message); }
diff --git a/src/SopHelper.CrossPlatform.Engine/Sop/SopConfig.cs b/src/SopHelper.CrossPlatform.Engine/Sop/SopConfig.cs
index 6cf7cea..753e77f 100644
--- a/src/SopHelper.CrossPlatform.Engine/Sop/SopConfig.cs
+++ b/src/SopHelper.CrossPlatform.Engine/Sop/SopConfig.cs
@@ -201,6 +201,10 @@ public class StepCondition
///
public static class ConditionMethod
{
+ /// 该判定方法是否需要手部推理。
+ public static bool RequiresHandDetection(string? method) => method?.ToLowerInvariant() is
+ HandInRegion or HandMove or HandNearObject;
+
/// 目标出现在画面(1 次)
public const string ObjectPresent = "object_present";
diff --git a/src/SopHelper.CrossPlatform.Engine/Sop/SopEngine.cs b/src/SopHelper.CrossPlatform.Engine/Sop/SopEngine.cs
index 2cb06a2..a449eb7 100644
--- a/src/SopHelper.CrossPlatform.Engine/Sop/SopEngine.cs
+++ b/src/SopHelper.CrossPlatform.Engine/Sop/SopEngine.cs
@@ -57,6 +57,10 @@ public class SopEngine
/// 当前步骤(未完成的那一步)
public StepDef? CurrentStep => State is EngineState.Idle or EngineState.Completed ? null : StepAt(_index);
+ /// 仅运行中的当前步骤需要手部条件时启用手部推理。
+ public bool RequiresHandDetection => State == EngineState.Running
+ && ConditionMethod.RequiresHandDetection(CurrentStep?.Detection?.Method);
+
/// 配方(UI 显示步骤卡用)
public SopConfig Config => _config;
diff --git a/tests/Pipeline.Smoke/Program.cs b/tests/Pipeline.Smoke/Program.cs
index 106e858..888b284 100644
--- a/tests/Pipeline.Smoke/Program.cs
+++ b/tests/Pipeline.Smoke/Program.cs
@@ -2,6 +2,39 @@ using System.Collections.Concurrent;
using OpenCvSharp;
using SopHelper.Engine.Camera;
using SopHelper.Engine.Pipeline;
+using SopHelper.Engine.Sop;
+using SopHelper.Engine.Common;
+
+// The first step must not enable hands merely because a later step uses them.
+var engine = new SopEngine();
+var config = new SopConfig();
+config.Sop.Settings.AutoResetOnComplete = false;
+config.Sop.Regions["work"] = new RegionDef { X1=0, Y1=0, X2=100, Y2=100 };
+config.Sop.Steps = [
+ new StepDef { Id=1, Detection=new StepCondition { Method=ConditionMethod.ObjectPresent, TargetObject="part", StableFrames=1 } },
+ new StepDef { Id=2, Detection=new StepCondition { Method=ConditionMethod.HandInRegion, Region="work", StableFrames=1 } },
+ new StepDef { Id=3, Detection=new StepCondition { Method=ConditionMethod.ObjectPresent, TargetObject="part", StableFrames=1 } }
+];
+engine.Load(config);
+if(engine.RequiresHandDetection)throw new Exception("Idle engine enabled hands");
+engine.Start();
+if(engine.RequiresHandDetection)throw new Exception("Future hand step enabled hands early");
+var partFrame = new FrameResult { Detections=[new Detection { Label="part", Confidence=1 }] };
+engine.ProcessFrame(partFrame);
+if(!engine.RequiresHandDetection)throw new Exception("Entering hand step did not enable hands");
+engine.TogglePause();
+if(engine.RequiresHandDetection)throw new Exception("Paused step enabled hands");
+engine.TogglePause();
+if(!engine.RequiresHandDetection)throw new Exception("Resuming hand step did not enable hands");
+engine.ProcessFrame(new FrameResult { Hands=[new Hand { Rect=new DetRect(10,10,20,20) }] });
+if(engine.RequiresHandDetection)throw new Exception("Leaving hand step did not disable hands");
+engine.ProcessFrame(partFrame);
+if(engine.State!=EngineState.Completed||engine.RequiresHandDetection)throw new Exception("Completed engine enabled hands");
+engine.Reset();
+if(engine.RequiresHandDetection)throw new Exception("Reset kept previous hand requirement");
+foreach(var method in new[]{ConditionMethod.HandInRegion,ConditionMethod.HandMove,ConditionMethod.HandNearObject})
+ if(!ConditionMethod.RequiresHandDetection(method.ToUpperInvariant()))throw new Exception("Hand method not recognized: "+method);
+Console.WriteLine("PASS: Hand inference follows only the current running step across transitions, pause, completion and reset");
using var camera = new TestCamera();
using var pipeline = new DetectionPipeline(camera);
@@ -70,6 +103,21 @@ if (args.Length >= 3)
var frame = await completion.Task.WaitAsync(TimeSpan.FromSeconds(10));pipeline.Stop();
if (frame.Hands.Count == 0 || pipeline.Warnings.Count != 0) throw new Exception("Combined YOLO/hand inference failed");
Console.WriteLine("PASS: Real YOLO and hand models process the same frame despite an outdated configured input size");
+ var expectedDetections = frame.Detections.Select(d => (d.Label,d.Rect,d.Confidence)).ToArray();
+ var detectHands = false;
+ pipeline.ShouldDetectHands = () => detectHands;
+ foreach (var enabled in new[]{false,true,false})
+ {
+ detectHands = enabled;
+ completion = new(TaskCreationOptions.RunContinuationsAsynchronously);
+ await pipeline.StartAsync();camera.Emit(200,image);
+ frame = await completion.Task.WaitAsync(TimeSpan.FromSeconds(10));pipeline.Stop();
+ if((frame.Hands.Count>0)!=enabled)throw new Exception("Hand inference did not follow the current requirement");
+ if(!frame.Detections.Select(d => (d.Label,d.Rect,d.Confidence)).SequenceEqual(expectedDetections))
+ throw new Exception("Disabling hands affected object detection");
+ }
+ pipeline.ShouldDetectHands = null;
+ Console.WriteLine("PASS: Real hand detection stops and resumes without stale hands while YOLO continues");
// Reproduce the original YOLO dimension exception after loading, to verify fault isolation.
var flags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic;
var yolo = typeof(DetectionPipeline).GetField("_yolo", flags)!.GetValue(pipeline)!;