开放USB相机采集参数并区分采集与渲染帧率
This commit is contained in:
parent
df044f6c59
commit
8001129a2a
@ -20,7 +20,7 @@ pwsh -File tools/Start-HandAiD3.ps1
|
||||
## 操作流程
|
||||
|
||||
1. 在“运行设置”中选择 UVC 或海康相机,新建或选择配方。设置页保留相机、配方和抽帧参数。
|
||||
2. 配方编辑器包含“步骤、区域、全局设置、SOP流程视频、Agent助手”五页。在原始相机画面上绘制区域;相机曝光在全局设置中。
|
||||
2. 配方编辑器包含“步骤、区域、全局设置、SOP流程视频、Agent助手”五页。在原始相机画面上绘制区域;相机曝光和 USB 采集参数在全局设置中。USB 可填写宽、高、目标 fps 和视频格式(MJPG / YUY2);留空使用驱动默认模式,宽高需成对填写。保存后重新启动采集生效,取图预览也使用这些参数。不支持的设置会报错;SOP 日志显示驱动回读模式,状态栏分别显示 USB 实测采集和渲染 fps。目标 fps 不保证设备能达到,需根据相机支持的模式实测。
|
||||
3. 步骤名描述操作,“说明”填写送检单帧能看到的静态完成状态,AI 用说明判断图片。触发规则支持手在区域内、手进入后离开区域、A→B 移动和持续计时。
|
||||
4. 送检可选整张画面、固定区域或跟随手部;跟随手部可以设置扩展距离、最小范围和位置保留时间。
|
||||
5. 保存、应用后开始采集。规则满足只触发送图;AI 确认且完成概率达标后才推进。步骤说明为空、接口失败或证据不足时不会按规则直接完成。
|
||||
|
||||
@ -526,6 +526,7 @@ public class RecipeSettingsNode : EditorNode
|
||||
private int _resetDelaySec = 1;
|
||||
private int _frameStride = 1;
|
||||
private double? _exposureTimeUs;
|
||||
public SopHelper.Engine.Camera.UvcCaptureOptions UsbCapture { get; set; } = new();
|
||||
|
||||
public double? ExposureTimeUs
|
||||
{
|
||||
@ -586,6 +587,7 @@ public class RecipeSettingsNode : EditorNode
|
||||
/// <summary>读入</summary>
|
||||
public void CopyFrom(SopSettings from)
|
||||
{
|
||||
UsbCapture = from.UsbCapture with { };
|
||||
ExposureTimeUs = from.ExposureTimeUs;
|
||||
ConfidenceThreshold = from.ConfidenceThreshold;
|
||||
StableFrames = from.StableFrames;
|
||||
@ -599,6 +601,7 @@ public class RecipeSettingsNode : EditorNode
|
||||
/// <summary>写出</summary>
|
||||
public void CopyTo(SopSettings to)
|
||||
{
|
||||
to.UsbCapture = UsbCapture with { };
|
||||
to.ExposureTimeUs = ExposureTimeUs;
|
||||
to.ConfidenceThreshold = ConfidenceThreshold;
|
||||
to.StableFrames = StableFrames;
|
||||
|
||||
@ -370,6 +370,17 @@
|
||||
</TabItem>
|
||||
<TabItem Header="全局设置">
|
||||
<StackPanel Margin="10" DataContext="{Binding Recipe.Settings}">
|
||||
<WrapPanel Margin="0,0,0,8">
|
||||
<TextBlock Text="USB 宽" VerticalAlignment="Center" Margin="0,0,8,0" />
|
||||
<TextBox x:Name="UsbWidthInput" Width="80" Text="{Binding UsbCapture.Width, Mode=TwoWay}" />
|
||||
<TextBlock Text="高" VerticalAlignment="Center" Margin="8,0" />
|
||||
<TextBox x:Name="UsbHeightInput" Width="80" Text="{Binding UsbCapture.Height, Mode=TwoWay}" />
|
||||
<TextBlock Text="目标 fps" VerticalAlignment="Center" Margin="8,0" />
|
||||
<TextBox x:Name="UsbFpsInput" Width="70" Text="{Binding UsbCapture.Fps, Mode=TwoWay}" />
|
||||
<TextBlock Text="格式" VerticalAlignment="Center" Margin="8,0" />
|
||||
<TextBox x:Name="UsbFormatInput" Width="80" Text="{Binding UsbCapture.Format, Mode=TwoWay}" PlaceholderText="默认" ToolTip.Tip="MJPG / YUY2;留空使用驱动默认格式" />
|
||||
</WrapPanel>
|
||||
<TextBlock Text="USB 参数留空使用驱动默认模式;保存后重新启动采集生效。实际协商参数见 SOP 日志;渲染 fps 不等于相机帧率。" TextWrapping="Wrap" Foreground="{StaticResource FgDim}" FontSize="12" Margin="0,0,0,10" />
|
||||
<StackPanel Orientation="Horizontal" Margin="0,0,0,10">
|
||||
<TextBlock Text="相机曝光(μs)" VerticalAlignment="Center" Margin="0,0,8,0" />
|
||||
<TextBox x:Name="CameraExposureInput" Width="120" Text="{Binding ExposureTimeUs, Mode=TwoWay}" ToolTip.Tip="留空保留相机当前曝光设置" />
|
||||
|
||||
@ -121,6 +121,8 @@ public partial class RecipeEditorViewModel : BindableBase, IDialogAware
|
||||
_isNew = parameters.GetValue<bool>("new");
|
||||
_onSaved = parameters.GetValue<Action<string>>("onSaved");
|
||||
SaveStatus = "";
|
||||
try { Recipe.Settings.UsbCapture.Validate(); }
|
||||
catch (ArgumentException ex) { Warnings.Add(ex.Message); return; }
|
||||
_camera = parameters.GetValue<ICameraService>("cameraService");
|
||||
_cameraInfo = parameters.GetValue<CameraInfo>("cameraInfo");
|
||||
_selectedCameraProvider = parameters.GetValue<Func<CameraInfo?>>("selectedCameraProvider") ?? (() => _cameraInfo);
|
||||
@ -235,6 +237,8 @@ public partial class RecipeEditorViewModel : BindableBase, IDialogAware
|
||||
try
|
||||
{
|
||||
if (!await camera.ConnectAsync(_cameraInfo)) throw new InvalidOperationException("连接相机失败,请查看 SOP 页日志");
|
||||
if (_cameraInfo.Kind == CameraKind.Uvc)
|
||||
await camera.ConfigureUvcAsync(Recipe.Settings.UsbCapture);
|
||||
if (Recipe.Settings.ExposureTimeUs is { } exposure)
|
||||
{
|
||||
if (!double.IsFinite(exposure) || exposure <= 0)
|
||||
@ -259,6 +263,8 @@ public partial class RecipeEditorViewModel : BindableBase, IDialogAware
|
||||
private void Save()
|
||||
{
|
||||
SaveStatus = "";
|
||||
try { Recipe.Settings.UsbCapture.Validate(); }
|
||||
catch (ArgumentException ex) { Warnings.Add(ex.Message); return; }
|
||||
if (Recipe.Settings.ExposureTimeUs is { } exposure && (!double.IsFinite(exposure) || exposure <= 0))
|
||||
{
|
||||
Warnings.Add("相机曝光必须大于 0(微秒),或留空保留相机设置");
|
||||
@ -312,6 +318,8 @@ public partial class RecipeEditorViewModel : BindableBase, IDialogAware
|
||||
private void RefreshWarnings()
|
||||
{
|
||||
SaveStatus = "";
|
||||
try { Recipe.Settings.UsbCapture.Validate(); }
|
||||
catch (ArgumentException ex) { Warnings.Add(ex.Message); return; }
|
||||
RaisePropertyChanged(nameof(NameValidationMessage));
|
||||
RaisePropertyChanged(nameof(FileNameText));
|
||||
SaveCommand.RaiseCanExecuteChanged();
|
||||
|
||||
@ -712,6 +712,18 @@ public class SopPageViewModel : ViewModelBase
|
||||
|
||||
ApplyRecipe();
|
||||
|
||||
if (SelectedCamera.Kind == CameraKind.Uvc)
|
||||
{
|
||||
try { Log("info", await _camera.ConfigureUvcAsync(_engine.Config.Sop.Settings.UsbCapture)); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log("error", "设置 USB 采集参数失败:" + ex.Message);
|
||||
await Task.Run(_camera.Disconnect);
|
||||
StatusText = "设置 USB 采集参数失败";
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (_engine.Config.Sop.Settings.ExposureTimeUs is { } exposure)
|
||||
{
|
||||
try
|
||||
@ -924,7 +936,8 @@ public class SopPageViewModel : ViewModelBase
|
||||
// 按真实经过的时间统计成功发布的预览帧。
|
||||
if (_fpsClock.Elapsed.TotalSeconds >= 0.5)
|
||||
{
|
||||
FpsText = $"{(_frameCount - _lastTickCount) / _fpsClock.Elapsed.TotalSeconds:F1} fps(渲染)";
|
||||
FpsText = (_camera.MeasuredCaptureFps is { } captureFps ? $"采集 {captureFps:F1} / " : "")
|
||||
+ $"渲染 {(_frameCount - _lastTickCount) / _fpsClock.Elapsed.TotalSeconds:F1} fps";
|
||||
_lastTickCount = _frameCount;
|
||||
_fpsClock.Restart();
|
||||
}
|
||||
|
||||
@ -21,6 +21,7 @@ public sealed class CameraService : ICameraService
|
||||
|
||||
public bool IsConnected => _active?.IsConnected == true;
|
||||
public bool IsGrabbing => _active?.IsGrabbing == true;
|
||||
public double? MeasuredCaptureFps => _active?.MeasuredCaptureFps;
|
||||
public event Action<CameraFrame>? FrameArrived;
|
||||
public event Action<bool>? ConnectionChanged;
|
||||
public event Action<string>? Error;
|
||||
@ -64,6 +65,18 @@ public sealed class CameraService : ICameraService
|
||||
finally { _operations.Release(); }
|
||||
}
|
||||
|
||||
public async Task<string> ConfigureUvcAsync(UvcCaptureOptions options)
|
||||
{
|
||||
await _operations.WaitAsync().ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
if (_active is null || !_active.IsConnected) throw new InvalidOperationException("请先连接相机");
|
||||
return await _active.ConfigureUvcAsync(options).ConfigureAwait(false);
|
||||
}
|
||||
finally { _operations.Release(); }
|
||||
}
|
||||
|
||||
public async Task<bool> StartAsync()
|
||||
{
|
||||
await _operations.WaitAsync().ConfigureAwait(false);
|
||||
|
||||
@ -55,6 +55,9 @@ public interface ICameraService : IDisposable
|
||||
/// <summary>是否正在采集</summary>
|
||||
bool IsGrabbing { get; }
|
||||
|
||||
/// <summary>采集循环实测帧率;尚未测得或后端不支持时为空。</summary>
|
||||
double? MeasuredCaptureFps => null;
|
||||
|
||||
/// <summary>新帧(在采集线程上触发,消费方用完不得保留 Mat)</summary>
|
||||
event Action<CameraFrame>? FrameArrived;
|
||||
|
||||
@ -74,6 +77,11 @@ public interface ICameraService : IDisposable
|
||||
Task SetExposureTimeAsync(double microseconds) =>
|
||||
Task.FromException(new NotSupportedException("当前相机不支持以微秒设置曝光,请将配方的相机曝光留空"));
|
||||
|
||||
/// <summary>连接后、采集前配置 USB 模式,返回驱动回读参数。</summary>
|
||||
Task<string> ConfigureUvcAsync(UvcCaptureOptions options) => options.IsDefault
|
||||
? Task.FromResult("")
|
||||
: Task.FromException<string>(new NotSupportedException("当前相机不支持 USB 采集参数"));
|
||||
|
||||
/// <summary>开始采集</summary>
|
||||
Task<bool> StartAsync();
|
||||
|
||||
|
||||
@ -40,6 +40,7 @@ public class UvcCameraService : ICameraService
|
||||
|
||||
/// <summary>实测帧率(每 2 秒刷新一次)</summary>
|
||||
public double ActualFps { get; private set; }
|
||||
public double? MeasuredCaptureFps => IsGrabbing && ActualFps > 0 ? ActualFps : null;
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<List<CameraInfo>> EnumerateAsync()
|
||||
@ -122,6 +123,43 @@ public class UvcCameraService : ICameraService
|
||||
});
|
||||
}
|
||||
|
||||
public Task<string> ConfigureUvcAsync(UvcCaptureOptions options) => Task.Run(() =>
|
||||
{
|
||||
options.Validate();
|
||||
lock (DshowLock)
|
||||
lock (_captureLock)
|
||||
{
|
||||
var capture = _capture ?? throw new InvalidOperationException("请先连接相机");
|
||||
if (IsGrabbing) throw new InvalidOperationException("请停止采集后再设置 USB 参数");
|
||||
void Set(VideoCaptureProperties property, double value, string label)
|
||||
{
|
||||
if (!capture.Set(property, value))
|
||||
throw new InvalidOperationException($"驱动不支持 USB {label},请更换参数或留空使用默认模式");
|
||||
}
|
||||
// 先协商传输格式,再协商分辨率和帧率。
|
||||
if (!string.IsNullOrWhiteSpace(options.Format))
|
||||
{
|
||||
var format = options.Format.Trim().ToUpperInvariant();
|
||||
Set(VideoCaptureProperties.FourCC, VideoWriter.FourCC(format[0], format[1], format[2], format[3]), "视频格式 " + format);
|
||||
}
|
||||
if (options.Width is { } width) Set(VideoCaptureProperties.FrameWidth, width, "宽度");
|
||||
if (options.Height is { } height) Set(VideoCaptureProperties.FrameHeight, height, "高度");
|
||||
if (options.Fps is { } fps) Set(VideoCaptureProperties.Fps, fps, "目标帧率");
|
||||
var actualWidth = capture.Get(VideoCaptureProperties.FrameWidth);
|
||||
var actualHeight = capture.Get(VideoCaptureProperties.FrameHeight);
|
||||
var actualFps = capture.Get(VideoCaptureProperties.Fps);
|
||||
var code = (int)capture.Get(VideoCaptureProperties.FourCC);
|
||||
var actualFormat = new string(Enumerable.Range(0, 4).Select(i => (char)((code >> (8 * i)) & 255)).ToArray()).Trim('\0', ' ');
|
||||
var mismatch = options.Width is { } w && Math.Abs(actualWidth - w) > 0.5
|
||||
|| options.Height is { } h && Math.Abs(actualHeight - h) > 0.5
|
||||
|| options.Fps is { } f && Math.Abs(actualFps - f) > 0.5
|
||||
|| !string.IsNullOrWhiteSpace(options.Format) && actualFormat != options.Format.Trim().ToUpperInvariant();
|
||||
ActualFps = 0;
|
||||
return $"USB 驱动回读:{actualWidth:F0}×{actualHeight:F0},{actualFps:F1} fps,格式 {actualFormat}(非实测帧率)"
|
||||
+ (mismatch ? ";与请求不一致,请调整到相机支持的模式" : "");
|
||||
}
|
||||
});
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<bool> StartAsync()
|
||||
{
|
||||
@ -137,6 +175,7 @@ public class UvcCameraService : ICameraService
|
||||
|
||||
if (IsGrabbing) return true;
|
||||
|
||||
ActualFps = 0;
|
||||
_cts = new CancellationTokenSource();
|
||||
IsGrabbing = true;
|
||||
_grabTask = Task.Run(() => GrabLoop(capture, _cts.Token));
|
||||
|
||||
@ -0,0 +1,22 @@
|
||||
namespace SopHelper.Engine.Camera;
|
||||
|
||||
/// <summary>USB 采集请求;空值使用驱动默认模式。</summary>
|
||||
public sealed record UvcCaptureOptions
|
||||
{
|
||||
public int? Width { get; set; }
|
||||
public int? Height { get; set; }
|
||||
public double? Fps { get; set; }
|
||||
public string? Format { get; set; }
|
||||
[YamlDotNet.Serialization.YamlIgnore]
|
||||
public bool IsDefault => Width is null && Height is null && Fps is null && string.IsNullOrWhiteSpace(Format);
|
||||
|
||||
public void Validate()
|
||||
{
|
||||
if ((Width is null) != (Height is null) || Width is <= 0 || Height is <= 0)
|
||||
throw new ArgumentException("USB 分辨率的宽、高必须同时填写正整数,或同时留空");
|
||||
if (Fps is { } fps && (!double.IsFinite(fps) || fps <= 0))
|
||||
throw new ArgumentException("USB 目标帧率必须是大于 0 的有限数值,或留空");
|
||||
if (!string.IsNullOrWhiteSpace(Format) && Format.Trim().ToUpperInvariant() is not ("MJPG" or "YUY2"))
|
||||
throw new ArgumentException("USB 视频格式请填写 MJPG、YUY2,或留空使用默认格式");
|
||||
}
|
||||
}
|
||||
@ -51,6 +51,8 @@ public class SopBody
|
||||
/// </summary>
|
||||
public class SopSettings
|
||||
{
|
||||
public SopHelper.Engine.Camera.UvcCaptureOptions UsbCapture { get; set; } = new();
|
||||
|
||||
/// <summary>手动相机曝光(微秒);空值保留相机当前设置。</summary>
|
||||
[YamlDotNet.Serialization.YamlMember(DefaultValuesHandling = YamlDotNet.Serialization.DefaultValuesHandling.OmitNull)]
|
||||
public double? ExposureTimeUs { get; set; }
|
||||
|
||||
@ -98,6 +98,7 @@ internal static class Smoke
|
||||
Console.WriteLine("Models: "+string.Join(", ",model.AgentModels));
|
||||
await model.ShutdownAsync();dialog.Close();_exit=0;return;
|
||||
}
|
||||
if(Environment.GetCommandLineArgs().Contains("--usb-capture-only")) { await CheckUsbCapture(); _exit=0; return; }
|
||||
CheckCameraPreferences(app);
|
||||
CheckRecipePreferences(app);
|
||||
var navigation=app.Container.Resolve<NavigationModel>();
|
||||
@ -570,6 +571,41 @@ internal static class Smoke
|
||||
finally{sop.IsRunning=false;sop.ApplyRecipeCommand.Execute();}
|
||||
}
|
||||
|
||||
private static async Task CheckUsbCapture()
|
||||
{
|
||||
var legacy=SopHelper.Engine.Sop.SopConfigLoader.Parse("sop:\n name: legacy\n");
|
||||
Check(legacy.Sop.Settings.UsbCapture.IsDefault,"Existing recipes preserve default USB camera negotiation");
|
||||
foreach(var invalid in new UvcCaptureOptions[] {new(){Width=1920},new(){Width=0,Height=1080},new(){Fps=double.NaN},new(){Fps=-1},new(){Format="bad"}})
|
||||
{
|
||||
var rejected=false;
|
||||
try {invalid.Validate();} catch(ArgumentException){rejected=true;}
|
||||
Check(rejected,"Invalid USB capture request is rejected before reaching the driver");
|
||||
}
|
||||
var model=new RecipeEditorViewModel();
|
||||
model.OnDialogOpened(new DialogParameters{{"new",true}});
|
||||
var editor=new RecipeEditor {DataContext=model};
|
||||
var dialog=new Window {Content=editor,Width=1040,Height=760};dialog.Show();
|
||||
try
|
||||
{
|
||||
editor.GetVisualDescendants().OfType<TabControl>().First().SelectedIndex=2;
|
||||
await Task.Delay(80);
|
||||
editor.FindControl<TextBox>("UsbWidthInput")!.Text="1920";
|
||||
editor.FindControl<TextBox>("UsbHeightInput")!.Text="1080";
|
||||
editor.FindControl<TextBox>("UsbFpsInput")!.Text="30";
|
||||
editor.FindControl<TextBox>("UsbFormatInput")!.Text="MJPG";
|
||||
await Task.Delay(60);
|
||||
var config=model.Recipe.ToConfig();
|
||||
config.Sop.Settings.UsbCapture.Validate();
|
||||
var yaml=SopHelper.Engine.Sop.SopConfigLoader.ToYaml(config);
|
||||
var restored=SopHelper.Engine.Sop.SopConfigLoader.Parse(yaml);
|
||||
Check(restored.Sop.Settings.UsbCapture is {Width:1920,Height:1080,Fps:30,Format:"MJPG"},"USB inputs survive editor mapping and YAML save/load");
|
||||
Check(!yaml.Contains("is_default"),"Computed USB state is excluded from recipe YAML");
|
||||
model.Recipe.Settings.UsbCapture.Width=1280;
|
||||
Check(config.Sop.Settings.UsbCapture.Width==1920,"Editing USB inputs does not mutate the applied configuration");
|
||||
}
|
||||
finally {await model.ShutdownAsync();dialog.Close();}
|
||||
}
|
||||
|
||||
private static async Task CheckCompletionImageSaving(App app,SopPageViewModel sop)
|
||||
{
|
||||
var store=new RecipeWorkspace(Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT")!);
|
||||
|
||||
Loading…
Reference in New Issue
Block a user