按检测轮次归档步骤完成图片

This commit is contained in:
wanglei 2026-12-04 09:33:18 +08:00
parent a9e8e72779
commit f7ebe824bb
5 changed files with 167 additions and 40 deletions

View File

@ -256,7 +256,9 @@
<StackPanel Spacing="6">
<CheckBox Content="保存结束图" IsChecked="{Binding SaveCompletionImage, Mode=TwoWay}" />
<StackPanel IsEnabled="{Binding SaveCompletionImage}" Spacing="6">
<TextBox x:Name="CompletionImageDirectoryBox" Text="{Binding CompletionImageDirectory, Mode=TwoWay}" PlaceholderText="默认:配方目录 / completion-images" />
<!-- 兼容旧配方的步骤目录字段。运行时按步骤顺序选取一个根目录供整轮归档。 -->
<TextBox x:Name="CompletionImageDirectoryBox" Text="{Binding CompletionImageDirectory, Mode=TwoWay}" PlaceholderText="默认:配方目录 / completion-images"
ToolTip.Tip="整轮共用一个目录,按步骤顺序采用首个已启用保存的自定义目录。" />
<Grid ColumnDefinitions="*,8,*">
<Button Content="选择目录…" Click="ChooseCompletionImageDirectory" HorizontalAlignment="Stretch" />
<Button Grid.Column="2" Content="恢复默认" Click="ResetCompletionImageDirectory" HorizontalAlignment="Stretch" />

View File

@ -3,6 +3,8 @@
using System.Collections.ObjectModel;
using System.IO;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using System.Text.Json;
using Avalonia.Media;
using ImageSource = Avalonia.Media.IImage;
@ -72,6 +74,8 @@ public class SopPageViewModel : ViewModelBase
private FrameResult? _lastFrame;
private Mat? _judgementFrame;
private Task _completionImageSaves = Task.CompletedTask;
private string? _roundImageDirectory;
private readonly HashSet<string> _roundImageNames = new(StringComparer.OrdinalIgnoreCase);
private FrameResult? _handResult;
private WriteableBitmap? _bitmap;
private long _frameCount;
@ -566,7 +570,7 @@ public class SopPageViewModel : ViewModelBase
_bitmap?.Dispose();
_bitmap = null;
// Image writes own their frames and never wait for the UI thread.
// 写盘任务拥有各自的原生帧,日志异步投递到界面,退出时可在界面线程等待写盘收尾。
_completionImageSaves.GetAwaiter().GetResult();
// 相机与推理管线是应用级共享实例,由 App 中的主窗口 Closed 回调统一释放。
@ -1142,10 +1146,44 @@ public class SopPageViewModel : ViewModelBase
});
}
/// <summary>相机启动、自动复位和标准视频重播均经此处建立独立归档目录。</summary>
private void OnRoundStarted()
{
if (Avalonia.Threading.Dispatcher.UIThread.CheckAccess()) { ClearProcessImages(); RefreshStatistics(); }
else _dispatcher.BeginInvoke(() => { if (!_destroyed) { ClearProcessImages(); RefreshStatistics(); } });
var startedAt = DateTime.Now;
void InitializeRound()
{
if (_destroyed) return;
CreateRoundImageDirectory(startedAt);
ClearProcessImages();
RefreshStatistics();
}
if (Avalonia.Threading.Dispatcher.UIThread.CheckAccess()) InitializeRound();
else _dispatcher.BeginInvoke(InitializeRound);
}
/// <summary>开始时创建日期时间目录。创建失败时清除本轮目标并记录原因,防止写入上一轮。</summary>
private void CreateRoundImageDirectory(DateTime startedAt)
{
_roundImageDirectory = null;
_roundImageNames.Clear();
if (string.IsNullOrWhiteSpace(ActiveRecipe) || ActiveRecipe == "未应用配方") return;
try
{
var recipeDirectory = DesktopPlatform.Recipes.DirectoryFor(Path.GetFileNameWithoutExtension(ActiveRecipe));
var configured = StepCards.FirstOrDefault(card => card.SaveCompletionImage
&& !string.IsNullOrWhiteSpace(card.CompletionImageDirectory))?.CompletionImageDirectory;
var root = configured is null ? Path.Combine(recipeDirectory, "completion-images")
: Path.GetFullPath(configured.Trim(), recipeDirectory);
var timestamp = startedAt.ToString("yyyyMMdd-HHmmss-fff", CultureInfo.InvariantCulture);
var directory = Path.Combine(root, timestamp);
for (var suffix = 2; Directory.Exists(directory) || File.Exists(directory); suffix++)
directory = Path.Combine(root, $"{timestamp}-{suffix}");
_roundImageDirectory = Directory.CreateDirectory(directory).FullName;
}
catch (Exception error) { Log("warn", "本轮结束图目录创建失败:" + error.Message); }
}
private void OnRoundFinished(bool passed) => _dispatcher.BeginInvoke(() => { if (!_destroyed) { StatusText = passed ? "本轮完成,全部通过" : "本轮结束,有步骤未通过并跳过"; RefreshStatistics(); } });
@ -1440,16 +1478,43 @@ public class SopPageViewModel : ViewModelBase
}
}
/// <summary>把步骤名转为可跨平台使用的文件名,同轮同名时递增后缀以保留各步骤的图片。</summary>
private string ReserveCompletionImageName(StepCard card)
{
const string invalid = "<>:\"/\\|?*";
var safeName = new StringBuilder();
var byteCount = 0;
foreach (var rune in card.Name.EnumerateRunes())
{
var replacement = Rune.IsControl(rune) || (rune.IsAscii && invalid.Contains((char)rune.Value))
? new Rune('_') : rune;
// 给扩展名和重名后缀预留空间,也避免从中间截断多字节字符。
byteCount += replacement.Utf8SequenceLength;
if (byteCount > 230) break;
safeName.Append(replacement.ToString());
}
var name = safeName.ToString().Trim().TrimEnd('.', ' ');
if (name.Length == 0) name = $"步骤{card.StepId}";
var deviceName = name.Split('.', 2)[0].TrimEnd().ToUpperInvariant();
if (deviceName is "CON" or "PRN" or "AUX" or "NUL" ||
(deviceName.Length == 4 && (deviceName.StartsWith("COM", StringComparison.Ordinal) || deviceName.StartsWith("LPT", StringComparison.Ordinal))
&& "123456789¹²³".Contains(deviceName[3])))
name = "_" + name;
var fileName = name + ".png";
for (var suffix = 2; !_roundImageNames.Add(fileName); suffix++)
fileName = $"{name}-{suffix}.png";
return fileName;
}
/// <summary>在界面线程固定本轮路径并克隆判定帧,后台依次写盘,切换轮次后仍写入原目录。</summary>
private void SaveCompletionImage(StepCard card, Mat frame)
{
if (_roundImageDirectory is not { } directory) return;
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 path = Path.Combine(directory, ReserveCompletionImageName(card));
var owned = frame.Clone();
_completionImageSaves = _completionImageSaves.ContinueWith(_ =>
{
@ -1457,9 +1522,9 @@ public class SopPageViewModel : ViewModelBase
{
try
{
Directory.CreateDirectory(directory);
// .NET handles Unicode paths consistently on Windows and Linux.
File.WriteAllBytes(path, owned.ToBytes(".png"));
// 先编码再创建文件,使用 .NET 打开中文路径并防止覆盖已有图片。
var png = owned.ToBytes(".png");
using (var stream = File.Open(path, FileMode.CreateNew)) stream.Write(png);
_dispatcher.BeginInvoke(() => { if (!_destroyed) Log("info", $"步骤 {card.StepId} 结束图已保存:{path}"); });
}
catch (Exception error)

View File

@ -153,7 +153,7 @@ public class StepDef
/// <summary>步骤完成时保存对应判定帧,旧配方也默认开启。</summary>
public bool SaveCompletionImage { get; set; } = true;
/// <summary>留空时保存到当前配方的 completion-images 目录。</summary>
/// <summary>按步骤顺序取第一个已启用保存的非空目录作为整轮归档根目录,全部留空时使用当前配方的 completion-images 目录。</summary>
public string CompletionImageDirectory { get; set; } = "";
/// <summary>本步判定条件(AND,全部满足才算完成)</summary>

View File

@ -327,10 +327,7 @@ public partial class SopEngine
if (_config.Sop.Settings.AutoResetOnComplete)
{
// 停留一会儿让操作员看到结果,再自动复位
var generation = Volatile.Read(ref _roundGeneration);
Task.Delay(TimeSpan.FromSeconds(Math.Max(1, _config.Sop.Settings.ResetDelaySec)))
.ContinueWith(_ => { if (generation == Volatile.Read(ref _roundGeneration) && State == EngineState.Completed) Reset(); });
_ = ResetAfterDelayAsync(Volatile.Read(ref _roundGeneration), Math.Max(1, _config.Sop.Settings.ResetDelaySec));
}
return;
@ -342,6 +339,13 @@ public partial class SopEngine
NotifyCurrent();
}
/// <summary>保留判定入口的同步上下文,使桌面端在界面线程完成复位和轮次初始化,再处理下一帧。</summary>
private async Task ResetAfterDelayAsync(int generation, int delaySeconds)
{
await Task.Delay(TimeSpan.FromSeconds(delaySeconds));
if (generation == Volatile.Read(ref _roundGeneration) && State == EngineState.Completed) Reset();
}
/// <summary>统一经实时请求策略调用客户端,保持在线运行和回测使用同一超时语义。</summary>
private static Task<VisionDecisionResult> RunDecisionAsync(IVisionDecisionClient client, VisionDecisionRequest request, CancellationToken token)
=> RealtimeDecisionPolicy.RunAsync(client, request, token);

View File

@ -297,6 +297,8 @@ internal static class Smoke
window.WindowState=WindowState.Normal;window.Width=1180;window.Height=820;
await Task.Delay(150);
var sop=app.Container.Resolve<SopPageViewModel>();
// 单独验证结束图归档,便于复现归档路径和轮次问题。
if(Environment.GetCommandLineArgs().Contains("--completion-images-only")){await CheckCompletionImageSaving(app,sop);_exit=0;return;}
if(_visionOnly){await CheckVisionConfirmation(app,sop);_exit=0;return;}
var sopView=window.GetVisualDescendants().OfType<SopPage>().Single();
Check(!sopView.GetVisualDescendants().Any(c=>c is ComboBox or Slider),"Operator page contains no camera, recipe or parameter editors");
@ -1123,12 +1125,17 @@ internal static class Smoke
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()
for(var id=1;id<=4;id++)
{
Id=id,Name="步骤"+id,SaveCompletionImage=id!=2,
CompletionImageDirectory=id==3?custom:id==4?blocked:"",
Detection=new(){Method="time_elapsed",DurationMs=1,StableFrames=1}
});
config.Sop.Regions["工位"+id]=new(){X1=(id-1)*16,Y1=0,X2=id*16,Y2=48};
config.Sop.Steps.Add(new()
{
Id=id,Name=id==1?"装配/检查":id==4?"装配_检查":"步骤"+id,SaveCompletionImage=id!=2,
Description="零件安装到位",CompletionImageDirectory=id==3?custom:id==4?blocked:"",
Detection=new(){Method="hand_in_region",Region="工位"+id,StableFrames=1,Tolerance=0},
AiConfirmation=new(){ImageMode="full_frame",EvidenceMode="single_frame",CheckWindowMs=0}
});
}
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);
@ -1160,7 +1167,12 @@ internal static class Smoke
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 previousClient=engine.VisionDecisionClient;
var decision=new UiVisionDecision();
decision.Result.SetResult(new(true,.99,"确认完成"));
engine.VisionDecisionClient=decision;
var receive=typeof(SopPageViewModel).GetMethod("OnResultFrame",System.Reflection.BindingFlags.NonPublic|System.Reflection.BindingFlags.Instance)!;
var frameId=0;
async Task WaitForImages()
{
await (Task)typeof(SopPageViewModel).GetField("_completionImageSaves",System.Reflection.BindingFlags.NonPublic|System.Reflection.BindingFlags.Instance)!.GetValue(sop)!;
@ -1170,33 +1182,77 @@ internal static class Smoke
{
for(var id=1;id<=4;id++)
{
await Task.Delay(20);
// 每步使用独立触发区域和颜色,经真实引擎取图,再用后续帧收取模拟 AI 结果。
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);
{
for(var attempt=0;attempt<20&&engine.CurrentStep?.Id==id;attempt++)
{
receive.Invoke(sop,[new SopHelper.Engine.Common.FrameResult{FrameId=++frameId,Timestamp=DateTime.Now,Size=(64,48),
Hands=[new(){Rect=new((id-1)*16+3,20,10,10)}]},frame]);
await Task.Delay(15);
}
}
Check(sop.StepCards[id-1].HasCompletionImage,$"步骤 {id} 通过后生成完成图");
}
await WaitForImages();
}
try
{
engine.Config.Sop.Settings.AutoResetOnComplete=true;
engine.Config.Sop.Settings.ResetDelaySec=1;
sop.IsRunning=true;engine.Start();
// A pending selection must not redirect the applied recipe's images.
// 第一帧之前就应有空目录。待应用的配方和后续步骤的目录配置都不能改变本轮路径。
var first=Directory.GetDirectories(custom).Single();
Check(DateTime.TryParseExact(Path.GetFileName(first),"yyyyMMdd-HHmmss-fff",System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,out _)&&Directory.GetFiles(first).Length==0,"开始检测时即创建日期时间目录");
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");
var expected=new Dictionary<string,byte>{{"装配_检查.png",30},{"步骤3.png",90},{"装配_检查-2.png",120}};
void CheckRoundImages(string directory)
{
Check(Directory.GetFiles(directory,"*.png").Length==expected.Count,"同轮只保存开启归档的步骤");
foreach(var (imageName,blue) in expected)
{
using var image=Cv2.ImDecode(File.ReadAllBytes(Path.Combine(directory,imageName)),ImreadModes.Color);
Check(image.Width==64&&image.Height==48&&Math.Abs(image.At<Vec3b>(0,0).Item0-blue)<=3,$"{imageName} 对应原判定帧");
}
}
CheckRoundImages(first);
Check(sop.StepCards[1].HasCompletionImage,"关闭保存的步骤仍显示完成图片");
for(var attempt=0;attempt<100&&Directory.GetDirectories(custom).Length==1;attempt++)await Task.Delay(20);
var second=Directory.GetDirectories(custom).Single(path=>path!=first);
Check(Directory.GetFiles(second).Length==0&&engine.State==EngineState.Running,"自动复位在新一轮首帧之前创建空目录");
engine.Config.Sop.Settings.AutoResetOnComplete=false;
await Round();
CheckRoundImages(first);
CheckRoundImages(second);
// 把原先次选的无效路径提升为归档根目录,确认创建失败时仍可完成检测。
sop.IsRunning=false;
roundTrip.Sop.Steps[2].CompletionImageDirectory="";
SopHelper.Engine.Sop.SopConfigLoader.Save(roundTrip,store.ConfigPath(name));
sop.SelectedRecipe=file;sop.ApplyRecipeCommand.Execute();
engine.Config.Sop.Settings.AutoResetOnComplete=false;
sop.IsRunning=true;engine.Start();
await Round();
Check(engine.State==EngineState.Completed&&sop.Logs.Any(l=>l.Message.Contains("本轮结束图目录创建失败")),"归档目录创建失败有日志,检测继续完成");
CheckRoundImages(second);
Check(Directory.GetDirectories(custom).Length==2,"创建失败的轮次不会写入上一轮目录");
sop.IsRunning=false;
roundTrip.Sop.Steps[3].CompletionImageDirectory="";
SopHelper.Engine.Sop.SopConfigLoader.Save(roundTrip,store.ConfigPath(name));
sop.ApplyRecipeCommand.Execute();
engine.Config.Sop.Settings.AutoResetOnComplete=false;
sop.IsRunning=true;engine.Start();
var defaultRound=Directory.GetDirectories(Path.Combine(store.DirectoryFor(name),"completion-images")).Single();
await Round();
CheckRoundImages(defaultRound);
}
finally
{
await WaitForImages();sop.IsRunning=false;sop.SelectedRecipe=selected;sop.ApplyRecipeCommand.Execute();
await WaitForImages();sop.IsRunning=false;engine.VisionDecisionClient=previousClient;
sop.SelectedRecipe=selected;sop.ApplyRecipeCommand.Execute();
sop.Recipes.Remove(file);
}
}
@ -1322,8 +1378,8 @@ internal static class Smoke
for(int i=0;i<100&&engine.State!=SopHelper.Engine.Sop.EngineState.Completed;i++)await Emit(new Scalar(240,0,0));
Check(engine.State==SopHelper.Engine.Sop.EngineState.Completed&&sop.StepCards[0].HasCompletionImage,"AI confirmation advances actual runtime UI");
await (Task)typeof(SopPageViewModel).GetField("_completionImageSaves",System.Reflection.BindingFlags.NonPublic|System.Reflection.BindingFlags.Instance)!.GetValue(sop)!;
var saved=Directory.GetFiles(Path.Combine(store.DirectoryFor(name),"completion-images"),"*.png").Single();
using var evidence=Cv2.ImRead(saved);var pixel=evidence.At<Vec3b>(0,0);
var archive=Directory.GetDirectories(Path.Combine(store.DirectoryFor(name),"completion-images")).Single();
using var evidence=Cv2.ImDecode(File.ReadAllBytes(Path.Combine(archive,"装配.png")),ImreadModes.Color);var pixel=evidence.At<Vec3b>(0,0);
Check(pixel.Item2>230&&pixel.Item0<10,"Saved image is red AI input, not blue frame at response arrival");
}
finally{sop.IsRunning=false;engine.Stop();}