From 630856444023d10204fad11aa0af332cc585f2c7 Mon Sep 17 00:00:00 2001
From: tfarcraw <123211521@163.com>
Date: Fri, 13 Nov 2026 00:59:35 +0800
Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E6=89=8B=E7=A6=BB=E5=BC=80?=
=?UTF-8?q?=E5=8C=BA=E5=9F=9F=E8=A7=A6=E5=8F=91=E5=8F=8A=E6=AD=A5=E9=AA=A4?=
=?UTF-8?q?=E9=80=81=E6=A3=80=E5=8C=BA=E5=9F=9F=E8=A3=81=E5=89=AA=E9=85=8D?=
=?UTF-8?q?=E7=BD=AE?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.../RecipeEditor/ConditionMethodLabels.cs | 1 +
.../VVMs/RecipeEditor/EditorNodes.cs | 6 ++
.../VVMs/RecipeEditor/RecipeEditor.axaml | 10 ++-
.../VVMs/SopPage/SopPageViewModel.cs | 4 +-
.../Sop/ConditionEvaluator.cs | 22 +++++
.../Sop/SopConfig.cs | 8 +-
.../Sop/SopConfigLoader.cs | 11 ++-
.../Sop/SopEngine.cs | 25 +++---
.../Sop/VisionDecision.cs | 2 +
.../Sop/VisionDecisionImage.cs | 22 +++++
tests/Avalonia.Smoke/Program.cs | 10 ++-
tests/VisionDecision.Smoke/Program.cs | 1 +
.../TriggerImageChecks.cs | 81 +++++++++++++++++++
13 files changed, 183 insertions(+), 20 deletions(-)
create mode 100644 src/SopHelper.CrossPlatform.Engine/Sop/VisionDecisionImage.cs
create mode 100644 tests/VisionDecision.Smoke/TriggerImageChecks.cs
diff --git a/src/SopHelper.Avalonia/VVMs/RecipeEditor/ConditionMethodLabels.cs b/src/SopHelper.Avalonia/VVMs/RecipeEditor/ConditionMethodLabels.cs
index d1d1dde..263ec37 100644
--- a/src/SopHelper.Avalonia/VVMs/RecipeEditor/ConditionMethodLabels.cs
+++ b/src/SopHelper.Avalonia/VVMs/RecipeEditor/ConditionMethodLabels.cs
@@ -10,6 +10,7 @@ public static class ConditionMethodLabels
{
ConditionMethod.TimeElapsed => "持续计时",
ConditionMethod.HandInRegion => "手在区域内",
+ ConditionMethod.HandLeaveRegion => "手进入后离开区域",
ConditionMethod.HandMove => "手从起点移到终点",
ConditionMethod.HandNearObject => "手靠近物体",
ConditionMethod.ObjectPresent => "物体出现在画面中",
diff --git a/src/SopHelper.Avalonia/VVMs/RecipeEditor/EditorNodes.cs b/src/SopHelper.Avalonia/VVMs/RecipeEditor/EditorNodes.cs
index 3fd10a5..a390560 100644
--- a/src/SopHelper.Avalonia/VVMs/RecipeEditor/EditorNodes.cs
+++ b/src/SopHelper.Avalonia/VVMs/RecipeEditor/EditorNodes.cs
@@ -103,6 +103,7 @@ public class RecipeNode : EditorNode
"",
ConditionMethod.TimeElapsed,
ConditionMethod.HandInRegion,
+ ConditionMethod.HandLeaveRegion,
ConditionMethod.HandMove,
ConditionMethod.HandNearObject,
ConditionMethod.ObjectPresent,
@@ -427,6 +428,7 @@ public class RecipeNode : EditorNode
AiConfirmation = step.AiConfirmation is null ? null : new AiConfirmation
{
Criteria = step.AiConfirmation.Criteria, MinConfidence = step.AiConfirmation.MinConfidence,
+ ImageRegion = step.AiConfirmation.ImageRegion,
RetryDelayMs = step.AiConfirmation.RetryDelayMs, TimeoutSeconds = step.AiConfirmation.TimeoutSeconds,
},
};
@@ -488,6 +490,7 @@ public class RecipeNode : EditorNode
AiConfirmation = step.RequireAiConfirmation ? new AiConfirmation
{
Criteria = step.AiCriteria, MinConfidence = step.AiMinConfidence,
+ ImageRegion = step.AiImageRegion,
RetryDelayMs = step.AiRetryDelayMs, TimeoutSeconds = step.AiTimeoutSeconds,
} : null,
};
@@ -783,10 +786,12 @@ public class StepNode : EditorNode
{
private bool _requireAiConfirmation;
private string _aiCriteria = "";
+ private string _aiImageRegion = "";
private double _aiMinConfidence = 0.85;
private int _aiRetryDelayMs = 3000, _aiTimeoutSeconds = 30;
public bool RequireAiConfirmation { get => _requireAiConfirmation; set => SetProperty(ref _requireAiConfirmation, value); }
public string AiCriteria { get => _aiCriteria; set => SetProperty(ref _aiCriteria, value); }
+ public string AiImageRegion { get => _aiImageRegion; set => SetProperty(ref _aiImageRegion, value); }
public double AiMinConfidence { get => _aiMinConfidence; set => SetProperty(ref _aiMinConfidence, value); }
public int AiRetryDelayMs { get => _aiRetryDelayMs; set => SetProperty(ref _aiRetryDelayMs, value); }
public int AiTimeoutSeconds { get => _aiTimeoutSeconds; set => SetProperty(ref _aiTimeoutSeconds, value); }
@@ -797,6 +802,7 @@ public class StepNode : EditorNode
RequireAiConfirmation = value is not null;
if (value is null) return;
AiCriteria = value.Criteria; AiMinConfidence = value.MinConfidence;
+ AiImageRegion = value.ImageRegion;
AiRetryDelayMs = value.RetryDelayMs; AiTimeoutSeconds = value.TimeoutSeconds;
}
}
diff --git a/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml b/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml
index c97204d..6402755 100644
--- a/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml
+++ b/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml
@@ -150,11 +150,13 @@
-
-
+
+
+
+
-
+
@@ -171,7 +173,7 @@
-
+
diff --git a/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs b/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs
index 42b60ca..e2e84b8 100644
--- a/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs
+++ b/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs
@@ -892,10 +892,10 @@ public class SopPageViewModel : ViewModelBase
_lastFrame = result;
}
- _engine.ProcessFrame(result, () =>
+ _engine.ProcessFrame(result, captureDecisionImage: region =>
{
if (_judgementFrame is not { } frame) return [];
- return Cv2.ImEncode(".jpg", frame, out var jpeg) ? jpeg : [];
+ return VisionDecisionImage.Encode(frame, region);
});
// 每帧均更新,无检测结果时清除上一帧的手部标记和目标框。
diff --git a/src/SopHelper.CrossPlatform.Engine/Sop/ConditionEvaluator.cs b/src/SopHelper.CrossPlatform.Engine/Sop/ConditionEvaluator.cs
index 5663673..cce0885 100644
--- a/src/SopHelper.CrossPlatform.Engine/Sop/ConditionEvaluator.cs
+++ b/src/SopHelper.CrossPlatform.Engine/Sop/ConditionEvaluator.cs
@@ -26,6 +26,7 @@ public class ConditionEvaluator
/// 稳定帧计数:key = "步骤Id:条件序号"
private readonly Dictionary _stablePassCounts = [];
+ private readonly HashSet _leaveRegionVisited = [];
/// 每只手最近访问过的区域(hand_move 的 from 证据)
private readonly Dictionary> _handVisitedRegions = [];
@@ -59,6 +60,7 @@ public class ConditionEvaluator
public void Reset()
{
_stablePassCounts.Clear();
+ _leaveRegionVisited.Clear();
_handVisitedRegions.Clear();
_objectVisitedRegions.Clear();
_stepEnterTime.Clear();
@@ -145,6 +147,26 @@ public class ConditionEvaluator
: No($"手未在 {condition.Region} 内");
}
+ case ConditionMethod.HandLeaveRegion:
+ {
+ var region = Region(condition.Region);
+ if (region is null) return No($"区域 {condition.Region} 不存在");
+ var selected = frame.Hands.Where(h => condition.Hand.ToLowerInvariant() switch
+ {
+ "left" or "左手" => h.HandType == HandType.Left,
+ "right" or "右手" => h.HandType == HandType.Right,
+ _ => true,
+ });
+ if (selected.Any(h => h.Rect.Intersects(region.Value, tolerance)))
+ {
+ _leaveRegionVisited.Add(step.Id);
+ return No($"等待手离开 {condition.Region}");
+ }
+ return _leaveRegionVisited.Contains(step.Id)
+ ? Yes($"手已离开 {condition.Region}")
+ : No($"等待手先进入 {condition.Region}");
+ }
+
case ConditionMethod.HandNearObject:
{
var hand = PickHand(frame, condition.Hand);
diff --git a/src/SopHelper.CrossPlatform.Engine/Sop/SopConfig.cs b/src/SopHelper.CrossPlatform.Engine/Sop/SopConfig.cs
index a68416b..fa26f93 100644
--- a/src/SopHelper.CrossPlatform.Engine/Sop/SopConfig.cs
+++ b/src/SopHelper.CrossPlatform.Engine/Sop/SopConfig.cs
@@ -207,7 +207,10 @@ public static class ConditionMethod
{
/// 该判定方法是否需要手部推理。
public static bool RequiresHandDetection(string? method) => method?.ToLowerInvariant() is
- HandInRegion or HandMove or HandNearObject;
+ HandInRegion or HandLeaveRegion or HandMove or HandNearObject;
+
+ public static bool SupportsAiTrigger(string? method) => method?.ToLowerInvariant() is
+ HandInRegion or HandLeaveRegion or HandMove;
/// 目标出现在画面(1 次)
public const string ObjectPresent = "object_present";
@@ -218,6 +221,9 @@ public static class ConditionMethod
/// 手在区域内(12 次)
public const string HandInRegion = "hand_in_region";
+ /// 本步先见到手进入区域,随后区域内无指定手且保持稳定帧。
+ public const string HandLeaveRegion = "hand_leave_region";
+
/// 手从 A 区移到 B 区(7 次;配方里写作 hand_move)
public const string HandMove = "hand_move";
diff --git a/src/SopHelper.CrossPlatform.Engine/Sop/SopConfigLoader.cs b/src/SopHelper.CrossPlatform.Engine/Sop/SopConfigLoader.cs
index d7edae5..5010bda 100644
--- a/src/SopHelper.CrossPlatform.Engine/Sop/SopConfigLoader.cs
+++ b/src/SopHelper.CrossPlatform.Engine/Sop/SopConfigLoader.cs
@@ -86,6 +86,7 @@ public static partial class SopConfigLoader
ConditionMethod.ObjectPresent,
ConditionMethod.ObjectInZone,
ConditionMethod.HandInRegion,
+ ConditionMethod.HandLeaveRegion,
ConditionMethod.HandMove,
ConditionMethod.HandNearObject,
ConditionMethod.TimeElapsed,
@@ -105,8 +106,14 @@ public static partial class SopConfigLoader
{
if (step.AiConfirmation is { } ai)
{
- if (step.Detection?.Method?.ToLowerInvariant() is not (ConditionMethod.HandInRegion or ConditionMethod.HandMove))
- config.Warnings.Add($"步骤 {step.Id} 的 AI 确认必须使用 hand_in_region 或 hand_move 触发");
+ if (!ConditionMethod.SupportsAiTrigger(step.Detection?.Method))
+ config.Warnings.Add($"步骤 {step.Id} 的 AI 确认必须使用手进入区域、离开区域或区域间移动触发");
+ if (!string.IsNullOrWhiteSpace(ai.ImageRegion))
+ {
+ var region = config.Sop.Regions.FirstOrDefault(p => p.Key.Equals(ai.ImageRegion, StringComparison.OrdinalIgnoreCase)).Value;
+ if (region is null || region.X1 < 0 || region.Y1 < 0 || region.X2 <= region.X1 || region.Y2 <= region.Y1)
+ config.Warnings.Add($"步骤 {step.Id} 的 AI 取图区域 '{ai.ImageRegion}' 不存在或坐标无效");
+ }
if (string.IsNullOrWhiteSpace(ai.Criteria) || !double.IsFinite(ai.MinConfidence) || ai.MinConfidence is < 0 or > 1
|| ai.RetryDelayMs < 0 || ai.TimeoutSeconds <= 0)
config.Warnings.Add($"步骤 {step.Id} 的 AI 判据、置信度、重试间隔或超时配置无效");
diff --git a/src/SopHelper.CrossPlatform.Engine/Sop/SopEngine.cs b/src/SopHelper.CrossPlatform.Engine/Sop/SopEngine.cs
index 96b205f..9ff9b0e 100644
--- a/src/SopHelper.CrossPlatform.Engine/Sop/SopEngine.cs
+++ b/src/SopHelper.CrossPlatform.Engine/Sop/SopEngine.cs
@@ -213,7 +213,7 @@ public class SopEngine
///
/// 一帧的判定入口(管线回调)
///
- public void ProcessFrame(FrameResult frame, Func? captureJpeg = null)
+ public void ProcessFrame(FrameResult frame, Func? captureJpeg = null, Func? captureDecisionImage = null)
{
if (State != EngineState.Running) return;
@@ -224,7 +224,7 @@ public class SopEngine
byte[]? evidence = null;
var result = step.AiConfirmation is null
? _evaluator.EvaluateStep(step, frame)
- : EvaluateAiStep(step, frame, captureJpeg, out evidence);
+ : EvaluateAiStep(step, frame, captureJpeg, captureDecisionImage, out evidence);
// 2. 违规:超时 / 必留物被拿走
var violation = _violations.CheckTimeout(step, _stepEnteredAt)
@@ -282,12 +282,12 @@ public class SopEngine
NotifyCurrent();
}
- private ConditionResult EvaluateAiStep(StepDef step, FrameResult frame, Func? captureJpeg, out byte[]? evidence)
+ private ConditionResult EvaluateAiStep(StepDef step, FrameResult frame, Func? captureJpeg, Func? captureDecisionImage, out byte[]? evidence)
{
evidence = null;
var options = step.AiConfirmation!;
- if (step.Detection?.Method?.ToLowerInvariant() is not (ConditionMethod.HandInRegion or ConditionMethod.HandMove))
- return new() { Message = "AI 确认仅支持纯手部区域或移动触发" };
+ if (!ConditionMethod.SupportsAiTrigger(step.Detection?.Method))
+ return new() { Message = "AI 确认需要手进入、离开区域或区域间移动触发" };
if (string.IsNullOrWhiteSpace(options.Criteria) || !double.IsFinite(options.MinConfidence) || options.MinConfidence is < 0 or > 1
|| options.RetryDelayMs < 0 || options.TimeoutSeconds <= 0)
return new() { Message = "AI 确认配置无效" };
@@ -308,21 +308,28 @@ public class SopEngine
if (Environment.TickCount64 < _nextDecisionAt) return new() { Message = "等待 AI 重试间隔,手部条件满足后重新取图" };
// 配置缺失不能绕过 AI;限流,避免逐帧刷日志。
_nextDecisionAt = Environment.TickCount64 + Math.Max(500, options.RetryDelayMs);
- if (VisionDecisionClient is not { } client || captureJpeg is null)
+ if (VisionDecisionClient is not { } client || captureJpeg is null && captureDecisionImage is null)
return new() { Message = "AI 接口或取图回调未配置" };
try
{
- var jpeg = captureJpeg();
+ RegionDef? region = null;
+ if (!string.IsNullOrWhiteSpace(options.ImageRegion))
+ {
+ region = _config.Sop.Regions.FirstOrDefault(p => p.Key.Equals(options.ImageRegion, StringComparison.OrdinalIgnoreCase)).Value;
+ if (region is null || captureDecisionImage is null)
+ return new() { Message = "AI 取图区域不存在或未配置区域取图,未发送图片" };
+ }
+ var jpeg = captureDecisionImage is not null ? captureDecisionImage(region) : captureJpeg!();
if (jpeg.Length == 0) return new() { Message = "AI 判定取图失败" };
var request = new VisionDecisionRequest(_config.Sop.Name, step.Id, step.Name, step.Description,
options.Criteria, frame.FrameId, frame.Timestamp, jpeg);
var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(options.TimeoutSeconds));
_pendingDecision = new(RunDecisionAsync(client, request, cancellation.Token), jpeg, cancellation);
- Log("info", $"步骤 {step.Id} 手部触发取图,提交 AI 判定(帧 {frame.FrameId})");
+ Log("info", $"步骤 {step.Id} 手部触发取图,提交 AI 判定(帧 {frame.FrameId},区域:{(region is null ? "整帧" : options.ImageRegion)})");
}
catch (Exception)
{
- return new() { Message = "AI 判定取图失败,等待重试" };
+ return new() { Message = "AI 判定取图失败,请检查区域坐标与相机尺寸,等待重试" };
}
return new() { Message = "手部动作已触发取图,等待 AI 确认…" };
}
diff --git a/src/SopHelper.CrossPlatform.Engine/Sop/VisionDecision.cs b/src/SopHelper.CrossPlatform.Engine/Sop/VisionDecision.cs
index 504449c..94bd08f 100644
--- a/src/SopHelper.CrossPlatform.Engine/Sop/VisionDecision.cs
+++ b/src/SopHelper.CrossPlatform.Engine/Sop/VisionDecision.cs
@@ -6,6 +6,8 @@ namespace SopHelper.Engine.Sop;
public sealed class AiConfirmation
{
+ /// 送检区域名;留空发送整帧。坐标使用相机原始像素。
+ public string ImageRegion { get; set; } = "";
public string Criteria { get; set; } = "";
public double MinConfidence { get; set; } = 0.85;
public int RetryDelayMs { get; set; } = 3000;
diff --git a/src/SopHelper.CrossPlatform.Engine/Sop/VisionDecisionImage.cs b/src/SopHelper.CrossPlatform.Engine/Sop/VisionDecisionImage.cs
new file mode 100644
index 0000000..5790c3e
--- /dev/null
+++ b/src/SopHelper.CrossPlatform.Engine/Sop/VisionDecisionImage.cs
@@ -0,0 +1,22 @@
+using OpenCvSharp;
+
+namespace SopHelper.Engine.Sop;
+
+public static class VisionDecisionImage
+{
+ /// 先裁剪再缩图,保留小区域细节;区域越界时拒绝,不回退整帧。
+ public static byte[] Encode(Mat frame, RegionDef? region, int maxEdge = 512)
+ {
+ if (frame.Empty() || maxEdge <= 0) throw new ArgumentException("判定帧或图片尺寸无效");
+ var bounds = region is null ? new Rect(0, 0, frame.Width, frame.Height)
+ : new Rect(region.X1, region.Y1, region.X2 - region.X1, region.Y2 - region.Y1);
+ if (bounds.X < 0 || bounds.Y < 0 || bounds.Width <= 0 || bounds.Height <= 0
+ || (long)bounds.X + bounds.Width > frame.Width || (long)bounds.Y + bounds.Height > frame.Height)
+ throw new ArgumentException("AI 取图区域超出当前相机画面");
+ using var crop = new Mat(frame, bounds);
+ using var resized = new Mat();
+ var scale = Math.Min(1d, (double)maxEdge / Math.Max(crop.Width, crop.Height));
+ Cv2.Resize(crop, resized, new Size(Math.Max(1, (int)Math.Round(crop.Width * scale)), Math.Max(1, (int)Math.Round(crop.Height * scale))), 0, 0, InterpolationFlags.Area);
+ return Cv2.ImEncode(".jpg", resized, out var jpeg) ? jpeg : throw new IOException("AI 判定图编码失败");
+ }
+}
diff --git a/tests/Avalonia.Smoke/Program.cs b/tests/Avalonia.Smoke/Program.cs
index 99699af..ae8a89e 100644
--- a/tests/Avalonia.Smoke/Program.cs
+++ b/tests/Avalonia.Smoke/Program.cs
@@ -773,10 +773,10 @@ internal static class Smoke
config.Sop.Settings.AutoResetOnComplete=false;
config.Sop.Regions["work"]=new(){X1=0,Y1=0,X2=64,Y2=48};
config.Sop.Steps.Add(new(){Id=1,Name="装配",Detection=new(){Method="hand_in_region",Region="work",StableFrames=1},
- AiConfirmation=new(){Criteria="红色零件安装到位",MinConfidence=.9,RetryDelayMs=4500,TimeoutSeconds=20}});
+ AiConfirmation=new(){Criteria="红色零件安装到位",ImageRegion="work",MinConfidence=.9,RetryDelayMs=4500,TimeoutSeconds=20}});
var roundTrip=RecipeNode.From(config,file,false).ToConfig();
var ai=roundTrip.Sop.Steps[0].AiConfirmation;
- Check(ai is {Criteria:"红色零件安装到位",MinConfidence:.9,RetryDelayMs:4500,TimeoutSeconds:20},"AI settings survive editor mapping");
+ Check(ai is {Criteria:"红色零件安装到位",ImageRegion:"work",MinConfidence:.9,RetryDelayMs:4500,TimeoutSeconds:20},"AI settings survive editor mapping");
Directory.CreateDirectory(store.DirectoryFor(name));SopHelper.Engine.Sop.SopConfigLoader.Save(roundTrip,store.ConfigPath(name));
var editorVm=new RecipeEditorViewModel();
editorVm.OnDialogOpened(new DialogParameters{{"directory",store.RecipesDirectory},{"path",store.ConfigPath(name)},{"config",roundTrip},{"new",false}});
@@ -786,6 +786,12 @@ internal static class Smoke
{
var toggle=editor.GetVisualDescendants().OfType().Single(c=>c.Content?.ToString()=="手部动作触发后由 AI 确认完成");
Check(toggle.IsChecked==true,"Editor exposes AI confirmation switch");
+ var picker=editor.FindControl("AiImageRegionPicker")!;
+ Check(picker.SelectedItem?.ToString()=="work","Editor exposes configured image region");
+ picker.SelectedItem="";await Task.Delay(20);
+ Check(editorVm.Recipe.ToConfig().Sop.Steps[0].AiConfirmation?.ImageRegion=="","Editor can switch to full-frame capture");
+ picker.SelectedItem="work";await Task.Delay(20);
+ Check(editorVm.Recipe.ToConfig().Sop.Steps[0].AiConfirmation?.ImageRegion=="work","Editor persists selected crop region");
toggle.IsChecked=false;await Task.Delay(20);
Check(editorVm.Recipe.ToConfig().Sop.Steps[0].AiConfirmation is null,"Disabling AI restores direct condition evaluation");
toggle.IsChecked=true;await Task.Delay(20);
diff --git a/tests/VisionDecision.Smoke/Program.cs b/tests/VisionDecision.Smoke/Program.cs
index 42b533a..fe943a8 100644
--- a/tests/VisionDecision.Smoke/Program.cs
+++ b/tests/VisionDecision.Smoke/Program.cs
@@ -111,6 +111,7 @@ try
finally { for (int i = 0; i < names.Length; i++) Environment.SetEnvironmentVariable(names[i], previous[i]); }
await LayaChecks.RunAsync(args);
await D3Checks.RunAsync(args);
+await TriggerImageChecks.RunAsync();
Console.WriteLine("PASS: 手部触发、单请求、AI 门控、证据帧、限流、超时、旧结果失效、配方往返、兼容 HTTP 消息及错误响应、Laya 原生适配与复核语义");
sealed class FakeDecision : IVisionDecisionClient
diff --git a/tests/VisionDecision.Smoke/TriggerImageChecks.cs b/tests/VisionDecision.Smoke/TriggerImageChecks.cs
new file mode 100644
index 0000000..d3b3dd2
--- /dev/null
+++ b/tests/VisionDecision.Smoke/TriggerImageChecks.cs
@@ -0,0 +1,81 @@
+using OpenCvSharp;
+using SopHelper.Engine.Common;
+using SopHelper.Engine.Sop;
+
+internal static class TriggerImageChecks
+{
+ public static async Task RunAsync()
+ {
+ static void Check(bool value, string message) { if (!value) throw new Exception(message); }
+ var config = SopConfigLoader.Parse("""
+ sop:
+ name: 离开区域后检查
+ settings: { auto_reset_on_complete: false }
+ regions:
+ work: { x1: 0, y1: 0, x2: 100, y2: 100 }
+ inspect: { x1: 200, y1: 100, x2: 1000, y2: 500 }
+ steps:
+ - id: 1
+ name: 放好零件
+ detection: { method: hand_leave_region, region: work, hand: any, stable_frames: 2, tolerance: 1 }
+ ai_confirmation: { image_region: inspect, criteria: 零件放在盒子里, min_confidence: 0.9 }
+ """);
+ Check(config.Warnings.Count == 0, "手离开与裁剪配方必须有效且不要求 YOLO");
+ Check(SopConfigLoader.Parse(SopConfigLoader.ToYaml(config)).Sop.Steps[0].AiConfirmation!.ImageRegion == "inspect", "裁剪区域必须随配方保存");
+ using var full = new Mat(600, 1200, MatType.CV_8UC3, new Scalar(0, 0, 255));
+ using (var roi = new Mat(full, new Rect(200, 100, 800, 400))) roi.SetTo(new Scalar(0, 255, 0));
+ var cropped = VisionDecisionImage.Encode(full, config.Sop.Regions["inspect"]);
+ using (var decoded = Cv2.ImDecode(cropped, ImreadModes.Color))
+ {
+ Check(decoded.Width == 512 && decoded.Height == 256, "必须先裁剪再等比缩到 512 长边");
+ var pixel = decoded.At(0, 0);
+ Check(pixel.Item1 > 240 && pixel.Item2 < 15, "裁剪不得混入区域外红色背景");
+ }
+ var rejected = false;
+ try { VisionDecisionImage.Encode(full, new() { X1 = -1, Y1 = 0, X2 = 100, Y2 = 100 }); }
+ catch (ArgumentException) { rejected = true; }
+ Check(rejected, "越界裁剪必须拒绝,不能悄悄发送整图");
+ using (var whole = Cv2.ImDecode(VisionDecisionImage.Encode(full, null), ImreadModes.Color))
+ Check(whole.Width == 512 && whole.Height == 256, "未指定区域时应发送缩小后的整帧");
+
+ var fake = new FakeDecision();
+ var engine = new SopEngine { VisionDecisionClient = fake };
+ engine.Load(config); engine.Start();
+ var inside = new FrameResult { FrameId = 5, Hands = [new() { Rect = new(20, 20, 20, 20) }] };
+ var outside = new FrameResult { FrameId = 6, Hands = [] };
+ int captures = 0;
+ byte[] Capture(RegionDef? region)
+ {
+ Check(ReferenceEquals(region, config.Sop.Regions["inspect"]), "引擎必须向取图层传递当前步骤的送检区域");
+ captures++; return cropped;
+ }
+ for (int i = 0; i < 5; i++) engine.ProcessFrame(outside, captureDecisionImage: Capture);
+ Check(captures == 0, "初始没有手不能误认为手已经离开");
+ engine.ProcessFrame(inside, captureDecisionImage: Capture);
+ engine.ProcessFrame(outside, captureDecisionImage: Capture);
+ Check(captures == 0, "手消失一帧不能绕过稳定帧防抖");
+ engine.ProcessFrame(inside, captureDecisionImage: Capture);
+ engine.ProcessFrame(outside, captureDecisionImage: Capture);
+ Check(captures == 0, "手重新出现必须清空离开稳定帧");
+ engine.ProcessFrame(outside, captureDecisionImage: Capture);
+ await fake.Called.Task.WaitAsync(TimeSpan.FromSeconds(5));
+ Check(captures == 1 && fake.Request!.Jpeg.SequenceEqual(cropped), "手离开稳定后应仅提交裁剪图");
+ byte[]? evidence = null;
+ engine.StepSnapshotChanged += snapshot => { if (snapshot.IsMet) evidence = snapshot.EvidenceJpeg; };
+ fake.Result.SetResult(new(true, .97, "盒子里有零件"));
+ for (int i = 0; i < 100 && engine.State != EngineState.Completed; i++)
+ { await Task.Delay(10); engine.ProcessFrame(outside, captureDecisionImage: Capture); }
+ Check(engine.State == EngineState.Completed && ReferenceEquals(evidence, cropped), "完成证据必须是送检裁剪图");
+ engine.Reset();
+ engine.ProcessFrame(outside, captureDecisionImage: Capture); engine.ProcessFrame(outside, captureDecisionImage: Capture);
+ Check(captures == 1 && engine.State == EngineState.Running, "复位后必须重新观察手进入,不能复用上一轮访问证据");
+ config.Sop.Steps[0].AiConfirmation!.ImageRegion = "missing";
+ Check(SopConfigLoader.Parse(SopConfigLoader.ToYaml(config)).Warnings.Any(w => w.Contains("取图区域")), "无效取图区域必须提示");
+ var next = new FakeDecision(); engine.VisionDecisionClient = next;
+ engine.ProcessFrame(inside, captureDecisionImage: Capture);
+ engine.ProcessFrame(outside, captureDecisionImage: Capture); engine.ProcessFrame(outside, captureDecisionImage: Capture);
+ Check(captures == 1 && !next.Called.Task.IsCompleted, "无效取图区域不得发送图片或退回整帧");
+ engine.Stop();
+ Console.WriteLine("PASS: 手进入后离开、防抖、复位、区域裁剪、缩图、越界拒绝、送检图与完成证据一致");
+ }
+}