新增物品在区域触发和稳定帧判定

This commit is contained in:
wanglei 2026-12-06 18:32:00 +08:00
parent eb4b0a1c7b
commit 65913be0c2
8 changed files with 155 additions and 13 deletions

View File

@ -167,7 +167,10 @@ public class FrameResult
/// <summary>原图像素尺寸</summary>
public (int W, int H) Size { get; set; }
/// <summary>YOLO 检出目标</summary>
/// <summary>本帧是否已完成物品检测,用于区分未推理与推理后未检出。</summary>
public bool ObjectDetectionRan { get; set; }
/// <summary>YOLO 检出目标,坐标使用原图像素。</summary>
public List<Detection> Detections { get; set; } = [];
/// <summary>检出的手</summary>

View File

@ -115,6 +115,26 @@ public class ConditionEvaluator
: new ConditionResult { IsMet = false, Message = $"持续 {elapsed / 1000:F1}s,还差 {(need - elapsed) / 1000:F1}s" };
}
case ConditionMethod.ObjectInZone:
{
var area = Region(condition.Region);
if (area is not { X: >= 0, Y: >= 0, W: > 0, H: > 0 }) return No($"区域 {condition.Region} 不存在或坐标无效");
var target = condition.TargetObject?.Trim();
if (string.IsNullOrEmpty(target)) return No("请设置目标类别");
if (!float.IsFinite(condition.MinConfidence) || condition.MinConfidence is < 0 or > 1)
return No("物品置信度必须在 0 到 1 之间");
if (!frame.ObjectDetectionRan) return No("当前帧未完成物品检测,请检查 YOLO 模型状态");
// 保留整帧上下文供模型识别。模型输出已映射回原图,按中心点与标定区域比较。
var matched = frame.Detections.Any(item =>
item.Label.Equals(target, StringComparison.OrdinalIgnoreCase)
&& float.IsFinite(item.Confidence) && item.Confidence >= condition.MinConfidence
&& item.Rect.W > 0 && item.Rect.H > 0
&& area.Value.Contains(item.Rect.Center.Cx, item.Rect.Center.Cy, tolerance));
return matched ? Yes($"{target} 在 {condition.Region} 内")
: No($"等待 {target} 出现在 {condition.Region} 内");
}
case ConditionMethod.HandInRegion:
case ConditionMethod.HandOutsideRegion:
{

View File

@ -52,10 +52,27 @@ public class SopBody
/// <summary>区域定义(键 = 配方里引用的区域名)</summary>
public Dictionary<string, RegionDef> Regions { get; set; } = new(StringComparer.OrdinalIgnoreCase);
/// <summary>物品触发使用的 YOLO 模型,纯手部或计时配方可省略。</summary>
[YamlMember(DefaultValuesHandling = DefaultValuesHandling.OmitNull)]
public ModelDef? Model { get; set; }
/// <summary>步骤列表(按书写顺序执行)</summary>
public List<StepDef> Steps { get; set; } = [];
}
/// <summary>配方绑定的 YOLO 检测模型,沿用旧 YAML 字段以便复用现有模型配置。</summary>
public sealed class ModelDef
{
/// <summary>ONNX 路径,可使用绝对路径或相对工作区、程序目录的路径。</summary>
public string Path { get; set; } = "";
/// <summary>按模型类别索引排列,可留空以读取 ONNX 的 names 元数据。</summary>
public List<string> Classes { get; set; } = [];
/// <summary>动态输入模型的正方形边长,固定输入模型以文件中的尺寸为准。</summary>
public int InputSize { get; set; } = 640;
}
/// <summary>
/// 引擎运行参数;旧配方 settings 只读兼容。
/// </summary>
@ -197,10 +214,10 @@ public class StepCondition
/// <summary>检测手别:any(任何手)、left(左手)、right(右手)、both(双手)</summary>
public string Hand { get; set; } = "any";
/// <summary>手-物相邻容差(像素)</summary>
/// <summary>区域向外扩展的容差(像素)。</summary>
public float Tolerance { get; set; } = 60f;
/// <summary>本条件置信度阈值</summary>
/// <summary>物品触发使用的最低 YOLO 置信度,取值 0 到 1。</summary>
public float MinConfidence { get; set; } = 0.7f;
/// <summary>稳定帧数(连续命中才放行)</summary>
@ -221,13 +238,19 @@ public static class ConditionMethod
public static bool RequiresHandDetection(string? method) => method?.ToLowerInvariant() is
HandInRegion or HandOutsideRegion or HandLeaveRegion or HandMove;
public static bool SupportsAiTrigger(string? method) => method?.ToLowerInvariant() is
HandInRegion or HandOutsideRegion or HandLeaveRegion or HandMove or TimeElapsed;
/// <summary>只有物品在区域规则会请求物品推理。</summary>
public static bool RequiresObjectDetection(string? method) =>
string.Equals(method, ObjectInZone, StringComparison.OrdinalIgnoreCase);
/// <summary>规则命中后可以采集证据并交由 AI 确认的触发方法。</summary>
public static bool SupportsAiTrigger(string? method) =>
RequiresHandDetection(method) || RequiresObjectDetection(method)
|| string.Equals(method, TimeElapsed, StringComparison.OrdinalIgnoreCase);
/// <summary>目标出现在画面(1 次)</summary>
public const string ObjectPresent = "object_present";
/// <summary>目标在区域内(14 次,第二常用)</summary>
/// <summary>指定类别的检测框中心落在区域内,连续命中达到稳定帧数时触发送检。</summary>
public const string ObjectInZone = "object_in_zone";
/// <summary>手在区域内(12 次)</summary>

View File

@ -39,7 +39,7 @@ public static partial class SopConfigLoader
.IgnoreUnmatchedProperties()
.Build();
// 旧模型与步骤结束图目录字段直接跳过,旧触发方法保留给校验提示。
// 旧步骤结束图目录字段直接跳过,旧模型绑定仍可用于物品在区域触发。
var config = deserializer.Deserialize<SopConfig>(yaml) ?? new SopConfig();
MigrateStepSettings(config);
@ -125,6 +125,7 @@ public static partial class SopConfigLoader
ConditionMethod.HandLeaveRegion,
ConditionMethod.HandMove,
ConditionMethod.TimeElapsed,
ConditionMethod.ObjectInZone,
};
var regionNames = new HashSet<String>(config.Sop.Regions.Keys, StringComparer.OrdinalIgnoreCase);
@ -137,6 +138,10 @@ public static partial class SopConfigLoader
if (ordered.Count > 0 && ordered[0].Id != config.Sop.Steps.Min(s => s.Id))
config.Warnings.Add("步骤顺序与 Id 不一致,执行顺序按 Id 升序");
if (ordered.Any(step => ConditionMethod.RequiresObjectDetection(step.Detection?.Method))
&& (config.Sop.Model is not { } model || string.IsNullOrWhiteSpace(model.Path) || model.InputSize < 1))
config.Warnings.Add("物品在区域触发需要配置 YOLO ONNX 模型路径及有效的输入尺寸");
foreach (var step in ordered)
{
step.AiConfirmation ??= new AiConfirmation();
@ -172,6 +177,21 @@ public static partial class SopConfigLoader
if (condition.Method == ConditionMethod.HandMove && (string.IsNullOrWhiteSpace(condition.FromRegion) || string.IsNullOrWhiteSpace(condition.ToRegion)))
config.Warnings.Add($"步骤 {step.Id}({step.Name})请设置起点和终点区域");
if (ConditionMethod.RequiresObjectDetection(condition.Method))
{
var region = config.Sop.Regions.FirstOrDefault(entry =>
entry.Key.Equals(condition.Region, 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} 请设置坐标有效的物品触发区域");
if (string.IsNullOrWhiteSpace(condition.TargetObject))
config.Warnings.Add($"步骤 {step.Id} 请填写目标类别");
else if (config.Sop.Model?.Classes is { Count: > 0 } classes
&& !classes.Contains(condition.TargetObject.Trim(), StringComparer.OrdinalIgnoreCase))
config.Warnings.Add($"步骤 {step.Id} 的目标类别 '{condition.TargetObject}' 不在模型类别表中");
if (!float.IsFinite(condition.MinConfidence) || condition.MinConfidence is < 0 or > 1)
config.Warnings.Add($"步骤 {step.Id} 的物品置信度必须在 0 到 1 之间");
}
if (!supported.Contains(condition.Method))
{
config.Warnings.Add(

View File

@ -46,7 +46,7 @@ public partial class SopEngine
private static string? GetDecisionError(StepDef step)
{
if (string.IsNullOrWhiteSpace(step.ResolveCompletionCriteria())) return "请先填写 AI 完成条件";
if (!ConditionMethod.SupportsAiTrigger(step.Detection?.Method)) return "AI 确认需要手进入、离开区域或区域间移动触发";
if (!ConditionMethod.SupportsAiTrigger(step.Detection?.Method)) return "AI 确认需要有效的手部、计时或物品触发规则";
var options = step.AiConfirmation ?? new();
if (!VisionImageMode.IsValid(options) || !VisionEvidenceMode.IsValid(options) || !VisionEvidenceMode.IsCheckPolicyValid(options) || !double.IsFinite(options.MinConfidence) || options.MinConfidence is < 0 or > 1
|| options.RetryDelayMs < 0) return "AI 确认配置无效";
@ -69,7 +69,7 @@ public partial class SopEngine
_handImageRegion.Observe(step, frame, _regions);
if (_pendingDecision is { } pending)
{
if (!pending.Task.IsCompleted) return new() { Message = "手部动作已触发取图,等待 AI 确认(后续动作继续取图)…" };
if (!pending.Task.IsCompleted) return new() { Message = "触发规则已命中,等待 AI 确认(后续动作继续取图)…" };
_pendingDecision = null;
pending.Cancellation.Dispose();
var decision = RealtimeDecisionPolicy.AtPublication(pending.Request, pending.Task.GetAwaiter().GetResult());
@ -111,7 +111,7 @@ public partial class SopEngine
}
else trigger = ObserveTrigger(step, frame, _evaluator.EvaluateStep(step, frame), "current");
if (!trigger.IsMet) return trigger;
if (Environment.TickCount64 < _nextDecisionAt) return new() { Message = "等待 AI 重试间隔,手部条件满足后重新取图" };
if (Environment.TickCount64 < _nextDecisionAt) return new() { Message = "等待 AI 重试间隔,触发条件满足后重新取图" };
_nextDecisionAt = Environment.TickCount64 + Math.Max(500, options.RetryDelayMs);
captured = CaptureDecision(step, frame, _handImageRegion, captureJpeg, captureDecisionImage, out error);
if (captured is null) return new() { Message = error! };
@ -126,7 +126,7 @@ public partial class SopEngine
else if (_nextCaptureIndex <= _index) ArmFollowingStep(frame, step);
Log("info", $"步骤 {step.Id} 提交 AI 判定(原始帧 {captured.Request.FrameId},区域:{captured.Area}{(buffered ? ",使用连续操作缓存" : "")})");
DecisionSubmitted?.Invoke(captured.Request);
return new() { Message = "手部动作已触发取图,等待 AI 确认(后续动作继续取图)…" };
return new() { Message = "触发规则已命中,等待 AI 确认(后续动作继续取图)…" };
}
/// <summary>按实际送检模式裁剪编码并记录来源帧与时间;裁剪或编码失败时返回原因,不发送替代图像。</summary>
@ -172,7 +172,8 @@ public partial class SopEngine
&& condition.Region.Equals(previous.Region, StringComparison.OrdinalIgnoreCase)
&& DetectionHands.Normalize(condition.Hand) == DetectionHands.Normalize(previous.Hand);
_followingGate = new(evaluator, tracker) { RequireRelease = repeatedEntry };
if (!repeatedEntry && next.Detection is not null)
// 物品稳定帧从后续步骤开始监测后的新帧计数,避免沿用前一步触发帧。
if (!repeatedEntry && next.Detection is not null && !ConditionMethod.RequiresObjectDetection(next.Detection.Method))
ObserveTrigger(next, frame, evaluator.EvaluateStep(next, frame), "primed"); // 只登记轨迹,禁止同帧连过。
}

View File

@ -128,6 +128,13 @@ public partial class SopEngine
public bool RequiresHandDetection => State == EngineState.Running
&& (CurrentStep?.NeedsHandDetection() == true || StepAt(_nextCaptureIndex)?.NeedsHandDetection() == true);
/// <summary>运行时只有当前待触发步骤或已开始监测的后续步骤需要物品推理;同一帧的结果可供两者复用。</summary>
public bool RequiresObjectDetection => State == EngineState.Running
&& ((_pendingDecision is null || CurrentStep?.AiConfirmation?.CheckWindowMs > 0
|| CurrentStep?.AiConfirmation?.EvidenceMode == VisionEvidenceMode.Sequence)
&& ConditionMethod.RequiresObjectDetection(CurrentStep?.Detection?.Method)
|| _nextCaptureIndex > _index && ConditionMethod.RequiresObjectDetection(StepAt(_nextCaptureIndex)?.Detection?.Method));
/// <summary>配方(UI 显示步骤卡用)</summary>
public SopConfig Config => _config;

View File

@ -0,0 +1,66 @@
using SopHelper.Engine.Common;
using SopHelper.Engine.Sop;
/// <summary>验证检测需求、原图坐标、稳定帧以及 AI 送检之间的衔接。</summary>
internal static class ObjectZoneChecks
{
public static async Task RunAsync()
{
var config = SopConfigLoader.Parse("""
sop:
name: 物品触发测试
model: { path: yolo_models/parts.onnx, classes: [box] }
regions:
work: { x1: 0, y1: 0, x2: 100, y2: 100 }
steps:
- id: 1
completion_criteria: 检查盒中物料
detection: { method: object_in_zone, region: work, target_object: Box, min_confidence: 0.8, stable_frames: 2, tolerance: 0 }
""");
var saved = SopConfigLoader.Parse(SopConfigLoader.ToYaml(config));
Check(saved.Warnings.Count == 0 && saved.Sop.Model?.Classes.Single() == "box"
&& saved.Sop.Steps[0].Detection?.TargetObject == "Box", "配方往返保留模型、目标类别及触发参数");
var fake = new FakeDecision();
var engine = new SopEngine { VisionDecisionClient = fake };
engine.Load(saved);
Check(!engine.RequiresObjectDetection, "空闲时不请求 YOLO");
engine.Start();
Check(engine.RequiresObjectDetection && !engine.RequiresHandDetection, "物品触发仅请求 YOLO");
long frameId = 0;
void Send(float x, float confidence = .9f, string label = "box", bool detected = true)
{
engine.ProcessFrame(new FrameResult
{
FrameId = ++frameId,
Timestamp = DateTime.Now,
ObjectDetectionRan = detected,
Detections = [new Detection { Label = label, Confidence = confidence, Rect = new(x, 10, 20, 20) }],
}, () => [1, 2]);
}
// 边缘相交但中心在区域外、低置信度、不同类别及未推理的帧都会中断连续计数。
Send(10); Send(95); Send(10); Send(10, .79f); Send(10); Send(10, label: "other");
Send(10); Send(10, detected: false); Send(10);
Check(!fake.Called.Task.IsCompleted, "需要两个连续有效命中帧");
Send(10);
await fake.Called.Task.WaitAsync(TimeSpan.FromSeconds(2));
Check(fake.Request?.FrameId == frameId && engine.State == EngineState.Running
&& !engine.RequiresObjectDetection, "命中帧用于送检,单步等待 AI 时停止物品推理");
engine.Stop();
Check(!engine.RequiresObjectDetection, "停止后不请求 YOLO");
saved.Sop.Steps[0].Detection!.Method = ConditionMethod.TimeElapsed;
engine.Load(saved);
engine.Start();
Check(!engine.RequiresObjectDetection, "保留模型配置的计时配方不会请求 YOLO");
engine.Stop();
Console.WriteLine("PASS: YOLO 需求门控、物品区域、稳定帧、配方往返及 AI 送检");
}
private static void Check(bool ok, string message)
{
if (!ok) throw new Exception(message);
}
}

View File

@ -17,7 +17,9 @@ sop:
description: 把盒子放好
detection: { method: object_present, target_object: 盒子 }
""");
Check(!SopConfigLoader.ToYaml(retired).Contains("model:") && retired.Warnings.Any(w=>w.Contains("已移除或不支持")), "旧模型绑定必须忽略,旧物体规则提示改用手部规则");
Check(retired.Sop.Model?.Path == "old.onnx" && retired.Warnings.Any(w => w.Contains("已移除或不支持")),
"保留旧模型绑定,并继续提示不支持全图物品规则");
await ObjectZoneChecks.RunAsync();
var sample = SopConfigLoader.Load(Path.Combine("configs", "sop", "hand-ai.yaml"));
Check(sample.Warnings.Count == 0 && sample.Sop.Steps.All(s => s.AiConfirmation is not null), "示例配方必须有效且不依赖 YOLO");
var d3Sample = SopConfigLoader.Load(Path.Combine("configs", "sop", "d3-workflow.yaml"));