增加手离开区域触发及步骤送检区域裁剪配置
This commit is contained in:
parent
226f05fa21
commit
6308564440
@ -10,6 +10,7 @@ public static class ConditionMethodLabels
|
||||
{
|
||||
ConditionMethod.TimeElapsed => "持续计时",
|
||||
ConditionMethod.HandInRegion => "手在区域内",
|
||||
ConditionMethod.HandLeaveRegion => "手进入后离开区域",
|
||||
ConditionMethod.HandMove => "手从起点移到终点",
|
||||
ConditionMethod.HandNearObject => "手靠近物体",
|
||||
ConditionMethod.ObjectPresent => "物体出现在画面中",
|
||||
|
||||
@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@ -150,11 +150,13 @@
|
||||
</Grid>
|
||||
<CheckBox Content="手部动作触发后由 AI 确认完成" IsChecked="{Binding RequireAiConfirmation, Mode=TwoWay}" Margin="0,10,0,4" />
|
||||
<StackPanel IsVisible="{Binding RequireAiConfirmation}" Spacing="6">
|
||||
<TextBlock Text="选择手在区域内或手从起点移到终点作为取图触发条件。" TextWrapping="Wrap" />
|
||||
<TextBlock Text="AI 完成判据(明确描述图片上应看到的结果)" />
|
||||
<TextBlock Text="规则满足后取图,由模型检查下方完成条件。选择“手进入后离开区域”可减少手部遮挡。" TextWrapping="Wrap" Foreground="{StaticResource FgDim}" />
|
||||
<TextBlock Text="送检区域(留空使用整张画面)" />
|
||||
<ComboBox x:Name="AiImageRegionPicker" ItemsSource="{Binding DataContext.Recipe.RegionNames, RelativeSource={RelativeSource AncestorType=UserControl}}" SelectedItem="{Binding AiImageRegion, Mode=TwoWay, Converter={StaticResource SelectionConverter}}" />
|
||||
<TextBlock Text="完成条件(用日常语言描述图片中应看到的结果)" />
|
||||
<TextBox Text="{Binding AiCriteria, Mode=TwoWay}" AcceptsReturn="True" TextWrapping="Wrap" MinHeight="64" />
|
||||
<Grid ColumnDefinitions="*,*" RowDefinitions="Auto,Auto,Auto,Auto">
|
||||
<TextBlock Text="最低置信度(0–1)" VerticalAlignment="Center" />
|
||||
<TextBlock Text="最低完成概率(0–1)" VerticalAlignment="Center" />
|
||||
<NumericUpDown Grid.Column="1" Value="{Binding AiMinConfidence, Mode=TwoWay}" Minimum="0" Maximum="1" Increment="0.05" FormatString="0.00" />
|
||||
<TextBlock Grid.Row="1" Text="重试间隔(毫秒)" VerticalAlignment="Center" />
|
||||
<NumericUpDown Grid.Row="1" Grid.Column="1" Value="{Binding AiRetryDelayMs, Mode=TwoWay}" Minimum="500" Maximum="600000" Increment="500" />
|
||||
@ -171,7 +173,7 @@
|
||||
<Button Grid.Column="2" Content="恢复默认" Click="ResetCompletionImageDirectory" Margin="8,0,0,0" />
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
<TextBlock Text="判定条件" FontSize="13" Margin="0,10,0,6" Classes="Title" />
|
||||
<TextBlock Text="触发 / 判定规则" FontSize="13" Margin="0,10,0,6" Classes="Title" />
|
||||
<StackPanel>
|
||||
<TextBlock Text="请先选择判定方法;等待后完成请选择“持续计时”" Classes.state2="{Binding Detection, Converter={x:Static conv:ObjectConverters.IsNull}}" Classes.state3="{Binding Detection.Method, Converter={x:Static conv:StringConverters.IsNullOrEmpty}}" IsVisible="False">
|
||||
</TextBlock>
|
||||
|
||||
@ -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);
|
||||
});
|
||||
|
||||
// 每帧均更新,无检测结果时清除上一帧的手部标记和目标框。
|
||||
|
||||
@ -26,6 +26,7 @@ public class ConditionEvaluator
|
||||
|
||||
/// <summary>稳定帧计数:key = "步骤Id:条件序号"</summary>
|
||||
private readonly Dictionary<string, int> _stablePassCounts = [];
|
||||
private readonly HashSet<int> _leaveRegionVisited = [];
|
||||
|
||||
/// <summary>每只手最近访问过的区域(hand_move 的 from 证据)</summary>
|
||||
private readonly Dictionary<string, HashSet<string>> _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);
|
||||
|
||||
@ -207,7 +207,10 @@ public static class ConditionMethod
|
||||
{
|
||||
/// <summary>该判定方法是否需要手部推理。</summary>
|
||||
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;
|
||||
|
||||
/// <summary>目标出现在画面(1 次)</summary>
|
||||
public const string ObjectPresent = "object_present";
|
||||
@ -218,6 +221,9 @@ public static class ConditionMethod
|
||||
/// <summary>手在区域内(12 次)</summary>
|
||||
public const string HandInRegion = "hand_in_region";
|
||||
|
||||
/// <summary>本步先见到手进入区域,随后区域内无指定手且保持稳定帧。</summary>
|
||||
public const string HandLeaveRegion = "hand_leave_region";
|
||||
|
||||
/// <summary>手从 A 区移到 B 区(7 次;配方里写作 hand_move)</summary>
|
||||
public const string HandMove = "hand_move";
|
||||
|
||||
|
||||
@ -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 判据、置信度、重试间隔或超时配置无效");
|
||||
|
||||
@ -213,7 +213,7 @@ public class SopEngine
|
||||
/// <summary>
|
||||
/// 一帧的判定入口(管线回调)
|
||||
/// </summary>
|
||||
public void ProcessFrame(FrameResult frame, Func<byte[]>? captureJpeg = null)
|
||||
public void ProcessFrame(FrameResult frame, Func<byte[]>? captureJpeg = null, Func<RegionDef?, byte[]>? 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<byte[]>? captureJpeg, out byte[]? evidence)
|
||||
private ConditionResult EvaluateAiStep(StepDef step, FrameResult frame, Func<byte[]>? captureJpeg, Func<RegionDef?, byte[]>? 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 确认…" };
|
||||
}
|
||||
|
||||
@ -6,6 +6,8 @@ namespace SopHelper.Engine.Sop;
|
||||
|
||||
public sealed class AiConfirmation
|
||||
{
|
||||
/// <summary>送检区域名;留空发送整帧。坐标使用相机原始像素。</summary>
|
||||
public string ImageRegion { get; set; } = "";
|
||||
public string Criteria { get; set; } = "";
|
||||
public double MinConfidence { get; set; } = 0.85;
|
||||
public int RetryDelayMs { get; set; } = 3000;
|
||||
|
||||
@ -0,0 +1,22 @@
|
||||
using OpenCvSharp;
|
||||
|
||||
namespace SopHelper.Engine.Sop;
|
||||
|
||||
public static class VisionDecisionImage
|
||||
{
|
||||
/// <summary>先裁剪再缩图,保留小区域细节;区域越界时拒绝,不回退整帧。</summary>
|
||||
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 判定图编码失败");
|
||||
}
|
||||
}
|
||||
@ -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<CheckBox>().Single(c=>c.Content?.ToString()=="手部动作触发后由 AI 确认完成");
|
||||
Check(toggle.IsChecked==true,"Editor exposes AI confirmation switch");
|
||||
var picker=editor.FindControl<ComboBox>("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);
|
||||
|
||||
@ -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
|
||||
|
||||
81
tests/VisionDecision.Smoke/TriggerImageChecks.cs
Normal file
81
tests/VisionDecision.Smoke/TriggerImageChecks.cs
Normal file
@ -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<Vec3b>(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: 手进入后离开、防抖、复位、区域裁剪、缩图、越界拒绝、送检图与完成证据一致");
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user