在主界面循环播放标准视频并检测流程

This commit is contained in:
wanglei 2026-11-25 13:01:05 +08:00
parent 207f7b4334
commit 9a7e89d12a
7 changed files with 191 additions and 115 deletions

View File

@ -36,7 +36,7 @@ pwsh -File tools/Start-HandAiD3.ps1
Windows DirectShow 设置分辨率时可能把 MJPG 重置为 YUY2,因此程序在分辨率和帧率设置后再应用视频格式;Linux V4L2 保持先设置格式。2026-11-18 在 USB Camera(0c45:636d)上验证:原顺序在 640×480 和 800×600 下均约 15fps,修复后通过实际 UvcCameraService 采集均约 30fps,格式回读为 MJPG,手动曝光回读 15.625ms。设置接口返回成功和驱动回读 30fps 均不能代替实际采集计数。
SOP 流程视频可在配方编辑器中录制和播放,独立保存在该配方的 `sop_stand` 目录。主界面的“播放标准 SOP”可独立打开当前已应用配方的视频,支持播放和拖动进度,不影响相机采集。配方导入导出在“运行设置”的配方行:选中配方点击“导出”,把配方定义和标准 SOP 视频打包成单个 `.bwsrecipe` 文件(zip,含 `package.json` 清单:配方名、导出时间、导出程序版本、每个文件的大小和 SHA-256)。关键帧已内联在配方 YAML 中,包内只有配方文件和 `sop_stand` 视频,不带运行图片、录像和已移除功能遗留的数据集/模型。步骤的完成图目录若位于配方目录内会改写为相对路径;位于配方目录之外时导出提醒并在包内清空,导入端使用配方默认目录,不搬运工位本地路径。
SOP 流程视频可在配方编辑器中录制和播放,独立保存在该配方的 `sop_stand` 目录。主界面的“播放标准 SOP”在主预览区播放当前已应用配方的视频,检测流程使用视频帧,每次播完间隔 5 秒从头重播并开始新一轮检测。播放前会停止正在进行的相机采集。配方导入导出在“运行设置”的配方行:选中配方点击“导出”,把配方定义和标准 SOP 视频打包成单个 `.bwsrecipe` 文件(zip,含 `package.json` 清单:配方名、导出时间、导出程序版本、每个文件的大小和 SHA-256)。关键帧已内联在配方 YAML 中,包内只有配方文件和 `sop_stand` 视频,不带运行图片、录像和已移除功能遗留的数据集/模型。步骤的完成图目录若位于配方目录内会改写为相对路径;位于配方目录之外时导出提醒并在包内清空,导入端使用配方默认目录,不搬运工位本地路径。
“导入”选择配方包后先检查:清单缺失、包被改动、大小与清单不符、格式版本高于当前程序或包含越界路径都会拒绝并给出原因。同名配方弹窗选择覆盖(现有配方整目录移入 `workspace/deleted-recipes`,可找回)或另存为 `-2` 等新名称;取消不动盘上文件。导入解压到配方目录内的暂存目录,逐文件校验通过后整目录一次移动到位,中断不会留下半个配方,也不留 `.importing-*`。导入的新配方不会自动应用,区域坐标按相机分辨率标定,需要复核后手动点击“应用”。导入导出不需要登录以外的额外权限:操作员点击只弹出权限提示,工艺师和管理员可用。

View File

@ -34,7 +34,7 @@
<Border Grid.Column="0" Classes="panel" x:Name="RealtimeImagePanel">
<Viewbox Stretch="Uniform" Margin="4">
<Grid Width="{Binding FrameWidth}" Height="{Binding FrameHeight}">
<Image Source="{Binding Frame}" Stretch="Fill" />
<Image Source="{Binding PreviewFrame}" Stretch="Fill" />
<ItemsControl ItemsSource="{Binding Rois}">
<ItemsControl.Styles>
<Style Selector="ContentPresenter">
@ -91,7 +91,7 @@
<WrapPanel Grid.Row="1" Margin="0,10,0,0" HorizontalAlignment="Left">
<Button Content="开始 / 停止" Command="{Binding StartStopCommand}" />
<Button x:Name="ResetCountsButton" Content="重置计数" Margin="6,0,0,0" Command="{Binding ResetCountsCommand}" ToolTip.Tip="清零当前已应用配方的正常次数和异常次数,保留步骤进度和其他配方计数" />
<Button x:Name="PlayStandardSopButton" Content="播放标准 SOP" Margin="6,0,0,0" Command="{Binding PlayStandardSopCommand}" ToolTip.Tip="播放当前已应用配方的标准视频;没有视频时请先在配方中录制或导入" />
<Button x:Name="PlayStandardSopButton" Content="{Binding StandardSopButtonText}" Margin="6,0,0,0" Command="{Binding PlayStandardSopCommand}" ToolTip.Tip="在主界面播放并检测当前已应用配方的标准视频,播完 5 秒后重播" />
</WrapPanel>
<Border Grid.Row="2" Margin="0,10,0,0" Classes="panel">
<ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled">

View File

@ -18,6 +18,7 @@ using SopHelper.Engine.Common;
using SopHelper.Engine.Pipeline;
using SopHelper.Engine.Sop;
using SopHelper.Engine.Recipes;
using SopHelper.SopVideo;
namespace SopHelper.VVMs.SopPage;
@ -159,7 +160,8 @@ public class SopPageViewModel : ViewModelBase
RefreshCamerasCommand = ConfigurationCommand(async () => await RefreshCamerasAsync(), () => CanSelectCamera);
StartStopCommand = new DelegateCommand(async () => { if (Access.CheckPermission(Access.IsAuthenticated, "启动或停止运行") && CanStart()) await StartStopAsync(); }, () => !Access.IsAuthenticated || CanStart());
ResetCountsCommand = ConfigurationCommand(ResetCounts, () => StepCards.Count > 0);
PlayStandardSopCommand = ConfigurationCommand(PlayStandardSop, () => StandardSopVideoPath is { } path && File.Exists(path));
PlayStandardSopCommand = ConfigurationCommand(async () => await ToggleStandardSopAsync(), () => !_isCameraBusy && !_deletingRecipe && !_transferringRecipe
&& (_standardSopCancellation is not null || StandardSopVideoPath is { } path && File.Exists(path)));
ApplyRecipeCommand = ConfigurationCommand(ApplyRecipe, () => CanSelectCamera && !string.IsNullOrWhiteSpace(SelectedRecipe));
SnapshotCommand = ConfigurationCommand(Snapshot, () => _lastFrame is not null);
EditRecipeCommand = ConfigurationCommand(EditRecipe, CanEditRecipe);
@ -255,7 +257,7 @@ public class SopPageViewModel : ViewModelBase
public ImageSource? Frame
{
get { return _frame; }
set { SetProperty(ref _frame, value); }
set { if (SetProperty(ref _frame, value)) RaisePropertyChanged(nameof(PreviewFrame)); }
}
/// <summary>最近一次推理结果,供图像上的手部与目标检测绘制层使用。</summary>
@ -545,7 +547,7 @@ public class SopPageViewModel : ViewModelBase
{
lock (_frameLock)
{
if (_destroyed) return;
if (_destroyed || _standardSopCancellation is not null) return;
var clone = frame.Bgr.Clone();
var old = _pending;
_pending = clone;
@ -555,7 +557,7 @@ public class SopPageViewModel : ViewModelBase
_dispatcher.BeginInvoke(() =>
{
Interlocked.Exchange(ref _renderQueued, 0);
if (!_destroyed) RenderFrame();
if (!_destroyed && _standardSopCancellation is null) RenderFrame();
}, DispatcherPriority.Render);
}
@ -588,7 +590,7 @@ public class SopPageViewModel : ViewModelBase
{
Access.SessionChanged -= AccessChanged;
_statisticsTimer.Stop();
_standardSopWindow?.Close();
_standardSopCancellation?.Cancel();
_engine.Stop();
_engine.RoundFinished -= OnRoundFinished;
_camera.FrameArrived -= OnCameraFrame;
@ -986,6 +988,13 @@ public class SopPageViewModel : ViewModelBase
/// <summary>按当前运行状态停止或启动;启动时依次应用配方、连接设备、设置参数和开启管线。</summary>
private async Task StartStopCoreAsync()
{
if (_standardSopCancellation is { } video)
{
video.Cancel();
await _standardSopTask;
return;
}
if (IsRunning)
{
await Task.Run(() =>
@ -1124,11 +1133,14 @@ public class SopPageViewModel : ViewModelBase
/// <summary>原图只在管线回调内有效,先克隆再投递 UI;在该帧判定和取证结束后释放克隆。</summary>
private void OnResultFrame(FrameResult result, Mat frame)
{
var videoRound = Volatile.Read(ref _videoRound);
var owned = frame.Clone();
_dispatcher.BeginInvoke(() =>
{
using (owned)
{
// 后台结果可能在切换来源或重播后才到达界面,必须丢弃旧轮次。
if (videoRound != _videoRound || _standardSopCancellation?.IsCancellationRequested == true) return;
_judgementFrame = owned;
try { OnResult(result); }
finally { _judgementFrame = null; }
@ -1248,28 +1260,136 @@ public class SopPageViewModel : ViewModelBase
}
}
private StandardSopWindow? _standardSopWindow;
private readonly RecordedVideoPlayback _standardSop = new();
private CancellationTokenSource? _standardSopCancellation;
private Task _standardSopTask = Task.CompletedTask;
private int _videoRound;
/// <summary>预览区域在视频会话中显示播放器持有的位图,其余时间显示相机位图。</summary>
public ImageSource? PreviewFrame => _standardSopCancellation is null ? Frame : _standardSop.Frame;
public string StandardSopButtonText => _standardSopCancellation is null ? "播放标准 SOP" : "停止标准 SOP";
private string? StandardSopVideoPath => string.IsNullOrWhiteSpace(ActiveRecipe) || ActiveRecipe == "未应用配方" ? null
: Path.Combine(DesktopPlatform.Recipes.DirectoryFor(Path.GetFileNameWithoutExtension(ActiveRecipe)), "sop_stand", "sop.avi");
/// <summary>复用当前配方已打开的视频窗口;配方变化时关闭旧窗口并打开对应标准视频。</summary>
private void PlayStandardSop()
/// <summary>使用当前已应用的配方播放并检测;如果正在采集,先停止相机采集再切换来源。</summary>
private async Task ToggleStandardSopAsync()
{
if (StandardSopVideoPath is not { } path || !File.Exists(path))
SetCameraBusy(true);
try
{
Log("warn", "当前配方没有标准 SOP 视频,请先录制或导入视频");
PlayStandardSopCommand.RaiseCanExecuteChanged();
return;
if (_standardSopCancellation is not null)
{
await StartStopCoreAsync();
return;
}
if (StandardSopVideoPath is not { } path || !File.Exists(path)) return;
if (IsRunning) await StartStopCoreAsync();
if (_destroyed) return;
var cancellation = new CancellationTokenSource();
_standardSopCancellation = cancellation;
lock (_frameLock)
{
_pending?.Dispose();
_pending = null;
_lastFrame = null;
}
RaisePropertyChanged(nameof(PreviewFrame));
RaisePropertyChanged(nameof(StandardSopButtonText));
_standardSopTask = RunStandardSopAsync(path, cancellation);
}
if (_standardSopWindow is { IsVisible: true } existing && existing.VideoPath == path)
catch (Exception error) { Log("warn", "切换标准 SOP 视频失败:" + error.Message); }
finally { if (!_destroyed) SetCameraBusy(false); }
}
/// <summary>每次从头播放时启动新检测轮次;片尾留出五秒,并在此期间收尾已提交的判定。</summary>
private async Task RunStandardSopAsync(string path, CancellationTokenSource cancellation)
{
var token = cancellation.Token;
var settings = _engine.Config.Sop.Settings;
var autoReset = settings.AutoResetOnComplete;
TaskCompletionSource end = new(TaskCreationOptions.RunContinuationsAsynchronously);
void PlaybackChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs args)
{
existing.Activate();
return;
if (args.PropertyName == nameof(RecordedVideoPlayback.IsAtEnd) && _standardSop.IsAtEnd)
end.TrySetResult();
if (args.PropertyName != nameof(RecordedVideoPlayback.Frame) || _destroyed) return;
if (_standardSop.Frame is { } frame)
{
FrameWidth = frame.PixelWidth;
FrameHeight = frame.PixelHeight;
}
RaisePropertyChanged(nameof(PreviewFrame));
}
void PlaybackFailed(string message) => end.TrySetException(new IOException(message));
try
{
// 重播是唯一的自动复位点,避免一次视频播放中途重新开始检测。
settings.AutoResetOnComplete = false;
_pipeline.SetFrameStride(FrameStride);
_standardSop.FrameProcessor = (frame, id, _) => _pipeline.SubmitVideoFrame(frame, id);
_standardSop.PropertyChanged += PlaybackChanged;
_standardSop.Failed += PlaybackFailed;
IsRunning = true;
while (true)
{
token.ThrowIfCancellationRequested();
end = new(TaskCreationOptions.RunContinuationsAsynchronously);
Interlocked.Increment(ref _videoRound);
_lastFrame = null;
HandResult = null;
_engine.Start();
_pipeline.StartVideoInput();
StatusText = "正在播放标准 SOP 并检测";
await _standardSop.PlayAsync(path);
await end.Task.WaitAsync(token);
var pause = Stopwatch.StartNew();
StatusText = "标准 SOP 播放结束,5 秒后重播";
// 等待期间没有新画面,只轮询已提交的 AI 判定,不使用片尾画面重新取证。
while (pause.Elapsed < TimeSpan.FromSeconds(5))
{
var remaining = TimeSpan.FromSeconds(5) - pause.Elapsed;
if (remaining <= TimeSpan.Zero) break;
await Task.Delay(TimeSpan.FromMilliseconds(Math.Min(remaining.TotalMilliseconds, 50)), token);
if (_engine.HasPendingDecision && _lastFrame is { } last) _engine.ProcessFrame(last);
}
_pipeline.StopVideoInput();
}
}
catch (OperationCanceledException) when (token.IsCancellationRequested) { }
catch (Exception error) { if (!_destroyed) Log("warn", "标准 SOP 播放或检测失败:" + error.Message); }
finally
{
if (!_destroyed) _pipeline.StopVideoInput();
Interlocked.Increment(ref _videoRound);
_standardSop.PropertyChanged -= PlaybackChanged;
_standardSop.Failed -= PlaybackFailed;
await _standardSop.StopAsync();
_standardSop.FrameProcessor = null;
settings.AutoResetOnComplete = autoReset;
if (!_destroyed)
{
_standardSopCancellation = null;
_lastFrame = null;
IsRunning = false;
if (Frame is BitmapSource cameraFrame)
{
FrameWidth = cameraFrame.PixelWidth;
FrameHeight = cameraFrame.PixelHeight;
}
RaisePropertyChanged(nameof(PreviewFrame));
RaisePropertyChanged(nameof(StandardSopButtonText));
StatusText = token.IsCancellationRequested ? "已停止标准 SOP 播放" : "标准 SOP 播放结束";
}
else _standardSopCancellation = null;
cancellation.Dispose();
}
_standardSopWindow?.Close();
var window = _standardSopWindow = new StandardSopWindow(path, Path.GetFileNameWithoutExtension(ActiveRecipe));
window.Closed += (_, _) => { if (ReferenceEquals(_standardSopWindow, window)) _standardSopWindow = null; };
window.Show(DesktopPlatform.Owner);
}
private void ResetCounts()

View File

@ -1,18 +0,0 @@
<Window xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="SopHelper.VVMs.SopPage.StandardSopWindow" Title="标准 SOP"
Width="900" Height="640" MinWidth="600" MinHeight="400" Background="{StaticResource Bg}" WindowStartupLocation="CenterOwner">
<Grid Margin="16" RowDefinitions="Auto,*,Auto,Auto">
<TextBlock x:Name="RecipeTitle" Classes="Title" Margin="0,0,0,12" />
<Border Grid.Row="1" Classes="panel" Background="#080E14" Padding="0">
<Image Source="{Binding Frame}" Stretch="Uniform" />
</Border>
<Grid Grid.Row="2" ColumnDefinitions="Auto,*,Auto,Auto" Margin="0,12,0,0">
<Button x:Name="PlaybackToggleButton" Content="播放" Click="TogglePlayback" />
<Slider x:Name="PlaybackSeekSlider" Grid.Column="1" Minimum="0" Maximum="100" Value="{Binding Progress, Mode=TwoWay}"
IsEnabled="{Binding IsLoaded}" VerticalAlignment="Center" Margin="12,0" />
<TextBlock Grid.Column="2" Text="{Binding TimeText}" Margin="0,0,12,0" />
<Button Grid.Column="3" Content="关闭" Click="ClosePlayback" />
</Grid>
<TextBlock x:Name="PlaybackErrorText" Grid.Row="3" TextWrapping="Wrap" Foreground="{StaticResource Ng}" Margin="0,8,0,0" />
</Grid>
</Window>

View File

@ -1,65 +0,0 @@
// 标准 SOP 视频窗口:封装播放器的显示、进度及窗口关闭时的资源清理。
using Avalonia.Controls;
using Avalonia.Interactivity;
using SopHelper.SopVideo;
namespace SopHelper.VVMs.SopPage;
public partial class StandardSopWindow : Window
{
public string VideoPath { get; }
public RecordedVideoPlayback Playback { get; } = new();
private Task _playOperation = Task.CompletedTask;
private bool _closeRequested, _closedSafely;
public StandardSopWindow(string videoPath, string recipeName)
{
InitializeComponent();
VideoPath = videoPath;
Title = "标准 SOP · " + recipeName;
RecipeTitle.Text = recipeName + " · 标准 SOP";
DataContext = Playback;
Playback.Failed += message => PlaybackErrorText.Text = message;
Playback.PropertyChanged += (_, e) =>
{
if (e.PropertyName is nameof(Playback.IsPlaying) or nameof(Playback.IsAtEnd))
PlaybackToggleButton.Content = Playback.IsPlaying ? "暂停播放" : Playback.IsAtEnd ? "重新播放" : "播放";
};
Opened += (_, _) => _playOperation = PlayAsync();
Closing += OnSafeClosing;
}
private async Task PlayAsync()
{
PlaybackToggleButton.IsEnabled = false;
PlaybackErrorText.Text = "";
try { await Playback.PlayAsync(VideoPath); }
catch (Exception error)
{
await Playback.StopAsync();
PlaybackErrorText.Text = "标准 SOP 视频无法播放:" + error.Message;
}
finally { if (!_closeRequested) PlaybackToggleButton.IsEnabled = true; }
}
private void TogglePlayback(object? sender, RoutedEventArgs e)
{
if (_closeRequested) return;
if (Playback.IsPlaying) Playback.Pause();
else _playOperation = PlayAsync();
}
private void ClosePlayback(object? sender, RoutedEventArgs e) => Close();
private async void OnSafeClosing(object? sender, WindowClosingEventArgs e)
{
if (_closedSafely) return;
e.Cancel = true;
if (_closeRequested) return;
_closeRequested = true;
PlaybackToggleButton.IsEnabled = false;
try { await _playOperation; await Playback.StopAsync(); }
finally { _closedSafely = true; Close(); }
}
}

View File

@ -51,6 +51,7 @@ public class DetectionPipeline : IDisposable
private CancellationTokenSource? _processingCancellation;
private Task? _processingTask;
private bool _acceptFrames;
private bool _externalInput;
/// <summary>管线就绪度(缺哪个模型就在这里报告,界面据此提示)</summary>
public List<string> Warnings { get; private set; } = [];
@ -124,6 +125,24 @@ public class DetectionPipeline : IDisposable
/// <summary>先创建可取消的后台处理循环,再启动相机;启动失败时同步回收处理循环。</summary>
public async Task<bool> StartAsync()
{
StartProcessing(externalInput: false);
try
{
if (await _camera.StartAsync()) return true;
StopProcessing();
return false;
}
catch { StopProcessing(); throw; }
}
/// <summary>开启视频帧检测,复用实时推理模型,不启动相机。</summary>
public void StartVideoInput() => StartProcessing(externalInput: true);
/// <summary>停止视频帧推理并等待后台释放当前帧,不操作相机连接。</summary>
public void StopVideoInput() => StopProcessing();
private void StartProcessing(bool externalInput)
{
ObjectDisposedException.ThrowIf(_disposed, this);
StopProcessing();
@ -133,15 +152,12 @@ public class DetectionPipeline : IDisposable
ResultFps = 0;
_processingCancellation = new CancellationTokenSource();
var token = _processingCancellation.Token;
lock (_frameGate) _acceptFrames = true;
_processingTask = Task.Run(() => ProcessLoopAsync(token));
try
lock (_frameGate)
{
if (await _camera.StartAsync()) return true;
StopProcessing();
return false;
_externalInput = externalInput;
_acceptFrames = true;
}
catch { StopProcessing(); throw; }
_processingTask = Task.Run(() => ProcessLoopAsync(token));
}
/// <summary>
@ -196,12 +212,20 @@ public class DetectionPipeline : IDisposable
/// 采集回调:按 stride 抽帧,将选中帧的克隆交给后台推理循环。
/// </summary>
/// <remarks>仅执行抽帧和克隆入槽,不在相机回调中推理;替换时立即释放旧待处理帧。</remarks>
private void OnFrame(CameraFrame frame)
private void OnFrame(CameraFrame frame) =>
QueueFrame(frame.Bgr, frame.FrameId, frame.Timestamp, externalInput: false);
/// <summary>提交解码原帧;管线仅克隆通过抽帧的图像,调用方保留原图所有权。</summary>
public void SubmitVideoFrame(Mat image, long frameId) =>
QueueFrame(image, frameId, DateTime.Now, externalInput: true);
/// <summary>只接收当前来源的帧,避免相机与视频在同一轮检测中混用。</summary>
private void QueueFrame(Mat image, long frameId, DateTime timestamp, bool externalInput)
{
lock (_frameGate)
{
if (!_acceptFrames || ++_seen % Math.Max(1, _options.FrameStride) != 0) return;
var copy = new CameraFrame { FrameId = frame.FrameId, Timestamp = frame.Timestamp, Bgr = frame.Bgr.Clone() };
if (!_acceptFrames || _externalInput != externalInput || ++_seen % Math.Max(1, _options.FrameStride) != 0) return;
var copy = new CameraFrame { FrameId = frameId, Timestamp = timestamp, Bgr = image.Clone() };
_pendingFrame?.Dispose();
_pendingFrame = copy;
if (_frameSignal.CurrentCount == 0) _frameSignal.Release();

View File

@ -91,6 +91,21 @@ pipeline.Stop();
if(results.Last()!=14||results.Count!=4)throw new Exception("Frame stride was not preserved");
Console.WriteLine("PASS: Frame stride is preserved by the asynchronous worker");
// 视频模式应排除相机帧,且解码方可以在提交后立即释放原图。
pipeline.StartVideoInput();
if (camera.IsGrabbing) throw new Exception("Video input started camera capture");
camera.Emit(15);
using (var video = new Mat(24, 40, MatType.CV_8UC3, Scalar.Black))
{
pipeline.SubmitVideoFrame(video, 16);
pipeline.SubmitVideoFrame(video, 17);
}
for (var i = 0; i < 100 && imageResults.Count < 5; i++) await Task.Delay(10);
pipeline.StopVideoInput();
if (results.Count != 5 || results.Last() != 17 || !imageResults.SequenceEqual(results))
throw new Exception("Video input did not isolate sources or preserve stride and frame ownership");
Console.WriteLine("PASS: Video input isolates sources and uses the regular inference worker");
internal sealed class TestCamera : ICameraService
{
public bool IsConnected => true;