按视觉差异保留瞬态关键帧并分离缓存与送检预算
This commit is contained in:
parent
8638f8a9aa
commit
d4650323c3
@ -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<string> 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;
|
||||
|
||||
@ -165,12 +165,13 @@
|
||||
</ComboBox>
|
||||
<StackPanel IsVisible="{Binding UsesSequenceEvidence}" Spacing="6">
|
||||
<TextBlock Text="手部动作打开观察窗口;需要支持多图的模型,证据不足时不放行。" TextWrapping="Wrap" />
|
||||
<Grid ColumnDefinitions="*,*" RowDefinitions="Auto,Auto,Auto,Auto,Auto">
|
||||
<Grid ColumnDefinitions="*,*" RowDefinitions="Auto,Auto,Auto,Auto,Auto,Auto">
|
||||
<TextBlock Text="触发前保留(毫秒)" /><NumericUpDown Grid.Column="1" Value="{Binding AiObservationPreRollMs, Mode=TwoWay}" Minimum="0" Maximum="5000" Increment="100" />
|
||||
<TextBlock Grid.Row="1" Text="首次观察(毫秒)" /><NumericUpDown Grid.Row="1" Grid.Column="1" Value="{Binding AiObservationMinMs, Mode=TwoWay}" Minimum="200" Maximum="30000" Increment="200" />
|
||||
<TextBlock Grid.Row="2" Text="最长观察(毫秒)" /><NumericUpDown Grid.Row="2" Grid.Column="1" Value="{Binding AiObservationMaxMs, Mode=TwoWay}" Minimum="200" Maximum="60000" Increment="1000" />
|
||||
<TextBlock Grid.Row="3" Text="采样间隔(毫秒)" /><NumericUpDown Grid.Row="3" Grid.Column="1" Value="{Binding AiObservationSampleMs, Mode=TwoWay}" Minimum="100" Maximum="2000" Increment="100" />
|
||||
<TextBlock Grid.Row="4" Text="最多画面数" /><NumericUpDown Grid.Row="4" Grid.Column="1" Value="{Binding AiObservationMaxFrames, Mode=TwoWay}" Minimum="3" Maximum="32" />
|
||||
<TextBlock Grid.Row="4" Text="缓存画面数" /><NumericUpDown Grid.Row="4" Grid.Column="1" Value="{Binding AiObservationMaxFrames, Mode=TwoWay}" Minimum="3" Maximum="32" />
|
||||
<TextBlock Grid.Row="5" Text="每次送检画面数" /><NumericUpDown Grid.Row="5" Grid.Column="1" Value="{Binding AiObservationRequestMaxFrames, Mode=TwoWay}" Minimum="3" Maximum="32" />
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
<TextBlock Text="送检方式" />
|
||||
|
||||
@ -4,6 +4,7 @@ namespace SopHelper.Engine.Sop;
|
||||
public sealed class ObservationEvidenceWindow(AiConfirmation options)
|
||||
{
|
||||
private readonly List<VisionEvidenceFrame> _frames = [];
|
||||
private readonly Dictionary<long, byte[]?> _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;
|
||||
|
||||
@ -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,
|
||||
|
||||
@ -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);
|
||||
|
||||
@ -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;
|
||||
/// <summary>full_frame / fixed_region / hand;空值按旧配方 image_region 推断。</summary>
|
||||
public string ImageMode { get; set; } = "";
|
||||
/// <summary>固定送检区域名;仅未指定 ImageMode 的旧配方按空值推断整帧。</summary>
|
||||
@ -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 }
|
||||
|
||||
@ -0,0 +1,54 @@
|
||||
using OpenCvSharp;
|
||||
|
||||
namespace SopHelper.Engine.Sop;
|
||||
|
||||
/// <summary>只压缩冗余证据,不判断工序完成;保留首尾及短暂出现的不同视觉状态。</summary>
|
||||
public static class VisualEvidenceSampler
|
||||
{
|
||||
public static VisionEvidenceFrame[] Select(IReadOnlyList<VisionEvidenceFrame> source, int maximum)
|
||||
{
|
||||
if (maximum < 3) throw new ArgumentOutOfRangeException(nameof(maximum));
|
||||
var frames = source.ToList(); var signatures = new Dictionary<long, byte[]?>();
|
||||
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<VisionEvidenceFrame> frames, Dictionary<long, byte[]?> 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;
|
||||
}
|
||||
}
|
||||
@ -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;
|
||||
|
||||
@ -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();
|
||||
|
||||
27
tests/VisionDecision.Smoke/VisualEvidenceTests.cs
Normal file
27
tests/VisionDecision.Smoke/VisualEvidenceTests.cs
Normal file
@ -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: 视觉冗余压缩、瞬态画面保护、首尾与顺序、独立请求图片预算");
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user