允许独立设置跟手送检手别

This commit is contained in:
wanglei 2026-12-05 14:03:10 +08:00
parent 1922c664cb
commit ccba2b9f04
12 changed files with 92 additions and 23 deletions

View File

@ -103,13 +103,14 @@ SystemOne 后端默认连接本机 Nano,兼容已有的 `SOPHELPER_VISION_PROV
- 整张画面(`full_frame`):发送当前判定帧。
- 固定区域(`fixed_region`):选择已画好的区域,只发送该区域;缺区域或越界会阻止发送,不会改发整图。
- 跟随手部(`hand`):使用当前步骤触发区域内、符合左右手设置的手部框,向四周扩展,并保证最小宽高;任何手模式下,区域内有双手时使用合并范围。双手模式只在左右手同时接触区域时更新合并范围。A→B 移动使用终点区域内的手。“手离开”使用离开前最后接触触发区域的位置,但裁剪的仍是触发时的新帧,不是旧照片。
- 跟随手部(`hand`):通过「送检手别」独立选择任何手、左手、右手或双手,旧配方未设置时默认任何手。手部触发按触发区域筛选手部框,A→B 移动使用终点区域;持续计时在整张画面中跟踪送检手。任何手模式合并范围内检出的手部框,双手模式须同帧匹配左右手才更新范围。“手离开”可使用最近一次有效位置裁剪当前判定帧。
跟随手部默认四周扩展 160 像素、最小宽高 320 像素、位置保留 3000ms,均可在编辑器设置。裁剪范围贴近画面边缘时限制在有效画面内。保留位置过期、从未观察到相关手、暂停/复位/切换步骤或相机尺寸改变后,等待新的有效手部位置,不改发整图。它是手部附近裁剪,不是物品分割;物品超出范围时应增大扩展距离,或选择固定区域/整帧。
```yaml
ai_confirmation:
image_mode: hand
image_hand: any
hand_padding: 160
hand_min_size: 320
hand_memory_ms: 3000

View File

@ -77,7 +77,8 @@ public sealed class SopVideoFlowTest : IDisposable
/// <summary>根据回测配方加载手部模型,供视频帧使用与运行流程一致的检测实现。</summary>
public void LoadModels()
{
if (!_engine.Config.Sop.Steps.Any(s => ConditionMethod.RequiresHandDetection(s.Detection?.Method))) return;
// 视频回测与实时运行按相同的取图需求加载手部模型。
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 目录");

View File

@ -418,6 +418,7 @@ public class RecipeNode : EditorNode
ObservationMaxMs = step.AiConfirmation.ObservationMaxMs, ObservationSampleMs = step.AiConfirmation.ObservationSampleMs,
ObservationMaxFrames = step.AiConfirmation.ObservationMaxFrames, ObservationRequestMaxFrames = step.AiConfirmation.ObservationRequestMaxFrames,
ImageRegion = step.AiConfirmation.ImageRegion,
ImageHand = step.AiConfirmation.ImageHand,
ImageMode = step.AiConfirmation.ImageMode, HandPadding = step.AiConfirmation.HandPadding,
HandMinSize = step.AiConfirmation.HandMinSize, HandMemoryMs = step.AiConfirmation.HandMemoryMs,
RetryDelayMs = step.AiConfirmation.RetryDelayMs, TimeoutSeconds = step.AiConfirmation.TimeoutSeconds,
@ -483,6 +484,7 @@ public class RecipeNode : EditorNode
ObservationMinMs = step.AiObservationMinMs, ObservationMaxMs = step.AiObservationMaxMs,
ObservationSampleMs = step.AiObservationSampleMs, ObservationMaxFrames = step.AiObservationMaxFrames, ObservationRequestMaxFrames = step.AiObservationRequestMaxFrames,
ImageRegion = step.AiImageRegion,
ImageHand = step.AiImageHand,
ImageMode = step.AiImageMode, HandPadding = step.AiHandPadding,
HandMinSize = step.AiHandMinSize, HandMemoryMs = step.AiHandMemoryMs,
RetryDelayMs = step.AiRetryDelayMs, TimeoutSeconds = step.AiTimeoutSeconds,
@ -701,6 +703,7 @@ public class StepNode : EditorNode
public int AiObservationRequestMaxFrames { get => _aiObservationRequestMaxFrames; set => SetProperty(ref _aiObservationRequestMaxFrames, value); }
public int AiObservationMaxFrames { get => _aiObservationMaxFrames; set => SetProperty(ref _aiObservationMaxFrames, value); }
private string _aiImageMode = VisionImageMode.FullFrame;
private string _aiImageHand = "any";
private int _aiHandPadding = 160, _aiHandMinSize = 320, _aiHandMemoryMs = 3000;
public IReadOnlyList<string> AiImageModes { get; } = [VisionImageMode.FullFrame, VisionImageMode.FixedRegion, VisionImageMode.Hand];
public string AiImageMode
@ -710,6 +713,8 @@ public class StepNode : EditorNode
}
public bool UsesFixedImageRegion => AiImageMode == VisionImageMode.FixedRegion;
public bool UsesHandImageRegion => AiImageMode == VisionImageMode.Hand;
/// <summary>跟手裁剪使用的手别,随 AI 取图参数保存,独立于触发条件。</summary>
public string AiImageHand { get => _aiImageHand; set => SetProperty(ref _aiImageHand, DetectionHands.Normalize(value)); }
public int AiHandPadding { get => _aiHandPadding; set => SetProperty(ref _aiHandPadding, value); }
public int AiHandMinSize { get => _aiHandMinSize; set => SetProperty(ref _aiHandMinSize, value); }
public int AiHandMemoryMs { get => _aiHandMemoryMs; set => SetProperty(ref _aiHandMemoryMs, value); }
@ -733,6 +738,7 @@ public class StepNode : EditorNode
AiObservationSampleMs = value.ObservationSampleMs; AiObservationMaxFrames = value.ObservationMaxFrames; AiObservationRequestMaxFrames = value.ObservationRequestMaxFrames;
AiImageRegion = value.ImageRegion;
AiImageMode = VisionImageMode.Resolve(value);
AiImageHand = value.ImageHand;
AiHandPadding = value.HandPadding; AiHandMinSize = value.HandMinSize; AiHandMemoryMs = value.HandMemoryMs;
AiRetryDelayMs = value.RetryDelayMs; AiTimeoutSeconds = value.TimeoutSeconds;
}

View File

@ -226,6 +226,15 @@
<ComboBox Grid.Column="1" x:Name="AiImageRegionPicker" ItemsSource="{Binding #RecipeEditorRoot.DataContext.Recipe.RegionNames}" SelectedItem="{Binding AiImageRegion, Mode=TwoWay, Converter={StaticResource SelectionConverter}}" />
</Grid>
<StackPanel IsVisible="{Binding UsesHandImageRegion}" Spacing="6">
<!-- 共用手别显示选项,绑定到独立的 AI 送检配置。 -->
<Grid ColumnDefinitions="76,*">
<TextBlock Text="送检手别" Classes="Field" VerticalAlignment="Center" />
<ComboBox Grid.Column="1" x:Name="AiImageHandPicker" ItemsSource="{Binding #RecipeEditorRoot.DataContext.Recipe.Hands}" SelectedItem="{Binding AiImageHand, Mode=TwoWay, Converter={StaticResource SelectionConverter}}">
<ComboBox.ItemTemplate>
<DataTemplate><TextBlock Text="{Binding Converter={x:Static ed:DetectionHandLabels.Converter}}" /></DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</Grid>
<Grid ColumnDefinitions="*,8,*">
<StackPanel Spacing="3">
<TextBlock Text="扩边 / px" Classes="Field" />

View File

@ -1065,7 +1065,8 @@ public class SopPageViewModel : ViewModelBase
// 提前读取统计,避免在切换管线之后才遇到存储错误。
_engine.GetStatistics(config.Sop.Name);
var needsHands = config.Sop.Steps.Any(step => ConditionMethod.RequiresHandDetection(step.Detection?.Method));
// 跟手送检可单独请求手部推理,计时配方也需要预载模型。
var needsHands = config.Sop.Steps.Any(step => step.NeedsHandDetection());
var options = new PipelineOptions
{
// 文件名必须和 models/ 下实际一致,否则 ResolveModel 返回 null、手部链路静默不跑

View File

@ -4,7 +4,7 @@ using SopHelper.Engine.Common;
namespace SopHelper.Engine.Sop;
/// <summary>只记当前步骤、当前图像尺寸下与触发规则相关的手,保存位置而非旧图片。</summary>
/// <summary>按送检手别记录当前步骤和图像尺寸下的手部位置,供后续裁剪判定帧。</summary>
public sealed class HandImageRegionTracker(TimeProvider? timeProvider = null)
{
private readonly TimeProvider _clock = timeProvider ?? TimeProvider.System;
@ -22,12 +22,19 @@ public sealed class HandImageRegionTracker(TimeProvider? timeProvider = null)
Reset(); _stepId = step.Id; _size = frame.Size;
}
if (step.AiConfirmation is not { } options || VisionImageMode.Resolve(options) != VisionImageMode.Hand) return;
var condition = step.Detection;
if (condition is null) return;
var mode = DetectionHands.Normalize(condition.Hand);
var target = condition.Method.ToLowerInvariant() == ConditionMethod.HandMove ? condition.ToRegion : condition.Region;
if (!regions.TryGetValue(target, out var region)) return;
var tolerance = Math.Max(0, condition.Tolerance);
var mode = DetectionHands.Normalize(options.ImageHand);
DetRect? region = null;
var tolerance = 0f;
if (step.Detection is { } condition && ConditionMethod.RequiresHandDetection(condition.Method))
{
// 手部触发仍用工位范围约束裁剪位置,保证手离开后能检查工位原处。
// 计时触发没有工位约束,在整个画面内跟踪配置的送检手。
var target = condition.Method.Equals(ConditionMethod.HandMove, StringComparison.OrdinalIgnoreCase)
? condition.ToRegion : condition.Region;
if (!regions.TryGetValue(target, out var triggerRegion)) return;
region = triggerRegion;
tolerance = Math.Max(0, condition.Tolerance);
}
// 双手模式只更新完整的双手范围,避免先离开的一只手被后续单手帧覆盖。
var candidates = DetectionHands.Select(frame.Hands, mode).Where(hand =>
@ -36,7 +43,7 @@ public sealed class HandImageRegionTracker(TimeProvider? timeProvider = null)
return float.IsFinite(rect.X) && float.IsFinite(rect.Y)
&& float.IsFinite(rect.Right) && float.IsFinite(rect.Bottom)
&& rect.W > 0 && rect.H > 0 && rect.Intersects(new(0, 0, frame.Size.W, frame.Size.H))
&& rect.Intersects(region, tolerance);
&& (region is null || rect.Intersects(region.Value, tolerance));
}).ToList();
if (!DetectionHands.HasRequiredHands(candidates, mode)) return;
var boxes = candidates.Select(hand => hand.ContactRect);

View File

@ -160,6 +160,10 @@ public class StepDef
[YamlMember(DefaultValuesHandling = DefaultValuesHandling.OmitNull)]
public AiConfirmation? AiConfirmation { get; set; } = new();
/// <summary>手部触发和跟手送检都需要手部推理,计时步骤也可仅为取图开启推理。</summary>
public bool NeedsHandDetection() => ConditionMethod.RequiresHandDetection(Detection?.Method)
|| AiConfirmation is { } options && VisionImageMode.Resolve(options) == VisionImageMode.Hand;
/// <summary>本步期间必须常在的物体,被拿走即违规</summary>
public List<string> MustKeep { get; set; } = [];

View File

@ -126,8 +126,7 @@ public partial class SopEngine
/// <summary>当前判定步骤或连续取图步骤需要手部条件时启用推理。</summary>
public bool RequiresHandDetection => State == EngineState.Running
&& (ConditionMethod.RequiresHandDetection(CurrentStep?.Detection?.Method)
|| ConditionMethod.RequiresHandDetection(StepAt(_nextCaptureIndex)?.Detection?.Method));
&& (CurrentStep?.NeedsHandDetection() == true || StepAt(_nextCaptureIndex)?.NeedsHandDetection() == true);
/// <summary>配方(UI 显示步骤卡用)</summary>
public SopConfig Config => _config;

View File

@ -21,6 +21,8 @@ public sealed class AiConfirmation
public string ImageMode { get; set; } = "";
/// <summary>固定送检区域名;仅未指定 ImageMode 的旧配方按空值推断整帧。</summary>
public string ImageRegion { get; set; } = "";
/// <summary>跟随手部取图使用的手别。旧配方缺少此字段时默认任何手,与触发手别独立。</summary>
public string ImageHand { get; set; } = "any";
public int HandPadding { get; set; } = 160;
public int HandMinSize { get; set; } = 320;
public int HandMemoryMs { get; set; } = 3000;

View File

@ -1321,8 +1321,19 @@ internal static class Smoke
modePicker.SelectedItem="hand";await Task.Delay(20);
var padding=editor.FindControl<NumericUpDown>("AiHandPaddingInput")!;
Check(padding.IsEffectivelyVisible,"Hand-follow mode exposes crop range controls");
// 送检手别在计时触发时也能编辑,并通过配方保存与加载往返。
var handPicker=editor.FindControl<ComboBox>("AiImageHandPicker")!;
var trigger=editor.FindControl<ComboBox>("StepTriggerMethodPicker")!;
var originalTrigger=trigger.SelectedItem;
var triggerHand=editorVm.Recipe.ToConfig().Sop.Steps[0].Detection?.Hand;
trigger.SelectedItem=ConditionMethod.TimeElapsed;await Task.Delay(20);
Check(handPicker.IsEffectivelyVisible&&Equals(handPicker.SelectedItem,"any"),"计时跟手送检应显示独立手别并默认任何手");
handPicker.SelectedItem="left";
trigger.SelectedItem=originalTrigger;
padding.Value=200;await Task.Delay(20);
Check(editorVm.Recipe.ToConfig().Sop.Steps[0].AiConfirmation is {ImageMode:"hand",HandPadding:200,HandMinSize:320,HandMemoryMs:3000},"Editor persists dynamic hand crop settings");
var handConfig=SopConfigLoader.Parse(SopConfigLoader.ToYaml(editorVm.Recipe.ToConfig())).Sop.Steps[0];
Check(handConfig.AiConfirmation is {ImageMode:"hand",ImageHand:"left",HandPadding:200,HandMinSize:320,HandMemoryMs:3000}
&&handConfig.Detection?.Hand==triggerHand,"送检手别应单独保存,切换触发方式后仍保留");
var description=editor.FindControl<TextBox>("StepDescriptionBox")!;
Check(description.Text=="红色零件安装到位","Step description is the only editable completion condition");
description.Text="把红色零件放到盒子里";await Task.Delay(20);

View File

@ -7,7 +7,7 @@ internal static class DynamicRegionChecks
public static async Task RunAsync()
{
static void Check(bool value, string message) { if (!value) throw new Exception(message); }
var options = new AiConfirmation { ImageMode = VisionImageMode.Hand, HandPadding = 20, HandMinSize = 100, HandMemoryMs = 3000 };
var options = new AiConfirmation { ImageMode = VisionImageMode.Hand, ImageHand = "right", HandPadding = 20, HandMinSize = 100, HandMemoryMs = 3000 };
var step = new StepDef { Id = 1, Description = "零件已放好", AiConfirmation = options,
Detection = new() { Method = ConditionMethod.HandLeaveRegion, Region = "work", Hand = "right", StableFrames = 2, Tolerance = 1 } };
var regions = new Dictionary<string, DetRect> { ["work"] = new(0, 0, 300, 300) };
@ -41,30 +41,38 @@ internal static class DynamicRegionChecks
&& VisionImageMode.Resolve(new()) == VisionImageMode.FullFrame, "旧配方的固定区域和整图语义必须兼容");
Check(!VisionImageMode.IsValid(new() { ImageMode = "invalid" })
&& !VisionImageMode.IsValid(new() { ImageMode = "hand", HandPadding = -1 }), "未知取图方式或无效范围不能退回整图");
step.Detection!.Hand = "any";
options.ImageHand = "any";
var both = Frame(Right(50,50), new Hand { HandType=HandType.Left, Rect=new(200,200,20,20) });
tracker.Observe(step, both, regions);
Check(tracker.Resolve(options, both) is { X1: 30, Y1: 30, X2: 240, Y2: 240 }, "任意手模式应覆盖触发区域内的双手");
step.Detection.Hand = "right";
options.ImageHand = "left";
step.Id = 1;
var config = new SopConfig(); config.Sop.Name = "跟手送检"; config.Sop.Settings.AutoResetOnComplete = false;
config.Sop.Regions["work"] = new() { X1 = 0, Y1 = 0, X2 = 300, Y2 = 300 };
config.Sop.Steps.Add(step);
var parsed = SopConfigLoader.Parse(SopConfigLoader.ToYaml(config));
Check(parsed.Warnings.Count == 0 && parsed.Sop.Steps[0].AiConfirmation is { ImageMode: "hand", HandPadding: 20, HandMinSize: 100, HandMemoryMs: 3000 }, "跟手配置应正确往返保存");
Check(parsed.Warnings.Count == 0 && parsed.Sop.Steps[0].AiConfirmation is { ImageMode: "hand", ImageHand: "left", HandPadding: 20, HandMinSize: 100, HandMemoryMs: 3000 }, "跟手配置应正确往返保存");
var legacy = SopConfigLoader.Parse(SopConfigLoader.ToYaml(config).Replace("image_hand: left", ""));
Check(legacy.Sop.Steps[0].AiConfirmation?.ImageHand == "any" && legacy.Sop.Steps[0].Detection?.Hand == "right",
"旧配方没有送检手别时默认任何手,并保留自己的触发手别");
var fake = new FakeDecision(); var engine = new SopEngine { VisionDecisionClient = fake };
engine.Load(config); engine.Start();
using var currentImage = new Mat(480, 640, MatType.CV_8UC3, new Scalar(0, 255, 0));
int captures = 0;
byte[] Capture(RegionDef? region)
{
Check(region is { X1: 60, Y1: 60, X2: 160, Y2: 160 }, "引擎应使用离开前的手部位置");
Check(region is { X1: 160, Y1: 160, X2: 260, Y2: 260 }, "右手触发后应按左手最后的位置裁剪");
captures++; return VisionDecisionImage.Encode(currentImage, region);
}
// 跟手取图须先满足两帧连续进入,再观察离开。
engine.ProcessFrame(first, captureDecisionImage: Capture);
engine.ProcessFrame(first, captureDecisionImage: Capture);
// 左手单独出现不触发。右手进入再离开时,用左手的位置取图。
engine.ProcessFrame(otherHand, captureDecisionImage: Capture);
engine.ProcessFrame(otherHand, captureDecisionImage: Capture);
engine.ProcessFrame(empty, captureDecisionImage: Capture);
engine.ProcessFrame(empty, captureDecisionImage: Capture);
Check(captures == 0, "送检手不能触发右手的离开条件");
engine.ProcessFrame(both, captureDecisionImage: Capture);
engine.ProcessFrame(both, captureDecisionImage: Capture);
Check(captures == 0, "手仍在区域内时不能提前拍照");
engine.ProcessFrame(empty, captureDecisionImage: Capture); engine.ProcessFrame(empty, captureDecisionImage: Capture);
await fake.Called.Task.WaitAsync(TimeSpan.FromSeconds(5));
@ -75,7 +83,25 @@ internal static class DynamicRegionChecks
engine.ProcessFrame(empty, captureDecisionImage: Capture);
Check(captures == 1, "暂停恢复不能沿用旧手部位置再次拍照");
engine.Stop();
Console.WriteLine("PASS: 跟手动态裁剪、当前帧送检、离开前定位、左右手过滤、过期/跨步骤/暂停/尺寸失效、旧配方兼容");
// 持续计时单独请求手部推理,且忽略从旧触发配置留下的区域和手别。
step.Detection!.Method = ConditionMethod.TimeElapsed;
step.Detection.DurationMs = 1;
var timedFake = new FakeDecision();
var timedEngine = new SopEngine { VisionDecisionClient = timedFake };
timedEngine.Load(config);
timedEngine.Start();
Check(timedEngine.RequiresHandDetection, "持续计时的跟手取图也应开启手部推理");
await Task.Delay(20);
var outside = Frame(Right(100, 100), new Hand { HandType = HandType.Left, Rect = new(500, 400, 20, 20) });
timedEngine.ProcessFrame(outside, captureDecisionImage: region =>
{
Check(region is { X1: 460, Y1: 360, X2: 560, Y2: 460 }, "计时应从全画面定位指定送检手");
return VisionDecisionImage.Encode(currentImage, region);
});
await timedFake.Called.Task.WaitAsync(TimeSpan.FromSeconds(5));
timedEngine.Stop();
Console.WriteLine("PASS: 送检手别独立、计时跟手取图、当前帧裁剪、历史位置失效及旧配方兼容");
}
private sealed class ProbeClock : TimeProvider

View File

@ -74,6 +74,8 @@ internal static class HandContactChecks
step.Detection.Method = ConditionMethod.HandLeaveRegion;
Check(!evaluator.EvaluateStep(step, Frame(left)).IsMet
&& !evaluator.EvaluateStep(step, Frame()).IsMet, "单手接触不得登记为双手进入");
// 双手裁剪由送检手别单独指定。
step.AiConfirmation!.ImageHand = "both";
tracker.Reset();
tracker.Observe(step, Frame(left, right), regions);
tracker.Observe(step, Frame(left), regions);