录像统一使用运行设置中的相机并移除独立刷新选择

This commit is contained in:
tfarcraw 2026-11-10 10:05:46 +08:00
parent 86e6b6100b
commit 90db7695c3
9 changed files with 46 additions and 46 deletions

View File

@ -48,7 +48,7 @@ Windows Python 环境使用 `tools/Setup-Python.ps1 -Sam2`;Linux 环境和部
- 零件名称只在“零件列表”维护,随配方保存到 `sop.parts`。标注类别、步骤目标类别、必留物品和完成必需物品均从该列表选择。
- 旧配方首次编辑时汇总已有训练类别、模型配置、步骤和标注项目名称;保存后列表成为唯一来源。重名、空名以及删除仍被步骤或标注项目引用的名称会阻止保存。
- 检测模型的类别表只读;维护零件列表不会更改已训练模型的类别映射。模型输出类别仍以训练版本为准。
- “SOP流程视频”页录制当前配方的完整标准操作,固定保存到 `recipes/配方名/sop_stand/sop.avi`,与零件训练录像分开存放。新配方先保存,再选择相机、开启预览并开始录像。
- “SOP流程视频”页录制当前配方的完整标准操作,固定保存到 `recipes/配方名/sop_stand/sop.avi`,与零件训练录像分开存放。新配方先保存,再开启预览并开始录像。普通录像与SOP录像统一使用运行设置中选中的相机,录制界面只显示相机名称,不再选择或刷新设备。
- 支持暂停、继续和停止保存;暂停时间不计入视频,累计有效录像最长 5 分钟,到时自动保存并弹窗。关闭编辑窗口也会停止并保存录像。
- 每份配方保留一段标准视频;“重新录制”先弹窗确认,确认后删除旧视频并重新开始,取消会保留原视频。录制中发起重新录制时会先暂停,取消后恢复原先的录制状态。
3. 零件标注与训练包含相机录像、视频导入、画框、SAM2 传播、复核、数据集导出、YOLO 训练和 ONNX 导出。

View File

@ -1,4 +1,3 @@
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Text.Json;
@ -24,6 +23,7 @@ public sealed class CameraViewModel : BindableBase
private readonly string _settingsPath;
private readonly string? _recipeRecordingDirectory;
private readonly bool _sopStandard;
private readonly Func<CameraInfo?> _selectedCameraProvider;
private readonly Stopwatch _previewClock = Stopwatch.StartNew();
private Mat? _latest;
private int _previewPending;
@ -32,18 +32,18 @@ public sealed class CameraViewModel : BindableBase
private volatile bool _closing;
private bool _busy, _previewing, _recording;
private bool _paused;
private string _status = "刷新设备列表,选择相机后开启预览";
private string _status = "使用运行设置中选中的相机,点击“开启相机预览”";
private string _directory;
private string _lastRecording = "";
private string _recordingInfo = "未录像";
private CameraInfo? _selected;
private CameraInfo? _previewCamera, _observedCamera;
private BitmapSource? _preview;
private Task _operation = Task.CompletedTask;
private Task? _shutdown;
private readonly List<DelegateCommand> _commands = [];
public ObservableCollection<CameraInfo> Cameras { get; } = [];
public CameraInfo? SelectedCamera { get => _selected; set { SetProperty(ref _selected, value); UpdateCommands(); } }
public CameraInfo? SelectedCamera => IsPreviewing ? _previewCamera : _selectedCameraProvider();
public string SelectedCameraName => SelectedCamera?.Name ?? "未选择相机,请先到运行设置中选择";
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(); } }
@ -54,7 +54,6 @@ public sealed class CameraViewModel : BindableBase
public string StandardVideoPath => Path.Combine(SaveDirectory, "sop.avi");
public bool HasStandardVideo => _sopStandard && File.Exists(StandardVideoPath);
public Func<Task<bool>>? ConfirmRestartAsync { get; set; }
public bool CanChooseCamera => !IsBusy && !IsPreviewing && !_closing;
public bool CanChangeDirectory => _recipeRecordingDirectory is null && !IsBusy && !IsRecording && !_closing;
public string PreviewButtonText => IsPreviewing ? "关闭相机" : "开启相机预览";
public string RecordButtonText => IsRecording ? "停止录像" : "开始录像";
@ -62,7 +61,6 @@ public sealed class CameraViewModel : BindableBase
public string SaveDirectory { get => _directory; set => SetProperty(ref _directory, _recipeRecordingDirectory ?? 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; }
@ -71,8 +69,9 @@ public sealed class CameraViewModel : BindableBase
public DelegateCommand RestartCommand { get; }
public event Action<string>? RecordingLimitReached;
public CameraViewModel(ICameraService camera, string root, string? recipeName = null, TimeProvider? timeProvider = null, bool sopStandard = false)
public CameraViewModel(ICameraService camera, string root, string? recipeName = null, TimeProvider? timeProvider = null, bool sopStandard = false, Func<CameraInfo?>? selectedCameraProvider = null)
{
_selectedCameraProvider = selectedCameraProvider ?? (() => null);
_recorder = new VideoRecorder(timeProvider);
_camera = camera; _dispatcher = Dispatcher.CurrentDispatcher;
var recipeDirectory = string.IsNullOrWhiteSpace(recipeName) ? null : new SopHelper.Engine.Training.RecipeWorkspace(root).DirectoryFor(recipeName);
@ -86,7 +85,6 @@ public sealed class CameraViewModel : BindableBase
SaveDirectory = _recipeRecordingDirectory ?? ReadSaveDirectory(root);
}
catch (Exception e) { Status = "录像目录配置读取失败:" + e.Message; }
RefreshCommand = Command(RefreshAsync, () => CanChooseCamera);
PreviewCommand = Command(TogglePreviewAsync, () => !IsBusy && !_closing && (IsPreviewing || SelectedCamera != null));
RecordCommand = Command(ToggleRecordingAsync, () => !IsBusy && !_closing && (IsRecording || (!HasStandardVideo && IsPreviewing && Preview != null && HasRecentFrame)));
PauseCommand = Command(() => { TogglePause(); return Task.CompletedTask; }, () => !IsBusy && !_closing && IsRecording);
@ -117,6 +115,7 @@ public sealed class CameraViewModel : BindableBase
_timer = new DispatcherTimer(TimeSpan.FromMilliseconds(250), DispatcherPriority.Background, (_, _) => Tick(), _dispatcher);
_timer.Start();
if (HasStandardVideo) { LastRecording = StandardVideoPath; RecordingInfo = "已有SOP流程视频"; Status = "已有标准操作录像;如需替换,请开启相机后点击“重新录制”"; }
if (SelectedCamera is null) Status = "请先在运行设置中选择相机,再开启录像预览";
}
private DelegateCommand Command(Func<Task> action, Func<bool> canExecute)
@ -135,19 +134,10 @@ public sealed class CameraViewModel : BindableBase
private void UpdateCommands() { foreach (var command in _commands) command.RaiseCanExecuteChanged(); }
private void StateChanged()
{
RaisePropertyChanged(nameof(CanChooseCamera)); RaisePropertyChanged(nameof(CanChangeDirectory));
RaisePropertyChanged(nameof(CanChangeDirectory)); RaisePropertyChanged(nameof(SelectedCameraName));
RaisePropertyChanged(nameof(PreviewButtonText)); RaisePropertyChanged(nameof(RecordButtonText)); UpdateCommands();
RaisePropertyChanged(nameof(PauseButtonText)); RaisePropertyChanged(nameof(HasStandardVideo));
}
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)
@ -157,7 +147,7 @@ public sealed class CameraViewModel : BindableBase
ClearPreview(); IsPreviewing = false; Status = "相机已关闭";
return;
}
var selected = SelectedCamera ?? throw new InvalidOperationException("请选择相机");
var selected = _selectedCameraProvider() ?? throw new InvalidOperationException("请先在运行设置中选择相机");
Status = "正在连接 " + selected.Name;
if (!await _camera.ConnectAsync(selected)) throw new IOException("相机连接失败,请检查设备是否被其他程序占用");
if (_closing) return;
@ -166,6 +156,7 @@ public sealed class CameraViewModel : BindableBase
await Task.Run(_camera.Disconnect);
throw new IOException("相机已连接,但采集启动失败");
}
_previewCamera = selected;
IsPreviewing = true; Status = "相机预览中,可开始录像";
}
private Task ToggleRecordingAsync()
@ -288,6 +279,12 @@ public sealed class CameraViewModel : BindableBase
private void Tick()
{
if (_closing) return;
if (!ReferenceEquals(_observedCamera, SelectedCamera))
{
_observedCamera = SelectedCamera;
RaisePropertyChanged(nameof(SelectedCameraName)); UpdateCommands();
if (!IsPreviewing) Status = SelectedCamera is null ? "请先在运行设置中选择相机,再开启录像预览" : "使用运行设置中选中的相机,点击“开启相机预览”";
}
if (IsRecording)
{
if (_recorder.Elapsed >= VideoRecorder.MaximumDuration)

View File

@ -20,17 +20,9 @@
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<ComboBox ItemsSource="{Binding Cameras}" SelectedItem="{Binding SelectedCamera, Converter={StaticResource SelectionConverter}}" IsEnabled="{Binding CanChooseCamera}" Margin="0,0,10,6" MinHeight="36">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<Button Grid.Column="1" Content="刷新相机" Command="{Binding RefreshCommand}" />
<Button Grid.Column="2" Content="{Binding PreviewButtonText}" Command="{Binding PreviewCommand}" />
<TextBlock Text="{Binding SelectedCameraName}" VerticalAlignment="Center" TextWrapping="Wrap" Margin="0,0,10,6" />
<Button Grid.Column="1" Content="{Binding PreviewButtonText}" Command="{Binding PreviewCommand}" />
</Grid>
<Border Grid.Row="2" Background="#080E14" BorderBrush="{StaticResource Line}" BorderThickness="1" CornerRadius="6" Classes="panel">
<Grid>

View File

@ -48,7 +48,7 @@ public partial class TrainingPage : UserControl
{_model.Status="请先停止 SOP 采集并等待相机操作完成,再打开录像";return;}
if(TopLevel.GetTopLevel(this) is not Window owner)return;
if(string.IsNullOrWhiteSpace(_model.RecipeName)){_model.Status="请先选择配方,再打开录像";return;}
_cameraWindow=new CameraWindow(new CameraViewModel(new CameraService(),_model.Root,_model.RecipeName));
_cameraWindow=new CameraWindow(new CameraViewModel(new CameraService(),_model.Root,_model.RecipeName,selectedCameraProvider:()=>_sop?.SelectedCamera));
try { await _cameraWindow.ShowDialog(owner); }
finally { _model.VideoImportDirectory=_cameraWindow.Model.SaveDirectory;_cameraWindow=null; }
}

View File

@ -444,16 +444,13 @@
<Grid Margin="10" RowDefinitions="Auto,*">
<TextBlock Text="录制完整标准操作流程,视频单独保存在当前配方的 sop_stand 目录。暂停期间不计时,累计录制最长5分钟。新配方请先保存。" TextWrapping="Wrap" Margin="0,0,0,10" />
<Grid Grid.Row="1" DataContext="{Binding SopRecording}" IsVisible="{Binding DataContext.HasSopRecording, RelativeSource={RelativeSource AncestorType=UserControl}}" RowDefinitions="Auto,*,Auto,Auto,Auto">
<Grid ColumnDefinitions="*,Auto,Auto" Margin="0,0,0,10">
<ComboBox ItemsSource="{Binding Cameras}" SelectedItem="{Binding SelectedCamera, Converter={StaticResource SelectionConverter}}" IsEnabled="{Binding CanChooseCamera}" Margin="0,0,8,0">
<ComboBox.ItemTemplate><DataTemplate><TextBlock Text="{Binding Name}" /></DataTemplate></ComboBox.ItemTemplate>
</ComboBox>
<Button Grid.Column="1" Content="刷新相机" Command="{Binding RefreshCommand}" Margin="0,0,8,0" />
<Button Grid.Column="2" Content="{Binding PreviewButtonText}" Command="{Binding PreviewCommand}" />
<Grid ColumnDefinitions="*,Auto" Margin="0,0,0,10">
<TextBlock Text="{Binding SelectedCameraName}" VerticalAlignment="Center" TextWrapping="Wrap" Margin="0,0,8,0" />
<Button Grid.Column="1" Content="{Binding PreviewButtonText}" Command="{Binding PreviewCommand}" />
</Grid>
<Border Grid.Row="1" Background="#080E14" CornerRadius="6" MinHeight="180">
<Grid>
<TextBlock Text="选择相机并开启预览后,开始录制标准操作流程" HorizontalAlignment="Center" VerticalAlignment="Center" Foreground="{StaticResource FgDim}" />
<TextBlock Text="使用运行设置中选中的相机,开启预览后录制标准操作流程" HorizontalAlignment="Center" VerticalAlignment="Center" Foreground="{StaticResource FgDim}" />
<Image Source="{Binding Preview}" Stretch="Uniform" />
</Grid>
</Border>

View File

@ -36,6 +36,7 @@ public class RecipeEditorViewModel : BindableBase, IDialogAware
private bool _isCapturing;
private ICameraService? _camera;
private CameraInfo? _cameraInfo;
private Func<CameraInfo?>? _selectedCameraProvider;
private SopHelper.Training.CameraViewModel? _sopRecording;
public SopHelper.Training.CameraViewModel? SopRecording { get => _sopRecording; private set => SetProperty(ref _sopRecording, value); }
public bool HasSopRecording => SopRecording is not null;
@ -119,6 +120,7 @@ public class RecipeEditorViewModel : BindableBase, IDialogAware
SaveStatus = "";
_camera = parameters.GetValue<ICameraService>("cameraService");
_cameraInfo = parameters.GetValue<CameraInfo>("cameraInfo");
_selectedCameraProvider = parameters.GetValue<Func<CameraInfo?>>("selectedCameraProvider") ?? (() => _cameraInfo);
PreviewImage = parameters.GetValue<BitmapSource>("preview");
CaptureImageCommand.RaiseCanExecuteChanged();
if (PreviewImage is not null) DescribeImage("最近一帧");
@ -159,7 +161,7 @@ public class RecipeEditorViewModel : BindableBase, IDialogAware
// Use a separate camera service so SOP capture cannot dispose the operator page's service.
var recipeDirectory = Path.GetDirectoryName(_path)!;
var root = Path.GetDirectoryName(Path.GetDirectoryName(recipeDirectory)!)!;
SopRecording = new SopHelper.Training.CameraViewModel(new CameraService(), root, Path.GetFileNameWithoutExtension(_path), sopStandard: true);
SopRecording = new SopHelper.Training.CameraViewModel(new CameraService(), root, Path.GetFileNameWithoutExtension(_path), sopStandard: true, selectedCameraProvider: _selectedCameraProvider);
RaisePropertyChanged(nameof(HasSopRecording));
}
public async Task ShutdownSopRecordingAsync()

View File

@ -464,6 +464,7 @@ public class SopPageViewModel : ViewModelBase
parameters.Add("onSaved", new Action<string>(fileName =>
_dispatcher.BeginInvoke(() => RefreshRecipes(fileName))));
parameters.Add("cameraService", _camera);
parameters.Add("selectedCameraProvider", new Func<CameraInfo?>(() => SelectedCamera));
if (SelectedCamera is not null) parameters.Add("cameraInfo", SelectedCamera);
if (Frame is BitmapSource image)
{

View File

@ -117,6 +117,7 @@ internal static class Smoke
sop.EditRecipeCommand.Execute();await Task.Delay(150);
var modal=lifetime.Windows.OfType<RecipeDialogWindow>().Single();
Check(modal.Width==1040&&modal.Height==760&&modal.DataContext is RecipeEditorViewModel,"Original edit command opens the sized Prism recipe dialog");
Check(ReferenceEquals(((RecipeEditorViewModel)modal.DataContext!).SopRecording!.SelectedCamera,sop.SelectedCamera),"SOP recording inherits the runtime settings camera");
((RecipeEditorViewModel)modal.DataContext!).CloseCommand.Execute();
for(var i=0;i<100&&lifetime.Windows.Contains(modal);i++)await Task.Delay(20);
Check(!lifetime.Windows.Contains(modal),"Recipe close command respects the Prism dialog lifecycle");

View File

@ -29,9 +29,14 @@ internal static class Program
Check(VideoRecorder.MaximumDuration == TimeSpan.FromMinutes(5), "Production recording limit is five minutes");
var clock = new ManualClock();
using var camera = new FakeCamera();
var model = new CameraViewModel(camera, root, timeProvider: clock);
CameraInfo? selected = null;
var model = new CameraViewModel(camera, root, timeProvider: clock, selectedCameraProvider: () => selected);
var window = new CameraWindow(model); window.Show();
model.RefreshCommand.Execute(); model.PreviewCommand.Execute();
Check(!model.PreviewCommand.CanExecute() && model.SelectedCameraName.Contains("运行设置"), "Recording requires the camera selected in runtime settings");
Check(!window.GetVisualDescendants().OfType<ComboBox>().Any() && !window.GetVisualDescendants().OfType<Button>().Any(b => b.Content?.ToString() == "刷新相机"), "Recording window has no camera selector or refresh button");
selected = new CameraInfo { Kind = CameraKind.Hikvision, Index = 7, SerialNumber = "GLOBAL-CAMERA", Name = "运行设置中的相机" };
Tick(model); model.PreviewCommand.Execute();
Check(ReferenceEquals(camera.ConnectedCamera, selected) && camera.EnumerationCount == 0, "Recording uses the exact global camera without enumerating devices");
Thread.Sleep(75); camera.Emit(); Dispatcher.UIThread.RunJobs();
Check(model.RecordCommand.CanExecute(), "Preview is ready for recording");
var notices = 0;
@ -88,14 +93,17 @@ internal static class Program
vm.OnDialogOpened(new DialogParameters { { "directory", store.RecipesDirectory }, { "path", store.ConfigPath(config.Sop.Name) }, { "config", config }, { "new", false } });
Pump(vm.ShutdownSopRecordingAsync());
var clock = new ManualClock(); using var camera = new FakeCamera();
var model = new CameraViewModel(camera, root, config.Sop.Name, clock, sopStandard: true);
var selected = new CameraInfo { Index = 3, Name = "全局SOP相机" };
var model = new CameraViewModel(camera, root, config.Sop.Name, clock, sopStandard: true, selectedCameraProvider: () => selected);
// Substitute the camera at the presentation boundary; never open real test hardware.
typeof(RecipeEditorViewModel).GetProperty(nameof(vm.SopRecording))!.SetValue(vm, model);
var editor = new RecipeEditor { DataContext = vm };
var window = new Window { Content = editor, Width = 1180, Height = 820 }; window.Show(); window.UpdateLayout();
var tabs = editor.GetVisualDescendants().OfType<TabControl>().Single(); tabs.SelectedIndex = 5; window.UpdateLayout();
Check(tabs.ItemCount == 6 && ((TabItem)tabs.Items[5]!).Header?.ToString() == "SOP流程视频", "Recipe editor contains the SOP recording page");
model.RefreshCommand.Execute(); model.PreviewCommand.Execute(); Thread.Sleep(75); camera.Emit(); Dispatcher.UIThread.RunJobs();
Check(!editor.GetVisualDescendants().OfType<Button>().Any(b => b.Content?.ToString() == "刷新相机"), "SOP page has no independent camera refresh");
model.PreviewCommand.Execute(); Thread.Sleep(75); camera.Emit(); Dispatcher.UIThread.RunJobs();
Check(ReferenceEquals(camera.ConnectedCamera, selected) && camera.EnumerationCount == 0, "SOP recording also uses the global camera directly");
model.RecordCommand.Execute();
var expectedPath = Path.Combine(store.DirectoryFor(config.Sop.Name), "sop_stand", "sop.avi");
Check(model.LastRecording == expectedPath && !model.CanChangeDirectory, "SOP video is stored separately under its current recipe");
@ -179,13 +187,15 @@ internal sealed class ManualClock : TimeProvider
}
internal sealed class FakeCamera : ICameraService
{
public CameraInfo? ConnectedCamera { get; private set; }
public int EnumerationCount { get; private set; }
public bool IsConnected { get; private set; }
public bool IsGrabbing { get; private set; }
public event Action<CameraFrame>? FrameArrived;
public event Action<bool>? ConnectionChanged;
public event Action<string>? Error { add { } remove { } }
public Task<List<CameraInfo>> EnumerateAsync() => Task.FromResult(new List<CameraInfo> { new() { Name = "测试相机" } });
public Task<bool> ConnectAsync(CameraInfo camera) { IsConnected = true; ConnectionChanged?.Invoke(true); return Task.FromResult(true); }
public Task<List<CameraInfo>> EnumerateAsync() { EnumerationCount++; return Task.FromResult(new List<CameraInfo> { new() { Name = "测试相机" } }); }
public Task<bool> ConnectAsync(CameraInfo camera) { ConnectedCamera = camera; IsConnected = true; ConnectionChanged?.Invoke(true); return Task.FromResult(true); }
public Task<bool> StartAsync() { IsGrabbing = true; return Task.FromResult(true); }
public void Stop() => IsGrabbing = false;
public void Disconnect() { Stop(); IsConnected = false; ConnectionChanged?.Invoke(false); }