diff --git a/src/SopHelper.Avalonia/VVMs/SopPage/SopPage.axaml b/src/SopHelper.Avalonia/VVMs/SopPage/SopPage.axaml index 51ed2f3..3af654d 100644 --- a/src/SopHelper.Avalonia/VVMs/SopPage/SopPage.axaml +++ b/src/SopHelper.Avalonia/VVMs/SopPage/SopPage.axaml @@ -14,6 +14,10 @@ + + + + @@ -150,5 +154,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs b/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs index 43934db..c8d33e8 100644 --- a/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs +++ b/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs @@ -56,6 +56,7 @@ public class SopPageViewModel : ViewModelBase /// 最近一次处理过的帧(快照按钮存盘用,由推理线程写入) private FrameResult? _lastFrame; + private Mat? _judgementFrame; private FrameResult? _handResult; private WriteableBitmap? _bitmap; private long _frameCount; @@ -104,14 +105,15 @@ public class SopPageViewModel : ViewModelBase }); _camera.Error += message => _dispatcher.BeginInvoke(() => Log("warn", message)); - _pipeline.ResultArrived += result => _dispatcher.BeginInvoke(() => OnResult(result)); + _pipeline.ResultFrameArrived += OnResultFrame; _pipeline.InferenceWarning += message => _dispatcher.BeginInvoke(() => Log("warn", message)); // 帧 Mat 只在采集线程的事件存活期内有效(事件返回即被释放),必须当场克隆 _camera.FrameArrived += OnCameraFrame; _engine.LogArrived += entry => _dispatcher.BeginInvoke(() => AppendLog(entry)); _engine.ViolationRaised += violation => _dispatcher.BeginInvoke(() => AppendViolation(violation)); - _engine.StepSnapshotChanged += snapshot => _dispatcher.BeginInvoke(() => UpdateCard(snapshot)); + _engine.StepSnapshotChanged += OnStepSnapshot; + _engine.RoundStarted += OnRoundStarted; _engine.Completed += () => _dispatcher.BeginInvoke(() => StatusText = "本轮完成"); LoadRecipes(); @@ -391,6 +393,10 @@ public class SopPageViewModel : ViewModelBase public override void Destroy() { _camera.FrameArrived -= OnCameraFrame; + _pipeline.ResultFrameArrived -= OnResultFrame; + _engine.StepSnapshotChanged -= OnStepSnapshot; + _engine.RoundStarted -= OnRoundStarted; + ClearProcessImages(); lock (_frameLock) { @@ -502,6 +508,7 @@ public class SopPageViewModel : ViewModelBase { _pipeline.LoadModels(new PipelineOptions()); _engine.Load(new SopConfig()); + ClearProcessImages(); StepCards.Clear(); Rois.Clear(); HandResult = null; _lastFrame = null; ActiveRecipe = "未应用配方"; RaisePropertyChanged(nameof(InferenceBackendText)); @@ -734,6 +741,7 @@ public class SopPageViewModel : ViewModelBase ActiveRecipe = SelectedRecipe; Log("info", $"推理设备:手部={_pipeline.HandBackend},YOLO={_pipeline.YoloBackend}"); + ClearProcessImages(); StepCards.Clear(); Rois.Clear(); @@ -777,6 +785,38 @@ public class SopPageViewModel : ViewModelBase return File.Exists(path) ? path : null; } + private void OnResultFrame(FrameResult result, Mat frame) + { + var owned = frame.Clone(); + _dispatcher.BeginInvoke(() => + { + using (owned) + { + _judgementFrame = owned; + try { OnResult(result); } + finally { _judgementFrame = null; } + } + }); + } + + private void OnRoundStarted() + { + if (Avalonia.Threading.Dispatcher.UIThread.CheckAccess()) ClearProcessImages(); + else _dispatcher.BeginInvoke(() => { if (!_destroyed) ClearProcessImages(); }); + } + + private void ClearProcessImages() + { + foreach (var card in StepCards) card.CompletionImage = null; + } + + private void OnStepSnapshot(StepSnapshot snapshot) + { + // ProcessFrame 在 UI 线程运行,必须在对应判定帧释放前定格。 + if (Avalonia.Threading.Dispatcher.UIThread.CheckAccess()) UpdateCard(snapshot); + else _dispatcher.BeginInvoke(() => { if (!_destroyed) UpdateCard(snapshot); }); + } + private void OnResult(FrameResult result) { if (_destroyed || !IsRunning) return; @@ -849,6 +889,9 @@ public class SopPageViewModel : ViewModelBase card.IsCurrent = snapshot.IsCurrent; card.IsMet = snapshot.IsMet; card.Message = snapshot.Message; + if (snapshot.IsMet && card.CompletionImage is null && _judgementFrame is { } frame) + card.CompletionImage = BitmapSource.Create(frame.Width, frame.Height, 96, 96, + PixelFormats.Bgr24, null, frame.Data, checked((int)(frame.Step() * frame.Height)), checked((int)frame.Step())); } private void AppendViolation(ViolationEvent violation) @@ -884,6 +927,25 @@ public class SopPageViewModel : ViewModelBase /// public class StepCard : ViewModelBase { + private BitmapSource? _completionImage; + + /// 步骤完成时的独立帧,不随实时画面更新。 + public BitmapSource? CompletionImage + { + get => _completionImage; + set + { + var previous = _completionImage; + if (!SetProperty(ref _completionImage, value)) return; + RaisePropertyChanged(nameof(HasCompletionImage)); + RaisePropertyChanged(nameof(IsWaitingForImage)); + previous?.Dispose(); + } + } + + public bool HasCompletionImage => CompletionImage is not null; + public bool IsWaitingForImage => !HasCompletionImage; + private bool _isCurrent; private bool _isMet; private string _message = ""; diff --git a/src/SopHelper.CrossPlatform.Engine/Pipeline/DetectionPipeline.cs b/src/SopHelper.CrossPlatform.Engine/Pipeline/DetectionPipeline.cs index aaeb282..96ac503 100644 --- a/src/SopHelper.CrossPlatform.Engine/Pipeline/DetectionPipeline.cs +++ b/src/SopHelper.CrossPlatform.Engine/Pipeline/DetectionPipeline.cs @@ -74,6 +74,9 @@ public class DetectionPipeline : IDisposable /// 结果帧(在管线线程上触发) public event Action? ResultArrived; + + /// 结果与对应原始帧;Mat 仅在回调期间有效,异步使用必须克隆。 + public event Action? ResultFrameArrived; public event Action? InferenceWarning; /// @@ -267,7 +270,11 @@ public class DetectionPipeline : IDisposable AvgInferenceMs = AvgInferenceMs <= 0 ? ms : AvgInferenceMs * 0.9 + ms * 0.1; ResultFps = AvgInferenceMs <= 0 ? 0 : 1000.0 / AvgInferenceMs; - if (!token.IsCancellationRequested) ResultArrived?.Invoke(result); + if (!token.IsCancellationRequested) + { + ResultArrived?.Invoke(result); + ResultFrameArrived?.Invoke(result, frame.Bgr); + } } private void ReportInferenceWarning(string message) diff --git a/src/SopHelper.CrossPlatform.Engine/Sop/SopEngine.cs b/src/SopHelper.CrossPlatform.Engine/Sop/SopEngine.cs index d8bc7f7..2cb06a2 100644 --- a/src/SopHelper.CrossPlatform.Engine/Sop/SopEngine.cs +++ b/src/SopHelper.CrossPlatform.Engine/Sop/SopEngine.cs @@ -72,6 +72,9 @@ public class SopEngine /// 整轮完成 public event Action? Completed; + /// 开始或复位到新一轮。 + public event Action? RoundStarted; + /// /// 加载配方(区域 → 像素矩形;校验提醒原样转出去) /// @@ -115,6 +118,7 @@ public class SopEngine _evaluator.NoteStepEntered(_ordered[0].Id, _stepEnteredAt); State = EngineState.Running; + RoundStarted?.Invoke(); Log("info", $"开始运行:{_config.Sop.Name}({_ordered.Count} 步)"); ClearStepStates(); NotifyCurrent(); @@ -133,6 +137,7 @@ public class SopEngine if (StepAt(0) is StepDef first) _evaluator.NoteStepEntered(first.Id, _stepEnteredAt); State = EngineState.Running; + RoundStarted?.Invoke(); Log("info", "已复位"); ClearStepStates(); NotifyCurrent(); diff --git a/tests/Avalonia.Smoke/Program.cs b/tests/Avalonia.Smoke/Program.cs index 5ac62c6..e4b964c 100644 --- a/tests/Avalonia.Smoke/Program.cs +++ b/tests/Avalonia.Smoke/Program.cs @@ -24,10 +24,12 @@ using Avalonia.Input; internal static class Smoke { private static int _exit=1; + private static bool _processImagesOnly; private static readonly FakeCamera Camera=new(); [STAThread] - public static int Main() + public static int Main(string[] args) { + _processImagesOnly=args.Contains("--process-images-only"); var previousRoot=Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT"); var dataRoot=Path.Combine(Path.GetTempPath(),"sophelper-layout-smoke-"+Guid.NewGuid().ToString("N")); Directory.CreateDirectory(dataRoot); @@ -112,6 +114,8 @@ internal static class Smoke Save(window,"sop"); sop.StartStopCommand.Execute();for(var i=0;i<100&&sop.IsRunning;i++)await Task.Delay(20); Check(!sop.IsRunning&&!Camera.IsConnected,"Stop command releases acquisition"); + await CheckProcessImages(app,sop,window); + if(_processImagesOnly){_exit=0;return;} navigation.SelectedIndex=1;await Task.Delay(80); Check(settings.GetVisualDescendants().Where(c=>c is ComboBox or Slider).Cast().All(c=>c.IsEnabled),"Runtime settings become editable after stopping"); await CheckRecipeDeletion(lifetime,settings,sop); @@ -532,7 +536,7 @@ internal static class Smoke private static async Task CheckMovingPreview(SopPageViewModel sop,Window window) { var image=window.GetVisualDescendants().OfType().Single() - .GetVisualDescendants().OfType().Single(); + .GetVisualDescendants().OfType().Single(i=>ReferenceEquals(i.Source,sop.Frame)); var changes=0; System.ComponentModel.PropertyChangedEventHandler onChanged=(_,e)=>{if(e.PropertyName==nameof(sop.Frame))changes++;}; sop.PropertyChanged+=onChanged; @@ -561,6 +565,49 @@ internal static class Smoke } finally{sop.PropertyChanged-=onChanged;} } + private static async Task CheckProcessImages(App app,SopPageViewModel sop,Window window) + { + var engine=app.Container.Resolve(); + var config=new SopHelper.Engine.Sop.SopConfig(); + config.Sop.Settings.AutoResetOnComplete=false; + config.Sop.Settings.StableFrames=1; + for(var id=1;id<=2;id++)config.Sop.Steps.Add(new() + { + Id=id,Name="过程图测试"+id, + Detection=new(){Method="time_elapsed",DurationMs=1,StableFrames=1} + }); + engine.Load(config); + sop.StepCards.Clear(); + foreach(var step in config.Sop.Steps)sop.StepCards.Add(new(){StepId=step.Id,Name=step.Name}); + sop.IsRunning=true;engine.Start(); + var receive=typeof(SopPageViewModel).GetMethod("OnResultFrame",System.Reflection.BindingFlags.NonPublic|System.Reflection.BindingFlags.Instance)!; + try + { + Check(sop.StepCards.All(c=>c.IsWaitingForImage),"Every step starts with an empty process image slot"); + for(var id=1;id<=2;id++) + { + await Task.Delay(20); + using(var frame=new Mat(48,64,MatType.CV_8UC3,new Scalar(id*30,60,90))) + receive.Invoke(sop,[new SopHelper.Engine.Common.FrameResult {FrameId=id,Size=(64,48)},frame]); + await Task.Delay(50); + Check(sop.StepCards[id-1].HasCompletionImage,"Completed step receives its own image"); + if(id==1)Check(sop.StepCards[1].IsWaitingForImage,"Future step remains empty"); + } + Check(engine.State==SopHelper.Engine.Sop.EngineState.Completed&&sop.StepCards.All(c=>c.HasCompletionImage),"Round completion retains every process image"); + for(var id=1;id<=2;id++) + { + var path=Path.Combine(Output,"process-step-"+id+".png");sop.StepCards[id-1].CompletionImage!.Save(path); + using var decoded=Cv2.ImRead(path); + Check(decoded.At(0,0)==new Vec3b((byte)(id*30),60,90),"Process image preserves the exact judged frame after source disposal"); + } + Save(window,"process-images"); + var panel=window.GetVisualDescendants().OfType().Single(b=>b.Name=="ProcessImagesPanel"); + Check(panel.Bounds.Height>100&&panel.GetVisualDescendants().OfType().Count()==2,"Bottom panel renders one image card per step"); + engine.Reset(); + Check(sop.StepCards.All(c=>c.IsWaitingForImage),"Reset clears process images for the next round"); + } + finally{sop.IsRunning=false;sop.ApplyRecipeCommand.Execute();} + } private static void Save(Window window,string name) { window.UpdateLayout(); diff --git a/tests/Pipeline.Smoke/Program.cs b/tests/Pipeline.Smoke/Program.cs index 6c6e2c3..106e858 100644 --- a/tests/Pipeline.Smoke/Program.cs +++ b/tests/Pipeline.Smoke/Program.cs @@ -6,6 +6,13 @@ using SopHelper.Engine.Pipeline; using var camera = new TestCamera(); using var pipeline = new DetectionPipeline(camera); var results = new ConcurrentQueue(); +var imageResults = new ConcurrentQueue(); +pipeline.ResultFrameArrived += (result, image) => +{ + if (image.Empty() || result.Size != (image.Width, image.Height)) + throw new Exception("Result image is invalid or does not match the inference dimensions"); + imageResults.Enqueue(result.FrameId); +}; using var entered = new ManualResetEventSlim(); using var release = new ManualResetEventSlim(); pipeline.ResultArrived += frame => @@ -34,6 +41,8 @@ camera.Emit(12); for(var i=0;i<100&&results.Count<3;i++)await Task.Delay(10); pipeline.Stop(); if(!results.SequenceEqual(new long[]{1,10,12}))throw new Exception("Restart left stale results"); +if(!imageResults.SequenceEqual(results))throw new Exception("Result images do not match the processed frames"); +Console.WriteLine("PASS: Each result carries its still-valid corresponding image"); Console.WriteLine("PASS: Stop drains the worker and restart accepts only new frames"); pipeline.LoadModels(new PipelineOptions { FrameStride = 2 }); await pipeline.StartAsync();camera.Emit(13);camera.Emit(14);