diff --git a/HAND_AI.md b/HAND_AI.md
index 4205205..2560bc6 100644
--- a/HAND_AI.md
+++ b/HAND_AI.md
@@ -107,6 +107,8 @@ SystemOne 后端默认连接本机 Nano,兼容已有的 `SOPHELPER_VISION_PROV
跟随手部默认四周扩展 160 像素、最小宽高 320 像素、位置保留 3000ms,均可在编辑器设置。裁剪范围贴近画面边缘时限制在有效画面内。保留位置过期、从未观察到相关手、暂停/复位/切换步骤或相机尺寸改变后,等待新的有效手部位置,不改发整图。它是手部附近裁剪,不是物品分割;物品超出范围时应增大扩展距离,或选择固定区域/整帧。
+「测试此步」可以用关键帧中检测到的送检手裁剪图片。要验证手离开后按历史位置送检,请用「测试流程」播放包含手部进入和离开的片段。
+
```yaml
ai_confirmation:
image_mode: hand
diff --git a/src/SopHelper.Avalonia/VVMs/RecipeEditor/OptimizeStepsViewModel.cs b/src/SopHelper.Avalonia/VVMs/RecipeEditor/OptimizeStepsViewModel.cs
index 6d894b0..c75a064 100644
--- a/src/SopHelper.Avalonia/VVMs/RecipeEditor/OptimizeStepsViewModel.cs
+++ b/src/SopHelper.Avalonia/VVMs/RecipeEditor/OptimizeStepsViewModel.cs
@@ -95,9 +95,10 @@ public partial class RecipeEditorViewModel
AgentStatus = $"{label}:正在查看关键帧并生成9条同义完成条件…";
var definition = config.Sop.Steps.First(s => s.Id == step.Id);
var prepared = await Task.Run(() => PrepareStepDecisionImage(definition, config.Sop.Regions, videoPaths, token), token);
- var jpeg = prepared.Jpeg;
- AppendStepDecisionLog($"{label} · 优化实际送检:{prepared.Scope}");
- report = new StepOptimizationReport(label, jpeg, step.KeyFrameSeconds, prepared.Scope);
+ // 沿用优化流程的逐步跳过规则,取图失败时保留该步原条件。
+ var jpeg = prepared.Jpeg ?? throw new ArgumentException(prepared.Detail);
+ AppendStepDecisionLog($"{label} · 优化实际送检:{prepared.Detail}");
+ report = new StepOptimizationReport(label, jpeg, step.KeyFrameSeconds, prepared.Detail);
OptimizationReports.Add(report);
string? best = null;
VisionDecisionResult? bestResult = null;
diff --git a/src/SopHelper.Avalonia/VVMs/RecipeEditor/StepTestDecisionViewModel.cs b/src/SopHelper.Avalonia/VVMs/RecipeEditor/StepTestDecisionViewModel.cs
index 531d7db..5f639f1 100644
--- a/src/SopHelper.Avalonia/VVMs/RecipeEditor/StepTestDecisionViewModel.cs
+++ b/src/SopHelper.Avalonia/VVMs/RecipeEditor/StepTestDecisionViewModel.cs
@@ -2,6 +2,8 @@
using OpenCvSharp;
using Prism.Commands;
+using SopHelper.Engine.Common;
+using SopHelper.Engine.Inference;
using SopHelper.Engine.Sop;
using SopHelper.Engine.SopAgent;
@@ -13,6 +15,8 @@ public partial class RecipeEditorViewModel
public DelegateCommand TestStepDecisionCommand { get; }
private CancellationTokenSource? _stepTestCancellation;
private Task? _stepTestTask;
+ /// 对关键帧执行手部推理,返回空值表示模型未就绪;测试可提供确定的检测结果。
+ internal Func?> DetectStepTestHands { get; set; } = DetectKeyFrameHands;
private bool _isTestingStep;
public bool IsTestingStep
{
@@ -70,6 +74,7 @@ public partial class RecipeEditorViewModel
var criteria = step.CompletionCriteria;
var config = Recipe.ToConfig();
var definition = config.Sop.Steps.First(s => s.Id == id);
+ var detectHands = DetectStepTestHands;
var videoPaths = KeyFrameVideoPaths();
var seconds = step.KeyFrameSeconds;
var threshold = step.AiMinConfidence;
@@ -81,10 +86,17 @@ public partial class RecipeEditorViewModel
StepTestStatus = $"{label}:正在按送检规则处理关键帧…";
try
{
- var prepared = await Task.Run(() => PrepareStepDecisionImage(definition, config.Sop.Regions, videoPaths, cancellation.Token), cancellation.Token);
- var jpeg = prepared.Jpeg;
- AppendStepDecisionLog($"{label} · 实际送检:{prepared.Scope}");
+ var prepared = await Task.Run(() => PrepareStepDecisionImage(definition, config.Sop.Regions, videoPaths, cancellation.Token, detectHands), cancellation.Token);
cancellation.Token.ThrowIfCancellationRequested();
+ if (prepared.Jpeg is not { } jpeg)
+ {
+ StepTestStatus = $"{label}:{prepared.Detail}";
+ return;
+ }
+ AppendStepDecisionLog($"{label} · 实际送检:{prepared.Detail}");
+ // 单步跟手测试还需加载模型并推理,从准备完毕后计入 djev 请求期限。
+ if (definition.AiConfirmation is { } options && VisionImageMode.Resolve(options) == VisionImageMode.Hand)
+ started = System.Diagnostics.Stopwatch.GetTimestamp();
var request = new VisionDecisionRequest(recipe, id, name, description, criteria, 0, DateTime.Now, jpeg,
SourceSeconds: seconds, StartedTimestamp: started, TimeoutMs: timeoutMs);
var result = await RunStepDecisionAsync(label, request, cancellation.Token);
@@ -113,16 +125,18 @@ public partial class RecipeEditorViewModel
/// 固定本次旧关键帧核对可用的来源,后台取图不访问编辑器状态。
private string?[] KeyFrameVideoPaths() => [AgentVideoPath, SopRecording?.StandardVideoPath];
- /// 共用运行时送检规则,将原视频坐标转换为关键帧像素后再裁剪。
- private static (byte[] Jpeg, string Scope) PrepareStepDecisionImage(StepDef step, IReadOnlyDictionary regions,
- string?[] videoPaths, CancellationToken token)
+ /// 将原视频坐标转换为关键帧像素后裁剪。无法从单帧定位手时,返回提示并停止送检。
+ private static (byte[]? Jpeg, string Detail) PrepareStepDecisionImage(StepDef step, IReadOnlyDictionary regions,
+ string?[] videoPaths, CancellationToken token, Func?>? detectHands = null)
{
var options = step.AiConfirmation ?? new();
- var region = VisionDecisionImage.ResolveRegion(options, regions);
+ // 仅显式提供单帧手部检测的入口可以试裁;批量优化仍要求可还原的送检范围。
+ var handDetector = VisionImageMode.Resolve(options) == VisionImageMode.Hand ? detectHands : null;
+ var region = handDetector is null ? VisionDecisionImage.ResolveRegion(options, regions) : null;
var bytes = Convert.FromBase64String(step.KeyFrameBase64);
using var image = Cv2.ImDecode(bytes, ImreadModes.Color);
if (image.Empty()) throw new FormatException("关键帧解码失败");
- if (region is null) return (VisionDecisionImage.Encode(image, null), "整帧");
+ if (handDetector is null && region is null) return (VisionDecisionImage.Encode(image, null), "整帧");
var source = step.KeyFrameSourceSize;
if (source is null && step.KeyFrameSeconds is { } seconds && bytes.Length >= 2 && bytes[0] == 0xff && bytes[1] == 0xd8
@@ -136,7 +150,30 @@ public partial class RecipeEditorViewModel
var height = source?.Height ?? image.Height;
if (width < image.Width || height < image.Height)
throw new ArgumentException("关键帧记录的原视频尺寸无效,请重新获取关键帧。");
- var scope = $"区域 {options.ImageRegion} [{region.X1},{region.Y1},{region.X2},{region.Y2}]";
+ if (handDetector is not null)
+ {
+ var hands = handDetector(image, token);
+ token.ThrowIfCancellationRequested();
+ if (hands is null) return (null, "手部模型未就绪,请检查 models 目录。未发送图片。");
+
+ // 用原视频像素判断工位接触并应用扩边,再把裁剪边界换算回关键帧像素。
+ var scaleX = (float)width / image.Width;
+ var scaleY = (float)height / image.Height;
+ var observation = new FrameResult { Size = (width, height), Hands = hands.Select(hand =>
+ {
+ var box = hand.ContactRect;
+ return new Hand { HandType = hand.HandType, Rect = new(box.X * scaleX, box.Y * scaleY, box.W * scaleX, box.H * scaleY) };
+ }).ToList() };
+ var trackingRegions = regions.ToDictionary(pair => pair.Key, pair =>
+ new DetRect(pair.Value.X1, pair.Value.Y1, pair.Value.X2 - pair.Value.X1, pair.Value.Y2 - pair.Value.Y1),
+ StringComparer.OrdinalIgnoreCase);
+ var tracker = new HandImageRegionTracker();
+ tracker.Observe(step, observation, trackingRegions);
+ region = tracker.Resolve(options, observation);
+ }
+ if (region is null)
+ return (null, "关键帧内没有符合送检手别和工位范围的手。请选用手部可见的关键帧,或用「测试流程」检查手离开后的画面。");
+ var scope = $"{(handDetector is null ? $"区域 {options.ImageRegion}" : "手部附近")} [{region.X1},{region.Y1},{region.X2},{region.Y2}]";
if (region.X1 < 0 || region.Y1 < 0 || region.X2 <= region.X1 || region.Y2 <= region.Y1 || region.X2 > width || region.Y2 > height)
throw new ArgumentException($"{scope} 无效或超出关键帧原始画面 {width}×{height},请核对送检区域或重新获取关键帧。");
if (width != image.Width || height != image.Height)
@@ -154,6 +191,17 @@ public partial class RecipeEditorViewModel
return (VisionDecisionImage.Encode(image, region), scope);
}
+ /// 单步测试使用本次任务独有的检测器,避免混用在线运行的手别追踪状态。
+ private static IReadOnlyList? DetectKeyFrameHands(Mat image, CancellationToken token)
+ {
+ token.ThrowIfCancellationRequested();
+ using var detector = new MediaPipeHandDetector();
+ detector.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());
+ token.ThrowIfCancellationRequested();
+ return detector.IsReady ? detector.Detect(image) : null;
+ }
+
/// 旧配方缺少尺寸时重抽同一时刻,只有 JPEG 内容匹配才采用候选视频的尺寸。
private static KeyFrameSourceSize? FindLegacyKeyFrameSource(byte[] jpeg, double seconds, string?[] videoPaths, CancellationToken token)
{
diff --git a/tests/VideoFlowTest.Smoke/StepTestDecisionChecks.cs b/tests/VideoFlowTest.Smoke/StepTestDecisionChecks.cs
index 444df61..9981cf7 100644
--- a/tests/VideoFlowTest.Smoke/StepTestDecisionChecks.cs
+++ b/tests/VideoFlowTest.Smoke/StepTestDecisionChecks.cs
@@ -1,5 +1,6 @@
using Avalonia.Threading;
using OpenCvSharp;
+using SopHelper.Engine.Common;
using SopHelper.Engine.Sop;
using SopHelper.VVMs.RecipeEditor;
@@ -87,8 +88,29 @@ internal static class StepTestDecisionChecks
model.TestStepDecisionCommand.Execute(); Until(() => !model.IsTestingStep);
Check(probe.Calls == regionCalls && model.StepTestStatus.Contains("超出"), "越界送检区域不回退整帧");
step.AiImageMode = VisionImageMode.Hand;
+ step.AiImageHand = "left";
+ step.AiHandMinSize = 32;
+ step.AiHandPadding = 0;
+ step.Detection!.Method = ConditionMethod.TimeElapsed;
+ step.KeyFrameSourceSize = new() { Width = 128, Height = 96 };
+ // 先提供错误手别,再提供缩图上的左手位置,验证手别过滤和原视频坐标换算。
+ var hand = new Hand { HandType = HandType.Right, Rect = new(20, 16, 12, 8) };
+ model.DetectStepTestHands = (_, _) => [hand];
model.TestStepDecisionCommand.Execute(); Until(() => !model.IsTestingStep);
- Check(probe.Calls == regionCalls && model.StepTestStatus.Contains("手部轨迹"), "静态跟手测试无真实轨迹时禁止猜测或发送整图");
+ Check(probe.Calls == regionCalls && model.StepTestStatus.Contains("测试流程"), "无匹配送检手时提示使用测试流程且不发送");
+ model.DetectStepTestHands = (_, _) => null;
+ model.TestStepDecisionCommand.Execute(); Until(() => !model.IsTestingStep);
+ Check(probe.Calls == regionCalls && model.StepTestStatus.Contains("手部模型未就绪"), "手部模型不可用时给出专门提示");
+ hand.HandType = HandType.Left;
+ model.DetectStepTestHands = (_, _) => [hand];
+ probe = new Probe(); model.StepTestDecisionClient = probe;
+ model.TestStepDecisionCommand.Execute(); Until(() => probe.Request is not null);
+ using (var cropped = Cv2.ImDecode(probe.Request!.Jpeg, ImreadModes.Color))
+ Check(cropped.Width == 16 && cropped.Height == 16 && Cv2.Mean(cropped).Val1 > 220,
+ "按关键帧实际手部裁剪,并按原视频像素应用最小宽高");
+ Check(model.StepDecisionLog.Contains("手部附近 [36,24,68,56] · 关键帧裁剪 [18,12,34,28]"),
+ "跟手测试日志记录实际送检范围");
+ probe.Result.SetResult(new(true, .99, "跟手测试")); Until(() => !model.IsTestingStep);
step.AiImageMode = VisionImageMode.FullFrame;
step.KeyFrameBase64 = "broken";