步骤编辑增加默认开启的结束图保存和目录选择
This commit is contained in:
parent
abc3290e41
commit
2197f740cb
@ -423,6 +423,8 @@ public class RecipeNode : EditorNode
|
||||
Description = step.Description,
|
||||
Timeout = step.Timeout,
|
||||
StandardDurationMs = step.StandardDurationMs,
|
||||
SaveCompletionImage = step.SaveCompletionImage,
|
||||
CompletionImageDirectory = step.CompletionImageDirectory,
|
||||
};
|
||||
|
||||
foreach (var item in step.MustKeep) stepNode.MustKeep.Items.Add(new TextItem { Text = item, RemoveCommand = stepNode.MustKeep.RemoveCommand });
|
||||
@ -477,6 +479,8 @@ public class RecipeNode : EditorNode
|
||||
Description = step.Description,
|
||||
Timeout = step.Timeout,
|
||||
StandardDurationMs = step.StandardDurationMs,
|
||||
SaveCompletionImage = step.SaveCompletionImage,
|
||||
CompletionImageDirectory = step.CompletionImageDirectory,
|
||||
};
|
||||
|
||||
def.MustKeep.AddRange(step.MustKeep.Items.Select(i => i.Text).Where(s => !string.IsNullOrWhiteSpace(s)));
|
||||
@ -773,6 +777,8 @@ public class StepNode : EditorNode
|
||||
private string _description = "";
|
||||
private int _timeout;
|
||||
private int _standardDurationMs;
|
||||
private bool _saveCompletionImage = true;
|
||||
private string _completionImageDirectory = "";
|
||||
// 即使 YAML 没有 detection,也保留可编辑对象,供界面写入新选择的方法。
|
||||
private ConditionNode? _detection = new();
|
||||
|
||||
@ -811,6 +817,18 @@ public class StepNode : EditorNode
|
||||
set { SetProperty(ref _standardDurationMs, value); }
|
||||
}
|
||||
|
||||
public bool SaveCompletionImage
|
||||
{
|
||||
get => _saveCompletionImage;
|
||||
set => SetProperty(ref _saveCompletionImage, value);
|
||||
}
|
||||
|
||||
public string CompletionImageDirectory
|
||||
{
|
||||
get => _completionImageDirectory;
|
||||
set => SetProperty(ref _completionImageDirectory, value);
|
||||
}
|
||||
|
||||
/// <summary>判定条件(method 留空 = 本步不写 detection 节点)</summary>
|
||||
public ConditionNode? Detection
|
||||
{
|
||||
|
||||
@ -148,6 +148,15 @@
|
||||
<TextBlock Text="说明" Classes="Field" />
|
||||
<TextBox Grid.Column="1" Text="{Binding Description, Mode=TwoWay}" />
|
||||
</Grid>
|
||||
<CheckBox Content="保存结束图" IsChecked="{Binding SaveCompletionImage, Mode=TwoWay}" Margin="0,8,0,4" />
|
||||
<StackPanel IsEnabled="{Binding SaveCompletionImage}">
|
||||
<TextBlock Text="步骤完成时保存一帧 PNG;目录留空时保存到当前配方的 completion-images 文件夹。" TextWrapping="Wrap" Foreground="{StaticResource FgDim}" />
|
||||
<Grid ColumnDefinitions="*,Auto,Auto" Margin="0,6,0,6">
|
||||
<TextBox x:Name="CompletionImageDirectoryBox" Text="{Binding CompletionImageDirectory, Mode=TwoWay}" PlaceholderText="默认:当前配方目录 / completion-images" />
|
||||
<Button Grid.Column="1" Content="选择目录…" Click="ChooseCompletionImageDirectory" Margin="8,0,0,0" />
|
||||
<Button Grid.Column="2" Content="恢复默认" Click="ResetCompletionImageDirectory" Margin="8,0,0,0" />
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
<TextBlock Text="判定条件" FontSize="13" Margin="0,10,0,6" Classes="Title" />
|
||||
<StackPanel>
|
||||
<TextBlock Text="请先选择判定方法;等待后完成请选择“持续计时”" Classes.state2="{Binding Detection, Converter={x:Static conv:ObjectConverters.IsNull}}" Classes.state3="{Binding Detection.Method, Converter={x:Static conv:StringConverters.IsNullOrEmpty}}" IsVisible="False">
|
||||
|
||||
@ -1,4 +1,5 @@
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Platform.Storage;
|
||||
using Avalonia.Threading;
|
||||
using System.ComponentModel;
|
||||
using SopHelper.Training;
|
||||
@ -57,6 +58,21 @@ public partial class RecipeEditor : UserControl
|
||||
_recording.RecordingLimitReached += RecordingLimit;
|
||||
}
|
||||
private async void RecordingLimit(string message) => await ShowNotice("录像时长提示", message, false);
|
||||
private async void ChooseCompletionImageDirectory(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
|
||||
{
|
||||
if (sender is not Button { DataContext: StepNode step } || TopLevel.GetTopLevel(this) is not Window owner) return;
|
||||
try
|
||||
{
|
||||
var folders = await owner.StorageProvider.OpenFolderPickerAsync(new FolderPickerOpenOptions { Title = "选择步骤结束图保存目录", AllowMultiple = false });
|
||||
var directory = folders.FirstOrDefault()?.TryGetLocalPath();
|
||||
if (!string.IsNullOrWhiteSpace(directory)) step.CompletionImageDirectory = directory;
|
||||
}
|
||||
catch (Exception error) { await ShowNotice("选择目录失败", error.Message, false); }
|
||||
}
|
||||
private void ResetCompletionImageDirectory(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
|
||||
{
|
||||
if (sender is Button { DataContext: StepNode step }) step.CompletionImageDirectory = "";
|
||||
}
|
||||
private async Task<bool> ShowNotice(string title, string message, bool confirmation)
|
||||
{
|
||||
if (_closing || _dialog is not null || TopLevel.GetTopLevel(this) is not Window owner) return false;
|
||||
|
||||
@ -57,6 +57,7 @@ public class SopPageViewModel : ViewModelBase
|
||||
/// <summary>最近一次处理过的帧(快照按钮存盘用,由推理线程写入)</summary>
|
||||
private FrameResult? _lastFrame;
|
||||
private Mat? _judgementFrame;
|
||||
private Task _completionImageSaves = Task.CompletedTask;
|
||||
private FrameResult? _handResult;
|
||||
private WriteableBitmap? _bitmap;
|
||||
private long _frameCount;
|
||||
@ -411,6 +412,9 @@ public class SopPageViewModel : ViewModelBase
|
||||
_bitmap?.Dispose();
|
||||
_bitmap = null;
|
||||
|
||||
// Image writes own their frames and never wait for the UI thread.
|
||||
_completionImageSaves.GetAwaiter().GetResult();
|
||||
|
||||
// 相机与推理管线是应用级单例,由 App.OnExit 按顺序统一释放。
|
||||
|
||||
base.Destroy();
|
||||
@ -755,7 +759,8 @@ public class SopPageViewModel : ViewModelBase
|
||||
Rois.Clear();
|
||||
|
||||
foreach (var step in config.Sop.Steps.OrderBy(s => s.Id))
|
||||
StepCards.Add(new StepCard { StepId = step.Id, Name = step.Name, Message = "—" });
|
||||
StepCards.Add(new StepCard { StepId = step.Id, Name = step.Name, Message = "—",
|
||||
SaveCompletionImage = step.SaveCompletionImage, CompletionImageDirectory = step.CompletionImageDirectory });
|
||||
|
||||
foreach (var (name, def) in config.Sop.Regions)
|
||||
Rois.Add(new RoiItem { Name = name, X = def.X1, Y = def.Y1, W = def.X2 - def.X1, H = def.Y2 - def.Y1, ColorHex = def.Color });
|
||||
@ -899,8 +904,43 @@ public class SopPageViewModel : ViewModelBase
|
||||
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()));
|
||||
if (card.SaveCompletionImage) SaveCompletionImage(card, frame);
|
||||
}
|
||||
}
|
||||
|
||||
private void SaveCompletionImage(StepCard card, Mat frame)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Resolve against the applied recipe, even if settings has a different pending selection.
|
||||
var recipeDirectory = DesktopPlatform.Recipes.DirectoryFor(Path.GetFileNameWithoutExtension(ActiveRecipe));
|
||||
var directory = string.IsNullOrWhiteSpace(card.CompletionImageDirectory)
|
||||
? Path.Combine(recipeDirectory, "completion-images")
|
||||
: Path.GetFullPath(card.CompletionImageDirectory.Trim(), recipeDirectory);
|
||||
var path = Path.Combine(directory, $"{DateTime.Now:yyyyMMdd-HHmmss-fff}-step-{card.StepId}-{Guid.NewGuid():N}.png");
|
||||
var owned = frame.Clone();
|
||||
_completionImageSaves = _completionImageSaves.ContinueWith(_ =>
|
||||
{
|
||||
using (owned)
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(directory);
|
||||
// .NET handles Unicode paths consistently on Windows and Linux.
|
||||
File.WriteAllBytes(path, owned.ToBytes(".png"));
|
||||
_dispatcher.BeginInvoke(() => { if (!_destroyed) Log("info", $"步骤 {card.StepId} 结束图已保存:{path}"); });
|
||||
}
|
||||
catch (Exception error)
|
||||
{
|
||||
_dispatcher.BeginInvoke(() => { if (!_destroyed) Log("warn", $"步骤 {card.StepId} 结束图保存失败:{path};{error.Message}"); });
|
||||
}
|
||||
}
|
||||
}, TaskScheduler.Default);
|
||||
}
|
||||
catch (Exception error) { Log("warn", $"步骤 {card.StepId} 结束图保存失败:{error.Message}"); }
|
||||
}
|
||||
|
||||
private void AppendViolation(ViolationEvent violation)
|
||||
@ -936,6 +976,8 @@ public class SopPageViewModel : ViewModelBase
|
||||
/// </summary>
|
||||
public class StepCard : ViewModelBase
|
||||
{
|
||||
public bool SaveCompletionImage { get; init; } = true;
|
||||
public string CompletionImageDirectory { get; init; } = "";
|
||||
private BitmapSource? _completionImage;
|
||||
|
||||
/// <summary>步骤完成时的独立帧,不随实时画面更新。</summary>
|
||||
|
||||
@ -139,6 +139,12 @@ public class StepDef
|
||||
/// <summary>标准节拍毫秒(报表对比用,判定不参与)</summary>
|
||||
public int StandardDurationMs { get; set; }
|
||||
|
||||
/// <summary>步骤完成时保存对应判定帧,旧配方也默认开启。</summary>
|
||||
public bool SaveCompletionImage { get; set; } = true;
|
||||
|
||||
/// <summary>留空时保存到当前配方的 completion-images 目录。</summary>
|
||||
public string CompletionImageDirectory { get; set; } = "";
|
||||
|
||||
/// <summary>本步判定条件(AND,全部满足才算完成)</summary>
|
||||
public StepCondition? Detection { get; set; }
|
||||
|
||||
|
||||
@ -119,6 +119,7 @@ internal static class Smoke
|
||||
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);
|
||||
await CheckCompletionImageSaving(app,sop);
|
||||
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");
|
||||
@ -652,6 +653,92 @@ internal static class Smoke
|
||||
}
|
||||
finally{sop.IsRunning=false;sop.ApplyRecipeCommand.Execute();}
|
||||
}
|
||||
private static async Task CheckCompletionImageSaving(App app,SopPageViewModel sop)
|
||||
{
|
||||
var store=new RecipeWorkspace(Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT")!);
|
||||
var name="结束图测试";var file=name+".yaml";
|
||||
var selected=sop.SelectedRecipe;
|
||||
var custom=Path.Combine(store.Root,"其它目录","结束图");
|
||||
var blocked=Path.Combine(store.Root,"不能作为目录.txt");File.WriteAllText(blocked,"blocked");
|
||||
var config=new SopHelper.Engine.Sop.SopConfig();config.Sop.Name=name;
|
||||
config.Sop.Settings.AutoResetOnComplete=false;config.Sop.Settings.StableFrames=1;
|
||||
for(var id=1;id<=4;id++)config.Sop.Steps.Add(new()
|
||||
{
|
||||
Id=id,Name="步骤"+id,SaveCompletionImage=id!=2,
|
||||
CompletionImageDirectory=id==3?custom:id==4?blocked:"",
|
||||
Detection=new(){Method="time_elapsed",DurationMs=1,StableFrames=1}
|
||||
});
|
||||
var legacy=SopHelper.Engine.Sop.SopConfigLoader.Parse("sop:\n name: legacy\n steps:\n - id: 1\n name: first\n");
|
||||
Check(legacy.Sop.Steps[0].SaveCompletionImage&&legacy.Sop.Steps[0].CompletionImageDirectory=="","Existing recipes default to saving completion images in their own recipe directory");
|
||||
var node=RecipeNode.From(config,file,false);
|
||||
var roundTrip=SopHelper.Engine.Sop.SopConfigLoader.Parse(SopHelper.Engine.Sop.SopConfigLoader.ToYaml(node.ToConfig()));
|
||||
Check(roundTrip.Sop.Steps[0].SaveCompletionImage&&!roundTrip.Sop.Steps[1].SaveCompletionImage&&roundTrip.Sop.Steps[2].CompletionImageDirectory==custom,"Step image switches and custom Unicode directories survive editor and YAML round trips");
|
||||
Directory.CreateDirectory(store.DirectoryFor(name));
|
||||
SopHelper.Engine.Sop.SopConfigLoader.Save(roundTrip,store.ConfigPath(name));
|
||||
var editorVm=new RecipeEditorViewModel();
|
||||
editorVm.OnDialogOpened(new DialogParameters{{"directory",store.RecipesDirectory},{"path",store.ConfigPath(name)},{"config",roundTrip},{"new",false}});
|
||||
var editor=new RecipeEditor{DataContext=editorVm};
|
||||
var dialog=new Window{Content=editor,Width=1040,Height=760};dialog.Show();await Task.Delay(60);
|
||||
try
|
||||
{
|
||||
var toggle=editor.GetVisualDescendants().OfType<CheckBox>().Single(c=>c.Content?.ToString()=="保存结束图");
|
||||
var directoryBox=editor.GetVisualDescendants().OfType<TextBox>().Single(t=>t.Name=="CompletionImageDirectoryBox");
|
||||
Check(toggle.IsChecked==true&&string.IsNullOrEmpty(directoryBox.Text),"Step editor exposes image saving enabled by default with the recipe directory selected");
|
||||
toggle.IsChecked=false;await Task.Delay(20);
|
||||
Check(!editorVm.Recipe.SelectedStep!.SaveCompletionImage&&!directoryBox.IsEffectivelyEnabled,"Turning off image saving disables its directory controls");
|
||||
toggle.IsChecked=true;editorVm.Recipe.SelectedStep=editorVm.Recipe.Steps[2];await Task.Delay(20);
|
||||
Check(directoryBox.Text==custom,"Selecting another step restores its own custom image directory");
|
||||
editor.GetVisualDescendants().OfType<Button>().Single(b=>b.Content?.ToString()=="恢复默认").RaiseEvent(new Avalonia.Interactivity.RoutedEventArgs(Button.ClickEvent));
|
||||
Check(editorVm.Recipe.SelectedStep.CompletionImageDirectory=="","Restore default clears the step's directory override");
|
||||
directoryBox.Text=custom;editorVm.SaveCommand.Execute();await Task.Delay(20);
|
||||
var saved=SopHelper.Engine.Sop.SopConfigLoader.Load(store.ConfigPath(name));
|
||||
Check(saved.Sop.Steps[0].SaveCompletionImage&&!saved.Sop.Steps[1].SaveCompletionImage&&saved.Sop.Steps[2].CompletionImageDirectory==custom,"Saving the actual step editor persists per-step image settings");
|
||||
editorVm.Recipe.SelectedStep=editorVm.Recipe.Steps[0];await Task.Delay(20);Save(dialog,"step-completion-image-settings");
|
||||
}
|
||||
finally{await editorVm.ShutdownAsync();dialog.Close();}
|
||||
sop.Recipes.Add(file);sop.SelectedRecipe=file;sop.ApplyRecipeCommand.Execute();
|
||||
var engine=app.Container.Resolve<SopHelper.Engine.Sop.SopEngine>();
|
||||
var receive=typeof(SopPageViewModel).GetMethod("OnResultFrame",System.Reflection.BindingFlags.NonPublic|System.Reflection.BindingFlags.Instance)!;
|
||||
async Task WaitForImages()
|
||||
{
|
||||
await (Task)typeof(SopPageViewModel).GetField("_completionImageSaves",System.Reflection.BindingFlags.NonPublic|System.Reflection.BindingFlags.Instance)!.GetValue(sop)!;
|
||||
await Task.Delay(30);
|
||||
}
|
||||
async Task Round()
|
||||
{
|
||||
for(var id=1;id<=4;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(30);
|
||||
}
|
||||
await WaitForImages();
|
||||
}
|
||||
try
|
||||
{
|
||||
sop.IsRunning=true;engine.Start();
|
||||
// A pending selection must not redirect the applied recipe's images.
|
||||
sop.SelectedRecipe=selected;
|
||||
await Round();
|
||||
var defaults=Path.Combine(store.DirectoryFor(name),"completion-images");
|
||||
var defaultFile=Directory.GetFiles(defaults,"*.png").Single();
|
||||
var customFile=Directory.GetFiles(custom,"*.png").Single();
|
||||
using(var image=Cv2.ImRead(defaultFile))Check(image.Width==64&&image.Height==48&&image.At<Vec3b>(0,0)==new Vec3b(30,60,90),"Default completion image is the exact judged frame and stays under the applied recipe");
|
||||
using(var image=Cv2.ImRead(customFile))Check(image.At<Vec3b>(0,0)==new Vec3b(90,60,90),"Custom directory receives its step's exact completion frame after source disposal");
|
||||
Check(defaultFile.Contains("step-1-")&&customFile.Contains("step-3-")&&sop.StepCards[1].HasCompletionImage,"Disabled image saving creates no file while retaining the on-screen completion image");
|
||||
Check(engine.State==SopHelper.Engine.Sop.EngineState.Completed&&sop.Logs.Any(l=>l.Message.Contains("步骤 4 结束图保存失败")),"An unwritable image directory reports a warning without interrupting step completion");
|
||||
engine.Reset();await Round();
|
||||
Check(Directory.GetFiles(defaults,"*.png").Length==2&&Directory.GetFiles(custom,"*.png").Length==2,"A new round saves one new image per enabled step without overwriting prior images");
|
||||
Check(File.Exists(defaultFile)&&File.Exists(customFile),"Reset preserves images already saved on disk");
|
||||
}
|
||||
finally
|
||||
{
|
||||
await WaitForImages();sop.IsRunning=false;sop.SelectedRecipe=selected;sop.ApplyRecipeCommand.Execute();
|
||||
sop.Recipes.Remove(file);
|
||||
}
|
||||
}
|
||||
|
||||
private static void Save(Window window,string name)
|
||||
{
|
||||
window.UpdateLayout();
|
||||
|
||||
Loading…
Reference in New Issue
Block a user