新增主界面步骤完成过程图展示区

This commit is contained in:
tfarcraw 2026-11-10 15:39:28 +08:00
parent 442fb282b7
commit 56fb5932a8
6 changed files with 171 additions and 5 deletions

View File

@ -14,6 +14,10 @@
</Style>
</UserControl.Styles>
<Grid Margin="10">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="390" />
@ -150,5 +154,37 @@
<TextBlock Text="{Binding ConnectionText}" Margin="6,0,0,0" Foreground="{StaticResource FgDim}" />
</StackPanel>
</Grid>
<Border Grid.Row="1" Grid.ColumnSpan="2" Margin="0,10,0,0" Classes="panel" x:Name="ProcessImagesPanel">
<Grid RowDefinitions="Auto,Auto">
<TextBlock Text="过程图 · 步骤完成时定格" Classes="Title" />
<ScrollViewer Grid.Row="1" Margin="0,8,0,0" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Disabled">
<ItemsControl ItemsSource="{Binding StepCards}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate><StackPanel Orientation="Horizontal" /></ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border Width="204" Margin="0,0,10,0" Padding="8" Background="{StaticResource Bg}" BorderBrush="{StaticResource Line}" BorderThickness="1" CornerRadius="6">
<Grid RowDefinitions="Auto,112,Auto">
<TextBlock Margin="0,0,0,6" TextTrimming="CharacterEllipsis" ToolTip.Tip="{Binding Name}">
<TextBlock.Text>
<MultiBinding StringFormat="{}{0}. {1}"><Binding Path="StepId" /><Binding Path="Name" /></MultiBinding>
</TextBlock.Text>
</TextBlock>
<Border Grid.Row="1" Background="{StaticResource Line}" CornerRadius="4">
<Grid>
<Image Source="{Binding CompletionImage}" Stretch="Uniform" />
<TextBlock Text="等待步骤完成" IsVisible="{Binding IsWaitingForImage}" HorizontalAlignment="Center" VerticalAlignment="Center" Foreground="{StaticResource FgDim}" />
</Grid>
</Border>
<TextBlock Grid.Row="2" Text="已完成" IsVisible="{Binding HasCompletionImage}" Foreground="{StaticResource Ok}" Margin="0,6,0,0" FontSize="12" />
</Grid>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
</Grid>
</Border>
</Grid>
</UserControl>

View File

@ -56,6 +56,7 @@ public class SopPageViewModel : ViewModelBase
/// <summary>最近一次处理过的帧(快照按钮存盘用,由推理线程写入)</summary>
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
/// </summary>
public class StepCard : ViewModelBase
{
private BitmapSource? _completionImage;
/// <summary>步骤完成时的独立帧,不随实时画面更新。</summary>
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 = "";

View File

@ -74,6 +74,9 @@ public class DetectionPipeline : IDisposable
/// <summary>结果帧(在管线线程上触发)</summary>
public event Action<FrameResult>? ResultArrived;
/// <summary>结果与对应原始帧;Mat 仅在回调期间有效,异步使用必须克隆。</summary>
public event Action<FrameResult, Mat>? ResultFrameArrived;
public event Action<string>? InferenceWarning;
/// <summary>
@ -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)

View File

@ -72,6 +72,9 @@ public class SopEngine
/// <summary>整轮完成</summary>
public event Action? Completed;
/// <summary>开始或复位到新一轮。</summary>
public event Action? RoundStarted;
/// <summary>
/// 加载配方(区域 → 像素矩形;校验提醒原样转出去)
/// </summary>
@ -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();

View File

@ -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<Control>().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<SopPage>().Single()
.GetVisualDescendants().OfType<Image>().Single();
.GetVisualDescendants().OfType<Image>().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<SopHelper.Engine.Sop.SopEngine>();
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<Vec3b>(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<Border>().Single(b=>b.Name=="ProcessImagesPanel");
Check(panel.Bounds.Height>100&&panel.GetVisualDescendants().OfType<Image>().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();

View File

@ -6,6 +6,13 @@ using SopHelper.Engine.Pipeline;
using var camera = new TestCamera();
using var pipeline = new DetectionPipeline(camera);
var results = new ConcurrentQueue<long>();
var imageResults = new ConcurrentQueue<long>();
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);