From d4650323c3cb2ddbff286221db1a10a5abcd01e9 Mon Sep 17 00:00:00 2001 From: tfarcraw <123211521@163.com> Date: Thu, 19 Nov 2026 02:26:43 +0800 Subject: [PATCH] =?UTF-8?q?=E6=8C=89=E8=A7=86=E8=A7=89=E5=B7=AE=E5=BC=82?= =?UTF-8?q?=E4=BF=9D=E7=95=99=E7=9E=AC=E6=80=81=E5=85=B3=E9=94=AE=E5=B8=A7?= =?UTF-8?q?=E5=B9=B6=E5=88=86=E7=A6=BB=E7=BC=93=E5=AD=98=E4=B8=8E=E9=80=81?= =?UTF-8?q?=E6=A3=80=E9=A2=84=E7=AE=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../VVMs/RecipeEditor/EditorNodes.cs | 9 ++-- .../VVMs/RecipeEditor/RecipeEditor.axaml | 5 +- .../Sop/ObservationEvidenceWindow.cs | 15 ++++-- .../Sop/SopEngine.ContinuousChecks.cs | 4 +- .../Sop/SopEngine.ObservationWindows.cs | 1 + .../Sop/VisionDecision.cs | 3 +- .../Sop/VisualEvidenceSampler.cs | 54 +++++++++++++++++++ tests/VideoFlowTest.Smoke/Program.cs | 5 +- tests/VisionDecision.Smoke/Program.cs | 1 + .../VisualEvidenceTests.cs | 27 ++++++++++ 10 files changed, 108 insertions(+), 16 deletions(-) create mode 100644 src/SopHelper.CrossPlatform.Engine/Sop/VisualEvidenceSampler.cs create mode 100644 tests/VisionDecision.Smoke/VisualEvidenceTests.cs diff --git a/src/SopHelper.Avalonia/VVMs/RecipeEditor/EditorNodes.cs b/src/SopHelper.Avalonia/VVMs/RecipeEditor/EditorNodes.cs index d7679c5..43e0c0b 100644 --- a/src/SopHelper.Avalonia/VVMs/RecipeEditor/EditorNodes.cs +++ b/src/SopHelper.Avalonia/VVMs/RecipeEditor/EditorNodes.cs @@ -428,7 +428,7 @@ public class RecipeNode : EditorNode EvidenceMode = step.AiConfirmation.EvidenceMode, ObservationPreRollMs = step.AiConfirmation.ObservationPreRollMs, ObservationMinMs = step.AiConfirmation.ObservationMinMs, ObservationMaxMs = step.AiConfirmation.ObservationMaxMs, ObservationSampleMs = step.AiConfirmation.ObservationSampleMs, - ObservationMaxFrames = step.AiConfirmation.ObservationMaxFrames, + ObservationMaxFrames = step.AiConfirmation.ObservationMaxFrames, ObservationRequestMaxFrames = step.AiConfirmation.ObservationRequestMaxFrames, ImageRegion = step.AiConfirmation.ImageRegion, ImageMode = step.AiConfirmation.ImageMode, HandPadding = step.AiConfirmation.HandPadding, HandMinSize = step.AiConfirmation.HandMinSize, HandMemoryMs = step.AiConfirmation.HandMemoryMs, @@ -496,7 +496,7 @@ public class RecipeNode : EditorNode CheckWindowMs = step.AiCheckWindowMs, MaxChecks = step.AiMaxChecks, CheckSettleMs = step.AiCheckSettleMs, EvidenceMode = step.AiEvidenceMode, ObservationPreRollMs = step.AiObservationPreRollMs, ObservationMinMs = step.AiObservationMinMs, ObservationMaxMs = step.AiObservationMaxMs, - ObservationSampleMs = step.AiObservationSampleMs, ObservationMaxFrames = step.AiObservationMaxFrames, + ObservationSampleMs = step.AiObservationSampleMs, ObservationMaxFrames = step.AiObservationMaxFrames, ObservationRequestMaxFrames = step.AiObservationRequestMaxFrames, ImageRegion = step.AiImageRegion, ImageMode = step.AiImageMode, HandPadding = step.AiHandPadding, HandMinSize = step.AiHandMinSize, HandMemoryMs = step.AiHandMemoryMs, @@ -787,7 +787,7 @@ public class StepNode : EditorNode public int AiCheckSettleMs { get => _aiCheckSettleMs; set => SetProperty(ref _aiCheckSettleMs, value); } private string _aiEvidenceMode = VisionEvidenceMode.SingleFrame; private int _aiObservationPreRollMs = 1000, _aiObservationMinMs = 2400, _aiObservationMaxMs = 10000, - _aiObservationSampleMs = 400, _aiObservationMaxFrames = 24; + _aiObservationSampleMs = 400, _aiObservationMaxFrames = 24, _aiObservationRequestMaxFrames = 12; public IReadOnlyList AiEvidenceModes { get; } = [VisionEvidenceMode.SingleFrame, VisionEvidenceMode.Sequence]; public string AiEvidenceMode { get => _aiEvidenceMode; set { if (SetProperty(ref _aiEvidenceMode, value)) RaisePropertyChanged(nameof(UsesSequenceEvidence)); } } public bool UsesSequenceEvidence => AiEvidenceMode == VisionEvidenceMode.Sequence; @@ -795,6 +795,7 @@ public class StepNode : EditorNode public int AiObservationMinMs { get => _aiObservationMinMs; set => SetProperty(ref _aiObservationMinMs, value); } public int AiObservationMaxMs { get => _aiObservationMaxMs; set => SetProperty(ref _aiObservationMaxMs, value); } public int AiObservationSampleMs { get => _aiObservationSampleMs; set => SetProperty(ref _aiObservationSampleMs, value); } + 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 int _aiHandPadding = 160, _aiHandMinSize = 320, _aiHandMemoryMs = 3000; @@ -825,7 +826,7 @@ public class StepNode : EditorNode AiCheckWindowMs = value.CheckWindowMs; AiMaxChecks = value.MaxChecks; AiCheckSettleMs = value.CheckSettleMs; AiEvidenceMode = value.EvidenceMode; AiObservationPreRollMs = value.ObservationPreRollMs; AiObservationMinMs = value.ObservationMinMs; AiObservationMaxMs = value.ObservationMaxMs; - AiObservationSampleMs = value.ObservationSampleMs; AiObservationMaxFrames = value.ObservationMaxFrames; + AiObservationSampleMs = value.ObservationSampleMs; AiObservationMaxFrames = value.ObservationMaxFrames; AiObservationRequestMaxFrames = value.ObservationRequestMaxFrames; AiImageRegion = value.ImageRegion; AiImageMode = VisionImageMode.Resolve(value); AiHandPadding = value.HandPadding; AiHandMinSize = value.HandMinSize; AiHandMemoryMs = value.HandMemoryMs; diff --git a/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml b/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml index cf2b8cc..c30498b 100644 --- a/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml +++ b/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml @@ -165,12 +165,13 @@ - + - + + diff --git a/src/SopHelper.CrossPlatform.Engine/Sop/ObservationEvidenceWindow.cs b/src/SopHelper.CrossPlatform.Engine/Sop/ObservationEvidenceWindow.cs index 16cabd6..1a5778c 100644 --- a/src/SopHelper.CrossPlatform.Engine/Sop/ObservationEvidenceWindow.cs +++ b/src/SopHelper.CrossPlatform.Engine/Sop/ObservationEvidenceWindow.cs @@ -4,6 +4,7 @@ namespace SopHelper.Engine.Sop; public sealed class ObservationEvidenceWindow(AiConfirmation options) { private readonly List _frames = []; + private readonly Dictionary _signatures = []; private double? _opened, _lastSample; private long _lastId = -1; public int Version { get; private set; } @@ -19,7 +20,7 @@ public sealed class ObservationEvidenceWindow(AiConfirmation options) { if (Opened) return; _opened = seconds; - _frames.RemoveAll(f => Time(f) < seconds - options.ObservationPreRollMs / 1000d); + TrimBefore(seconds - options.ObservationPreRollMs / 1000d); } public bool WantsFrame(long id, double seconds) => !Expired && Error is null && id != _lastId && (_lastSample is null || seconds - _lastSample >= options.ObservationSampleMs / 1000d); @@ -31,17 +32,21 @@ public sealed class ObservationEvidenceWindow(AiConfirmation options) if (!WantsFrame(frame.FrameId, seconds)) return; _lastSample = seconds; _lastId = frame.FrameId; _frames.Add(frame); Version++; - if (!Opened) _frames.RemoveAll(f => Time(f) < seconds - options.ObservationPreRollMs / 1000d); + if (!Opened) TrimBefore(seconds - options.ObservationPreRollMs / 1000d); while (_frames.Count > options.ObservationMaxFrames) { - // 保留起始和最新画面,压缩最密集的内部时间段,避免只留下尾部而丢失过程起点。 - var remove = Enumerable.Range(1, _frames.Count - 2) - .MinBy(i => Time(_frames[i + 1]) - Time(_frames[i - 1])); + var remove = VisualEvidenceSampler.RemovalIndex(_frames, _signatures); + _signatures.Remove(_frames[remove].FrameId); _frames.RemoveAt(remove); } if (_frames.Sum(f => f.Jpeg.LongLength) > 4 * 1024 * 1024) Error = "观察图片超过预算,未接受该段证据"; Advance(seconds); } + private void TrimBefore(double seconds) => _frames.RemoveAll(f => + { + if (Time(f) >= seconds) return false; + _signatures.Remove(f.FrameId); return true; + }); public void Advance(double seconds) { if (_opened is not { } opened) return; diff --git a/src/SopHelper.CrossPlatform.Engine/Sop/SopEngine.ContinuousChecks.cs b/src/SopHelper.CrossPlatform.Engine/Sop/SopEngine.ContinuousChecks.cs index 9e3c5c2..634099d 100644 --- a/src/SopHelper.CrossPlatform.Engine/Sop/SopEngine.ContinuousChecks.cs +++ b/src/SopHelper.CrossPlatform.Engine/Sop/SopEngine.ContinuousChecks.cs @@ -169,8 +169,6 @@ public partial class SopEngine var firstWait = Math.Min(interval, Math.Max(500, options.CheckSettleMs)); var timeToCheck = state.Attempts == 0 ? quiet || sinceRequest >= firstWait : sinceRequest >= interval; var prior = PriorCompletedEvidenceTime(); - if (options.EvidenceMode == VisionEvidenceMode.SingleFrame && state.Attempts > 0) - prior = Math.Max(prior, state.LatestSeconds - options.CheckWindowMs / 1000d); var frames = state.Window.Frames.Where(f => ObservationEvidenceWindow.Time(f) >= prior).ToArray(); if (!timeToCheck) return new() { Message = $"等待下一次检查时机(已送检 {state.Attempts}/{options.MaxChecks} 次)" }; if (options.EvidenceMode == VisionEvidenceMode.SingleFrame) @@ -197,6 +195,8 @@ public partial class SopEngine || options.EvidenceMode == VisionEvidenceMode.Sequence && state.Window.Version <= state.SentVersion || options.EvidenceMode == VisionEvidenceMode.Sequence && !processReady) return new() { Message = $"窗口内观察,优先在手部停稳或离开后检查(已送检 {state.Attempts}/{options.MaxChecks} 次)" }; + if (options.EvidenceMode == VisionEvidenceMode.Sequence) + frames = VisualEvidenceSampler.Select(frames, options.ObservationRequestMaxFrames); var last = frames[^1]; var request = new VisionDecisionRequest(_config.Sop.Name, step.Id, step.Name, step.Description, step.Description, last.FrameId, last.CapturedAt, last.Jpeg, options.EvidenceMode, diff --git a/src/SopHelper.CrossPlatform.Engine/Sop/SopEngine.ObservationWindows.cs b/src/SopHelper.CrossPlatform.Engine/Sop/SopEngine.ObservationWindows.cs index cc4e76e..7f5b298 100644 --- a/src/SopHelper.CrossPlatform.Engine/Sop/SopEngine.ObservationWindows.cs +++ b/src/SopHelper.CrossPlatform.Engine/Sop/SopEngine.ObservationWindows.cs @@ -109,6 +109,7 @@ public partial class SopEngine || ObservationEvidenceWindow.Time(f) >= prior).ToArray(); state.Window.LastSentVersion = state.Window.Version; if (frames.Length < 3) return new() { Message = "证据不足:前序完成后没有三张有效过程画面,未放行" }; + frames = VisualEvidenceSampler.Select(frames, step.AiConfirmation!.ObservationRequestMaxFrames); var last = frames[^1]; var request = new VisionDecisionRequest(_config.Sop.Name, step.Id, step.Name, step.Description, step.Description, last.FrameId, last.CapturedAt, last.Jpeg, VisionEvidenceMode.Sequence, frames, last.SourceSeconds); diff --git a/src/SopHelper.CrossPlatform.Engine/Sop/VisionDecision.cs b/src/SopHelper.CrossPlatform.Engine/Sop/VisionDecision.cs index eda3a58..f889417 100644 --- a/src/SopHelper.CrossPlatform.Engine/Sop/VisionDecision.cs +++ b/src/SopHelper.CrossPlatform.Engine/Sop/VisionDecision.cs @@ -16,6 +16,7 @@ public sealed class AiConfirmation public int ObservationMaxMs { get; set; } = 10000; public int ObservationSampleMs { get; set; } = 400; public int ObservationMaxFrames { get; set; } = 24; + public int ObservationRequestMaxFrames { get; set; } = 12; /// full_frame / fixed_region / hand;空值按旧配方 image_region 推断。 public string ImageMode { get; set; } = ""; /// 固定送检区域名;仅未指定 ImageMode 的旧配方按空值推断整帧。 @@ -40,7 +41,7 @@ public static class VisionEvidenceMode private static bool IsObservationValid(AiConfirmation options) => options.ObservationPreRollMs is >= 0 and <= 5000 && options.ObservationMinMs is >= 200 and <= 30000 && options.ObservationMaxMs >= options.ObservationMinMs && options.ObservationMaxMs <= 60000 && options.ObservationSampleMs is >= 100 and <= 2000 - && options.ObservationMaxFrames is >= 3 and <= 32; + && options.ObservationMaxFrames is >= 3 and <= 32 && options.ObservationRequestMaxFrames is >= 3 and <= 32; } public enum VisionDecisionStatus { Unspecified, Completed, NotCompleted, Insufficient, Unsupported } diff --git a/src/SopHelper.CrossPlatform.Engine/Sop/VisualEvidenceSampler.cs b/src/SopHelper.CrossPlatform.Engine/Sop/VisualEvidenceSampler.cs new file mode 100644 index 0000000..6e37499 --- /dev/null +++ b/src/SopHelper.CrossPlatform.Engine/Sop/VisualEvidenceSampler.cs @@ -0,0 +1,54 @@ +using OpenCvSharp; + +namespace SopHelper.Engine.Sop; + +/// 只压缩冗余证据,不判断工序完成;保留首尾及短暂出现的不同视觉状态。 +public static class VisualEvidenceSampler +{ + public static VisionEvidenceFrame[] Select(IReadOnlyList source, int maximum) + { + if (maximum < 3) throw new ArgumentOutOfRangeException(nameof(maximum)); + var frames = source.ToList(); var signatures = new Dictionary(); + while (frames.Count > maximum) + { + var index = RemovalIndex(frames, signatures); + signatures.Remove(frames[index].FrameId); frames.RemoveAt(index); + } + return frames.ToArray(); + } + internal static int RemovalIndex(IReadOnlyList frames, Dictionary signatures) + { + foreach (var frame in frames) + if (!signatures.ContainsKey(frame.FrameId)) signatures[frame.FrameId] = Describe(frame.Jpeg); + var visual = frames.All(f => signatures[f.FrameId] is not null); + return Enumerable.Range(1, frames.Count - 2).MinBy(i => + { + var cost = visual ? Difference(signatures[frames[i - 1].FrameId]!, signatures[frames[i].FrameId]!) + + Difference(signatures[frames[i].FrameId]!, signatures[frames[i + 1].FrameId]!) + - Difference(signatures[frames[i - 1].FrameId]!, signatures[frames[i + 1].FrameId]!) : 0; + return (cost, ObservationEvidenceWindow.Time(frames[i + 1]) - ObservationEvidenceWindow.Time(frames[i - 1])); + }); + } + private static byte[]? Describe(byte[] jpeg) + { + if (jpeg.Length < 16) return null; + try + { + using var image = Cv2.ImDecode(jpeg, ImreadModes.Grayscale); + if (image.Empty()) return null; + using var small = new Mat(); + Cv2.Resize(image, small, new Size(32, 32), 0, 0, InterpolationFlags.Area); + var signature = new byte[1024]; + System.Runtime.InteropServices.Marshal.Copy(small.Data, signature, 0, signature.Length); + return signature; + } + catch (Exception error) when (error is OpenCVException or ArgumentException or DllNotFoundException or TypeInitializationException or EntryPointNotFoundException) + { return null; } // 特征不可用时退回有界时间采样,不影响判定能力或伪造证据。 + } + private static double Difference(byte[] first, byte[] second) + { + var sum = 0; + for (var i = 0; i < first.Length; i++) sum += Math.Abs(first[i] - second[i]); + return (double)sum / first.Length; + } +} diff --git a/tests/VideoFlowTest.Smoke/Program.cs b/tests/VideoFlowTest.Smoke/Program.cs index 0a86f80..50eac74 100644 --- a/tests/VideoFlowTest.Smoke/Program.cs +++ b/tests/VideoFlowTest.Smoke/Program.cs @@ -51,13 +51,14 @@ internal static class Program "新建步骤默认使用10秒限时复检,最多3次"); var config = new SopConfig(); config.Sop.Steps.Add(new() { Id = 1, Description = "状态变化", AiConfirmation = new() - { EvidenceMode = VisionEvidenceMode.Sequence, ObservationMinMs = 1800, ObservationMaxFrames = 13, ObservationSampleMs = 300, + { EvidenceMode = VisionEvidenceMode.Sequence, ObservationMinMs = 1800, ObservationMaxFrames = 13, ObservationRequestMaxFrames = 7, ObservationSampleMs = 300, CheckWindowMs = 7000, MaxChecks = 4, CheckSettleMs = 450 } }); var editor = RecipeNode.From(config, "试验.yaml", false); Check(editor.Steps[0].UsesSequenceEvidence, "编辑器须识别过程时序模式"); var restored = SopConfigLoader.Parse(SopConfigLoader.ToYaml(editor.ToConfig())).Sop.Steps[0].AiConfirmation!; Check(restored.EvidenceMode == VisionEvidenceMode.Sequence && restored.ObservationMinMs == 1800 - && restored.ObservationMaxFrames == 13 && restored.ObservationSampleMs == 300, "编辑保存不得丢失时序模式与窗口参数"); + && restored.ObservationMaxFrames == 13 && restored.ObservationRequestMaxFrames == 7 && restored.ObservationSampleMs == 300, + "编辑保存不得丢失时序模式、缓存容量与单次请求预算"); Check(editor.Steps[0].AiContinueAfterWindow && restored.CheckWindowMs == 7000 && restored.MaxChecks == 4 && restored.CheckSettleMs == 450, "编辑保存须保留连续操作限时复检参数"); editor.Steps[0].AiContinueAfterWindow = false; diff --git a/tests/VisionDecision.Smoke/Program.cs b/tests/VisionDecision.Smoke/Program.cs index a92deb1..dc707f8 100644 --- a/tests/VisionDecision.Smoke/Program.cs +++ b/tests/VisionDecision.Smoke/Program.cs @@ -152,6 +152,7 @@ await BufferedEvidenceChecks.RunAsync(); await ObservationWindowChecks.RunAsync(); await ContinuousCheckTests.RunAsync(); await SequenceProtocolTests.RunAsync(); +VisualEvidenceTests.Run(); HandContactChecks.Run(); await TriggerImageChecks.RunAsync(); await DynamicRegionChecks.RunAsync(); diff --git a/tests/VisionDecision.Smoke/VisualEvidenceTests.cs b/tests/VisionDecision.Smoke/VisualEvidenceTests.cs new file mode 100644 index 0000000..8e0ed3e --- /dev/null +++ b/tests/VisionDecision.Smoke/VisualEvidenceTests.cs @@ -0,0 +1,27 @@ +using OpenCvSharp; +using SopHelper.Engine.Sop; + +internal static class VisualEvidenceTests +{ + public static void Run() + { + using var dark = new Mat(32, 32, MatType.CV_8UC3, Scalar.Black); + using var bright = new Mat(32, 32, MatType.CV_8UC3, Scalar.White); + var normal = VisionDecisionImage.Encode(dark, null); var transient = VisionDecisionImage.Encode(bright, null); + var frames = Enumerable.Range(0, 4).Select(i => new VisionEvidenceFrame(i, DateTime.UnixEpoch.AddSeconds(i * .11), + i == 1 ? transient : normal, i * .11)).ToArray(); + var compact = VisualEvidenceSampler.Select(frames, 3); + if (!compact.Select(f => f.FrameId).SequenceEqual(new long[] { 0, 1, 3 })) + throw new Exception("重复背景不能挤掉短暂出现的不同视觉状态,且须保留真实首尾帧"); + var window = new ObservationEvidenceWindow(new() { ObservationMaxFrames = 3, ObservationSampleMs = 100 }); + window.Open(0); + foreach (var frame in frames) window.Add(frame); + if (!window.Frames.Select(f => f.FrameId).SequenceEqual(new long[] { 0, 1, 3 })) + throw new Exception("缓存压缩与请求采样均须保护瞬态关键画面"); + var many = Enumerable.Range(0, 12).Select(i => new VisionEvidenceFrame(i, DateTime.UnixEpoch.AddSeconds(i), normal, i)).ToArray(); + var snapshot = VisualEvidenceSampler.Select(many, 4); + if (snapshot.Length != 4 || snapshot[0].FrameId != 0 || snapshot[^1].FrameId != 11 || many.Length != 12) + throw new Exception("请求图片预算须独立于缓存容量,并保持时间顺序及快照隔离"); + Console.WriteLine("PASS: 视觉冗余压缩、瞬态画面保护、首尾与顺序、独立请求图片预算"); + } +}