From f1783f321dc388ab2c478161074939104898e92d Mon Sep 17 00:00:00 2001 From: sophelper <123211521@163.com> Date: Sat, 7 Nov 2026 09:09:04 +0800 Subject: [PATCH] Integrate PartTrainer workflow into SopHelper --- .gitignore | 8 +- README.md | 33 +- src/SopHelper.App/App.xaml.cs | 7 +- src/SopHelper.App/SopHelper.App.csproj | 5 + .../Training/AnnotationCanvas.cs | 67 +++ src/SopHelper.App/Training/CameraViewModel.cs | 288 +++++++++++ src/SopHelper.App/Training/CameraWindow.xaml | 39 ++ .../Training/CameraWindow.xaml.cs | 27 + src/SopHelper.App/Training/MainViewModel.cs | 367 ++++++++++++++ .../Training/ModelTestViewModel.cs | 114 +++++ .../Training/ModelTestWindow.xaml | 27 + .../Training/ModelTestWindow.xaml.cs | 23 + src/SopHelper.App/Training/Styles.xaml | 32 ++ src/SopHelper.App/Training/TrainingPage.xaml | 78 +++ .../Training/TrainingPage.xaml.cs | 94 ++++ src/SopHelper.Engine/Camera/VideoRecorder.cs | 110 ++++ src/SopHelper.Engine/Training/Project.cs | 62 +++ src/SopHelper.Engine/Training/WorkerClient.cs | 74 +++ tests/Training.CameraSmoke/Program.cs | 191 +++++++ .../Training.CameraSmoke.csproj | 4 + tests/Training.ShellSmoke/Program.cs | 77 +++ .../Training.ShellSmoke.csproj | 4 + tests/Training.Smoke/Program.cs | 45 ++ tests/Training.Smoke/Training.Smoke.csproj | 1 + tests/Training.UiSmoke/Program.cs | 112 +++++ .../Training.UiSmoke/Training.UiSmoke.csproj | 1 + tests/test_worker.py | 87 ++++ tools/Setup-Python.ps1 | 26 + tools/requirements.txt | 7 + tools/worker.py | 476 ++++++++++++++++++ 30 files changed, 2483 insertions(+), 3 deletions(-) create mode 100644 src/SopHelper.App/Training/AnnotationCanvas.cs create mode 100644 src/SopHelper.App/Training/CameraViewModel.cs create mode 100644 src/SopHelper.App/Training/CameraWindow.xaml create mode 100644 src/SopHelper.App/Training/CameraWindow.xaml.cs create mode 100644 src/SopHelper.App/Training/MainViewModel.cs create mode 100644 src/SopHelper.App/Training/ModelTestViewModel.cs create mode 100644 src/SopHelper.App/Training/ModelTestWindow.xaml create mode 100644 src/SopHelper.App/Training/ModelTestWindow.xaml.cs create mode 100644 src/SopHelper.App/Training/Styles.xaml create mode 100644 src/SopHelper.App/Training/TrainingPage.xaml create mode 100644 src/SopHelper.App/Training/TrainingPage.xaml.cs create mode 100644 src/SopHelper.Engine/Camera/VideoRecorder.cs create mode 100644 src/SopHelper.Engine/Training/Project.cs create mode 100644 src/SopHelper.Engine/Training/WorkerClient.cs create mode 100644 tests/Training.CameraSmoke/Program.cs create mode 100644 tests/Training.CameraSmoke/Training.CameraSmoke.csproj create mode 100644 tests/Training.ShellSmoke/Program.cs create mode 100644 tests/Training.ShellSmoke/Training.ShellSmoke.csproj create mode 100644 tests/Training.Smoke/Program.cs create mode 100644 tests/Training.Smoke/Training.Smoke.csproj create mode 100644 tests/Training.UiSmoke/Program.cs create mode 100644 tests/Training.UiSmoke/Training.UiSmoke.csproj create mode 100644 tests/test_worker.py create mode 100644 tools/Setup-Python.ps1 create mode 100644 tools/requirements.txt create mode 100644 tools/worker.py diff --git a/.gitignore b/.gitignore index aaddcb4..4eed81a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,4 @@ -## Ignore Visual Studio temporary files, build results, and +## Ignore Visual Studio temporary files, build results, and ## files generated by popular Visual Studio add-ons. ## ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore @@ -392,3 +392,9 @@ FodyWeavers.xsd !/libs/MvCameraControl.Net.dll /libs/cuda/ /models + +# Training environments and generated data +/.venv/ +/.cache/ +/workspace/ +*.pt diff --git a/README.md b/README.md index 62f6632..96fe17a 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # SopHelper — 单相机 SOP 辅助 工位上接一个 UVC 或海康工业相机,程序按 YAML 配方定义的步骤顺序判定操作员动作:逐步打勾、 -超时报违规、留日志和快照。只做一件事,不做大而全。 +超时报违规、留日志和快照。侧栏的「零件标注与训练」集成 PartTrainer 的采集、标注与模型训练流程。 引擎逻辑移植自 [VisionInspectionSystem](https://github.com/TheDoorIsUnlocked/VisionInspectionSystem)(MIT)。 @@ -106,6 +106,37 @@ dotnet run --project tests/ShutdownSmoke/ShutdownSmoke.csproj dotnet run --project tests/ShutdownSmoke/ShutdownSmoke.csproj -- --hardware ``` +## 零件标注与训练 + +侧栏「零件标注与训练」包含原 PartTrainer 的完整工作流:相机录像、导入视频与抽帧、手工画框、SAM2 双向传播、逐帧或一键复核、负样本与排除帧、YOLO 数据集导出、训练与 ONNX 导出、视频模型测试,以及可选视觉 API 建议框。切换到 SOP 页再返回会保留当前项目及任务。 + +首次使用 Python 功能,在 SopHelper 根目录执行: + +```powershell +powershell -ExecutionPolicy Bypass -File tools/Setup-Python.ps1 -Sam2 +# CPU 环境附加 -Cpu +``` + +程序优先使用本项目 `.venv/Scripts/python.exe`,也可在「设置」填写已有 PartTrainer 的 Python 完整路径来复用环境。相机预览和录像不需要 Python。设置保存在 `workspace/settings.json`,录像默认保存在 `workspace/recordings`;API Key 不保存到配置或日志。原 PartTrainer 的 `project.json` 可直接打开,项目中原有的绝对视频、权重路径需要仍然有效。集成后的源码、Python worker 和安装脚本均在本仓库内,构建与发布无需 PartTrainer 目录。 + +相机录像窗口以模态打开;SOP 正在运行或操作相机时会提示先停止,避免两个流程同时占用设备。关闭采集窗口会结束并封装录像。关闭主窗口时会取消后台 Python 任务、等待进程退出并释放相机;即使已切回 SOP 页面也会清理。 + +标注目前支持单目标、单类别矩形框。导出只包含已复核正样本和明确标记的无目标帧,按时间划分训练与验证并保留间隔。单段视频的指标用于验证流程,实际效果需使用独立现场视频评估。 + +训练后点击「导出最新模型为 ONNX」,在 SOP 配方编辑器「检测模型」选择导出的 ONNX;类别表可留空以读取模型元数据,也可提供对应类别表。导出采用固定尺寸、opset 17、无内置 NMS。原 PartTrainer 项目保留,可继续独立运行。 + +Python 依赖中的 Ultralytics 使用 AGPL-3.0 / 商业许可;SAM2 使用其上游许可。部署时需遵守所选依赖与模型的许可。 + +集成回归检查: + +```powershell +dotnet run --project tests/Training.Smoke +dotnet run --project tests/Training.UiSmoke +dotnet run --project tests/Training.CameraSmoke +dotnet run --project tests/Training.ShellSmoke +.venv/Scripts/python.exe -X utf8 -m unittest discover -s tests -p test_worker.py -v +``` + ## 配方 `configs/sop/*.yaml`,写好的例子见 `configs/sop/demo.yaml`。 diff --git a/src/SopHelper.App/App.xaml.cs b/src/SopHelper.App/App.xaml.cs index 9a80978..d8e63bb 100644 --- a/src/SopHelper.App/App.xaml.cs +++ b/src/SopHelper.App/App.xaml.cs @@ -22,6 +22,7 @@ public partial class App { private ICameraService? _camera; private DetectionPipeline? _pipeline; + private Engine.Training.WorkerClient? _trainingWorker; /// /// 注册应用程序所需的类型和服务 @@ -58,7 +59,10 @@ public partial class App _ = containerRegistry.RegisterSingleton(); // ViewModel 工厂默认走容器解析,带构造注入的 ViewModel 必须先注册 - _ = containerRegistry.Register(); + _ = containerRegistry.RegisterSingleton(); + _trainingWorker = new Engine.Training.WorkerClient(); + containerRegistry.RegisterInstance(_trainingWorker); + containerRegistry.RegisterSingleton(); // 配方编辑器弹窗(SOP 页「编辑」「新建」按钮弹出) containerRegistry.RegisterDialog("RecipeEditorDialog"); @@ -101,6 +105,7 @@ public partial class App { try { + _trainingWorker?.Dispose(); // Dispose 等待采集线程退出、归还缓冲并关闭设备,然后才能释放推理模型。 try { _camera?.Dispose(); } catch (Exception ex) { Log(ex, "Exit.Camera"); } diff --git a/src/SopHelper.App/SopHelper.App.csproj b/src/SopHelper.App/SopHelper.App.csproj index d86eaa5..ae4e5ab 100644 --- a/src/SopHelper.App/SopHelper.App.csproj +++ b/src/SopHelper.App/SopHelper.App.csproj @@ -33,4 +33,9 @@ + + + + + diff --git a/src/SopHelper.App/Training/AnnotationCanvas.cs b/src/SopHelper.App/Training/AnnotationCanvas.cs new file mode 100644 index 0000000..2a1f54a --- /dev/null +++ b/src/SopHelper.App/Training/AnnotationCanvas.cs @@ -0,0 +1,67 @@ +using System.Windows; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Imaging; + +namespace SopHelper.Training; + +/// Aspect-fit preview with original-image coordinates, including letterbox offsets. +public sealed class AnnotationCanvas : FrameworkElement +{ + public static readonly DependencyProperty SourceProperty = DependencyProperty.Register(nameof(Source), typeof(BitmapSource), typeof(AnnotationCanvas), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender)); + public static readonly DependencyProperty BoxProperty = DependencyProperty.Register(nameof(Box), typeof(double[]), typeof(AnnotationCanvas), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender)); + public BitmapSource? Source { get => (BitmapSource?)GetValue(SourceProperty); set => SetValue(SourceProperty, value); } + public double[]? Box { get => (double[]?)GetValue(BoxProperty); set => SetValue(BoxProperty, value); } + public event Action? BoxDrawn; + private Point? _start; + private Point _end; + public AnnotationCanvas() { ClipToBounds = true; Cursor = Cursors.Cross; Focusable = true; } + private Rect ImageRect + { + get + { + if (Source == null) return Rect.Empty; + var scale = Math.Min(ActualWidth / Source.PixelWidth, ActualHeight / Source.PixelHeight); + var w = Source.PixelWidth * scale; var h = Source.PixelHeight * scale; + return new Rect((ActualWidth - w) / 2, (ActualHeight - h) / 2, w, h); + } + } + protected override void OnRender(DrawingContext dc) + { + dc.DrawRectangle(Brushes.Transparent, null, new Rect(RenderSize)); + var image = ImageRect; + if (Source == null || image.IsEmpty) return; + dc.DrawImage(Source, image); + var pen = new Pen(new SolidColorBrush(Color.FromRgb(0, 220, 220)), 2); + if (Box is { Length: 4 } b) + { + var scale = image.Width / Source.PixelWidth; + dc.DrawRectangle(new SolidColorBrush(Color.FromArgb(30, 0, 220, 220)), pen, + new Rect(image.X + b[0]*scale, image.Y + b[1]*scale, (b[2]-b[0])*scale, (b[3]-b[1])*scale)); + } + if (_start is { } start) dc.DrawRectangle(null, new Pen(Brushes.Yellow, 2), new Rect(start, _end)); + } + protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e) + { + if (!IsEnabled || Source == null || !ImageRect.Contains(e.GetPosition(this))) return; + Focus(); _start = _end = e.GetPosition(this); CaptureMouse(); InvalidateVisual(); e.Handled = true; + } + protected override void OnMouseMove(MouseEventArgs e) + { + if (_start == null) return; + var p = e.GetPosition(this); var image = ImageRect; + _end = new Point(Math.Clamp(p.X, image.Left, image.Right), Math.Clamp(p.Y, image.Top, image.Bottom)); + InvalidateVisual(); + } + protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e) + { + if (_start is not { } start || Source == null) return; + var rectangle = new Rect(start, _end); var image = ImageRect; + _start = null; ReleaseMouseCapture(); InvalidateVisual(); + if (rectangle.Width < 3 || rectangle.Height < 3 || image.Width <= 0) return; + var scale = Source.PixelWidth / image.Width; + BoxDrawn?.Invoke([(rectangle.Left-image.Left)*scale, (rectangle.Top-image.Top)*scale, + Math.Min(Source.PixelWidth, (rectangle.Right-image.Left)*scale), Math.Min(Source.PixelHeight, (rectangle.Bottom-image.Top)*scale)]); + } + protected override void OnLostMouseCapture(MouseEventArgs e) { _start = null; InvalidateVisual(); base.OnLostMouseCapture(e); } +} diff --git a/src/SopHelper.App/Training/CameraViewModel.cs b/src/SopHelper.App/Training/CameraViewModel.cs new file mode 100644 index 0000000..6866ac5 --- /dev/null +++ b/src/SopHelper.App/Training/CameraViewModel.cs @@ -0,0 +1,288 @@ +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.IO; +using System.Text.Json; +using System.Windows; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Threading; +using Microsoft.Win32; +using OpenCvSharp; +using SopHelper.Engine.Camera; +using Prism.Commands; +using Prism.Mvvm; + +namespace SopHelper.Training; + +public sealed class CameraViewModel : BindableBase +{ + private readonly ICameraService _camera; + private readonly VideoRecorder _recorder = new(); + private readonly object _frames = new(); + private readonly Dispatcher _dispatcher; + private readonly DispatcherTimer _timer; + private readonly string _settingsPath; + private readonly Stopwatch _previewClock = Stopwatch.StartNew(); + private Mat? _latest; + private int _previewPending; + private int _generation; + private long _lastFrameTick; + private volatile bool _closing; + private bool _busy, _previewing, _recording; + private string _status = "刷新设备列表,选择相机后开启预览"; + private string _directory; + private string _lastRecording = ""; + private string _recordingInfo = "未录像"; + private CameraInfo? _selected; + private BitmapSource? _preview; + private Task _operation = Task.CompletedTask; + private Task? _shutdown; + private readonly List _commands = []; + + public ObservableCollection Cameras { get; } = []; + public CameraInfo? SelectedCamera { get => _selected; set { SetProperty(ref _selected, value); UpdateCommands(); } } + public BitmapSource? Preview { get => _preview; private set => SetProperty(ref _preview, value); } + public string Status { get => _status; private set => SetProperty(ref _status, value); } + public bool IsBusy { get => _busy; private set { SetProperty(ref _busy, value); StateChanged(); } } + public bool IsPreviewing { get => _previewing; private set { SetProperty(ref _previewing, value); StateChanged(); } } + public bool IsRecording { get => _recording; private set { SetProperty(ref _recording, value); StateChanged(); } } + public bool CanChooseCamera => !IsBusy && !IsPreviewing && !_closing; + public bool CanChangeDirectory => !IsBusy && !IsRecording && !_closing; + public string PreviewButtonText => IsPreviewing ? "关闭相机" : "开启相机预览"; + public string RecordButtonText => IsRecording ? "停止录像" : "开始录像"; + public string RecordingInfo { get => _recordingInfo; private set => SetProperty(ref _recordingInfo, value); } + public string SaveDirectory { get => _directory; set => SetProperty(ref _directory, value); } + public string LastRecording { get => _lastRecording; private set { SetProperty(ref _lastRecording, value); UpdateCommands(); } } + public double RecordingFps { get; set; } = 30; + public DelegateCommand RefreshCommand { get; } + public DelegateCommand PreviewCommand { get; } + public DelegateCommand RecordCommand { get; } + public DelegateCommand BrowseCommand { get; } + public DelegateCommand RevealCommand { get; } + + public CameraViewModel(ICameraService camera, string root) + { + _camera = camera; _dispatcher = Application.Current.Dispatcher; + _directory = Path.Combine(root, "workspace", "recordings"); + _settingsPath = Path.Combine(root, "workspace", "camera-settings.json"); + try + { + if (File.Exists(_settingsPath)) + { + using var json = JsonDocument.Parse(File.ReadAllText(_settingsPath)); + SaveDirectory = json.RootElement.GetProperty("directory").GetString() ?? _directory; + } + } + catch (Exception e) { Status = "录像目录配置读取失败:" + e.Message; } + RefreshCommand = Command(RefreshAsync, () => CanChooseCamera); + PreviewCommand = Command(TogglePreviewAsync, () => !IsBusy && !_closing && (IsPreviewing || SelectedCamera != null)); + RecordCommand = Command(ToggleRecordingAsync, () => !IsBusy && !_closing && (IsRecording || (IsPreviewing && Preview != null && HasRecentFrame))); + BrowseCommand = Command(() => + { + var picker = new OpenFolderDialog { Title = "选择录像保存目录" }; + if (Directory.Exists(SaveDirectory)) picker.InitialDirectory = SaveDirectory; + if (picker.ShowDialog() == true) { SaveDirectory = picker.FolderName; SaveSettings(); } + return Task.CompletedTask; + }, () => CanChangeDirectory); + RevealCommand = Command(() => + { + if (!string.IsNullOrEmpty(LastRecording) && File.Exists(LastRecording)) + { + var info = new ProcessStartInfo("explorer.exe") { UseShellExecute = true }; + info.ArgumentList.Add("/select," + LastRecording); Process.Start(info); + } + else + { + Directory.CreateDirectory(SaveDirectory); + var info = new ProcessStartInfo("explorer.exe") { UseShellExecute = true }; + info.ArgumentList.Add(Path.GetFullPath(SaveDirectory)); Process.Start(info); + } + return Task.CompletedTask; + }, () => !IsBusy && !_closing); + _camera.FrameArrived += OnFrame; + _camera.ConnectionChanged += OnConnection; + _camera.Error += OnError; + _timer = new DispatcherTimer(TimeSpan.FromMilliseconds(250), DispatcherPriority.Background, (_, _) => Tick(), _dispatcher); + _timer.Start(); + } + + private DelegateCommand Command(Func action, Func canExecute) + { + var command = new DelegateCommand(() => _operation = PerformAsync(action), canExecute); + _commands.Add(command); return command; + } + private async Task PerformAsync(Func action) + { + if (IsBusy || _closing) return; + IsBusy = true; + try { await action(); } + catch (Exception e) { Status = e.Message; } + finally { IsBusy = false; } + } + private void UpdateCommands() { foreach (var command in _commands) command.RaiseCanExecuteChanged(); } + private void StateChanged() + { + RaisePropertyChanged(nameof(CanChooseCamera)); RaisePropertyChanged(nameof(CanChangeDirectory)); + RaisePropertyChanged(nameof(PreviewButtonText)); RaisePropertyChanged(nameof(RecordButtonText)); UpdateCommands(); + } + private async Task RefreshAsync() + { + Status = "正在枚举 UVC / 海康相机…"; + var devices = await _camera.EnumerateAsync(); + if (_closing) return; + Cameras.Clear(); foreach (var device in devices) Cameras.Add(device); + SelectedCamera = Cameras.FirstOrDefault(); + Status = Cameras.Count == 0 ? "未找到相机,请检查连接;海康设备需要 MVS x64 运行时" : $"找到 {Cameras.Count} 台相机"; + } + private async Task TogglePreviewAsync() + { + if (IsPreviewing) + { + StopRecording(); + await Task.Run(_camera.Disconnect); + ClearPreview(); IsPreviewing = false; Status = "相机已关闭"; + return; + } + var selected = SelectedCamera ?? throw new InvalidOperationException("请选择相机"); + Status = "正在连接 " + selected.Name; + if (!await _camera.ConnectAsync(selected)) throw new IOException("相机连接失败,请检查设备是否被其他程序占用"); + if (_closing) return; + if (!await _camera.StartAsync()) + { + await Task.Run(_camera.Disconnect); + throw new IOException("相机已连接,但采集启动失败"); + } + IsPreviewing = true; Status = "相机预览中,可开始录像"; + } + private Task ToggleRecordingAsync() + { + if (IsRecording) { StopRecording(); return Task.CompletedTask; } + if (string.IsNullOrWhiteSpace(SaveDirectory)) throw new ArgumentException("请选择录像保存目录"); + var directory = Path.GetFullPath(SaveDirectory.Trim()); + SaveDirectory = directory; SaveSettings(); + lock (_frames) + { + if (_latest == null || !_camera.IsGrabbing) throw new InvalidOperationException("尚未收到相机画面,请先开启预览"); + if (Stopwatch.GetElapsedTime(_lastFrameTick).TotalSeconds > 2) throw new IOException("超过2秒未收到相机画面,请重新连接后再录像"); + LastRecording = _recorder.Start(directory, _latest, RecordingFps); + } + IsRecording = true; Status = "正在录像,点击“停止录像”保存文件"; Tick(); + return Task.CompletedTask; + } + private void StopRecording() + { + RecordingResult? result; + lock (_frames) result = _recorder.Stop(); + IsRecording = false; + if (result != null) + { + LastRecording = result.Path; + RecordingInfo = $"已保存 · {result.Duration.TotalSeconds:F1} 秒 · {result.Frames} 帧"; + Status = "录像已保存,可在主窗口导入视频继续标注"; + } + } + private void OnFrame(CameraFrame frame) + { + if (_closing) return; + BitmapSource? preview = null; + string? recordingError = null; + var generation = Volatile.Read(ref _generation); + lock (_frames) + { + if (_closing) return; + Interlocked.Exchange(ref _lastFrameTick, Stopwatch.GetTimestamp()); + if (_latest == null) _latest = frame.Bgr.Clone(); else frame.Bgr.CopyTo(_latest); + try { _recorder.Write(frame.Bgr); } + catch (Exception e) { recordingError = "录像中断:" + e.Message + ";已写入内容保存在 " + _recorder.CurrentPath; } + if (_previewClock.ElapsedMilliseconds >= 66 && Interlocked.CompareExchange(ref _previewPending, 1, 0) == 0) + { + try + { + var stride = checked((int)frame.Bgr.Step()); + preview = BitmapSource.Create(frame.Bgr.Width, frame.Bgr.Height, 96, 96, PixelFormats.Bgr24, + null, frame.Bgr.Data, checked(stride * frame.Bgr.Height), stride); + preview.Freeze(); _previewClock.Restart(); + } + catch { Interlocked.Exchange(ref _previewPending, 0); throw; } + } + } + if (recordingError != null) + { + var error = recordingError; + Post(() => { IsRecording = false; Status = error; RecordingInfo = "录像中断,请检查日志提示"; }); + } + if (preview != null) + { + var bitmap = preview; + Post(() => + { + try + { + if (generation == Volatile.Read(ref _generation)) { Preview = bitmap; UpdateCommands(); } + } + finally { Interlocked.Exchange(ref _previewPending, 0); } + }); + } + } + private void OnConnection(bool connected) + { + if (!connected) Post(() => + { + if (_camera.IsConnected) return; // Ignore a queued disconnect from the previous connection. + StopRecording(); IsPreviewing = false; ClearPreview(); + }); + } + private void OnError(string message) => Post(() => Status = message); + private void Post(Action action) + { + if (!_closing && !_dispatcher.HasShutdownStarted) + _dispatcher.BeginInvoke(() => { if (!_closing) action(); }, DispatcherPriority.Background); + } + private void Tick() + { + if (_closing) return; + if (IsRecording) + { + if (Stopwatch.GetElapsedTime(Interlocked.Read(ref _lastFrameTick)).TotalSeconds > 2) + { + StopRecording(); Status = "超过2秒未收到相机画面,录像已结束,请检查相机连接"; + } + else if (!_recorder.IsRecording) IsRecording = false; + else RecordingInfo = $"● 正在录像 {_recorder.Elapsed:hh\\:mm\\:ss} · {RecordingFps:F0} fps"; + } + if (IsPreviewing && !_camera.IsGrabbing && !IsBusy) + { + StopRecording(); IsPreviewing = false; ClearPreview(); Status = "相机采集已中断,请重新连接"; + } + } + private bool HasRecentFrame => Interlocked.Read(ref _lastFrameTick) != 0 && + Stopwatch.GetElapsedTime(Interlocked.Read(ref _lastFrameTick)).TotalSeconds <= 2; + private void ClearPreview() + { + Interlocked.Increment(ref _generation); + lock (_frames) { _latest?.Dispose(); _latest = null; } + Preview = null; + } + private void SaveSettings() + { + Directory.CreateDirectory(Path.GetDirectoryName(_settingsPath)!); + File.WriteAllText(_settingsPath, JsonSerializer.Serialize(new { directory = SaveDirectory })); + } + public Task ShutdownAsync() => _shutdown ??= ShutdownCoreAsync(); + private async Task ShutdownCoreAsync() + { + _closing = true; _timer.Stop(); StateChanged(); + await _operation; + try { await Task.Run(_camera.Dispose); } + finally + { + try { StopRecording(); } + finally + { + ClearPreview(); + _camera.FrameArrived -= OnFrame; _camera.ConnectionChanged -= OnConnection; _camera.Error -= OnError; + IsPreviewing = false; + } + } + } +} diff --git a/src/SopHelper.App/Training/CameraWindow.xaml b/src/SopHelper.App/Training/CameraWindow.xaml new file mode 100644 index 0000000..13f49d8 --- /dev/null +++ b/src/SopHelper.App/Training/CameraWindow.xaml @@ -0,0 +1,39 @@ + + + + + + + + + + +