From f17194038265dce258159fb6e55074b677e7ad4d Mon Sep 17 00:00:00 2001 From: tfarcraw <123211521@163.com> Date: Wed, 18 Nov 2026 16:58:13 +0800 Subject: [PATCH] =?UTF-8?q?=E5=BC=80=E6=94=BEUSB=E7=9B=B8=E6=9C=BA?= =?UTF-8?q?=E6=9B=9D=E5=85=89=E8=A1=A5=E5=81=BF=E5=B9=B6=E6=A0=A1=E9=AA=8C?= =?UTF-8?q?=E9=A9=B1=E5=8A=A8=E6=94=AF=E6=8C=81=E4=B8=8E=E5=9B=9E=E8=AF=BB?= =?UTF-8?q?=E7=BB=93=E6=9E=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- .../CameraSettings/CameraSettingsViewModel.cs | 15 +- .../CameraSettings/CameraSettingsWindow.axaml | 7 +- .../Camera/UvcCameraService.cs | 10 +- .../Camera/UvcCaptureOptions.cs | 5 +- .../Camera/WindowsExposureCompensation.cs | 150 ++++++++++++++++++ tests/Avalonia.Smoke/Program.cs | 30 +++- 7 files changed, 210 insertions(+), 9 deletions(-) create mode 100644 src/SopHelper.CrossPlatform.Engine/Camera/WindowsExposureCompensation.cs diff --git a/README.md b/README.md index 729df34..a0b8402 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ pwsh -File tools/Start-HandAiD3.ps1 ## 操作流程 1. 在“运行设置”中选择 UVC 或海康相机,新建或选择配方。设置页保留相机、配方和抽帧参数。 -2. 配方编辑器包含“步骤、区域、全局设置、SOP流程视频、Agent助手”五页。在原始相机画面上绘制区域;相机设置独立于配方,在“运行设置”中点击相机后面的“配置”按钮打开专用窗口。USB 分辨率、目标帧率和视频格式使用下拉菜单选择,列表提供常用配置,不代表设备均支持;海康相机可设置曝光时间。设置按设备保存在 workspace/camera-settings.json,保存后下次开启采集、取图或录像预览时生效。SOP 日志显示驱动回读模式,状态栏分别显示 USB 实测采集和渲染 fps。 +2. 配方编辑器包含“步骤、区域、全局设置、SOP流程视频、Agent助手”五页。在原始相机画面上绘制区域;相机设置独立于配方,在“运行设置”中点击相机后面的“配置”按钮打开专用窗口。USB 分辨率、目标帧率、视频格式和曝光补偿使用下拉菜单选择,列表提供常用配置,不代表设备均支持;海康相机可设置曝光时间。设置按设备保存在 workspace/camera-settings.json,保存后下次开启采集、取图或录像预览时生效。SOP 日志显示驱动回读模式,状态栏分别显示 USB 实测采集和渲染 fps。曝光补偿以 EV 为单位,负值压低自动曝光;选择“不修改”保留当前值,0 EV 清除补偿。当前通过 Windows MSMF 对应设备的 KS 扩展接口写入并回读确认,不支持的设备、步长或平台会明确报错;可改回“不修改”继续采集。 3. 步骤名描述操作,“说明”填写送检单帧能看到的静态完成状态,AI 用说明判断图片。触发规则支持手在区域内、手进入后离开区域、A→B 移动和持续计时。 4. 送检可选整张画面、固定区域或跟随手部;跟随手部可以设置扩展距离、最小范围和位置保留时间。 5. 保存、应用后开始采集。规则满足只触发送图;AI 确认且完成概率达标后才推进。步骤说明为空、接口失败或证据不足时不会按规则直接完成。 diff --git a/src/SopHelper.Avalonia/VVMs/CameraSettings/CameraSettingsViewModel.cs b/src/SopHelper.Avalonia/VVMs/CameraSettings/CameraSettingsViewModel.cs index a472cfd..7101261 100644 --- a/src/SopHelper.Avalonia/VVMs/CameraSettings/CameraSettingsViewModel.cs +++ b/src/SopHelper.Avalonia/VVMs/CameraSettings/CameraSettingsViewModel.cs @@ -13,6 +13,10 @@ public sealed record FrameRatePreset(double? Fps) { public override string ToString() => Fps is null ? "驱动默认" : $"{Fps:0.##} fps"; } +public sealed record ExposureCompensationPreset(double? Ev) +{ + public override string ToString() => Ev is null ? "不修改" : $"{Ev:+0.##;-0.##;0} EV"; +} public sealed class CameraSettingsViewModel : BindableBase { private readonly CameraInfo _camera; @@ -27,6 +31,10 @@ public sealed class CameraSettingsViewModel : BindableBase new(3264,2448), new(3840,2160), new(4096,2160), new(4608,3456), new(4656,3496)]); public ObservableCollection FrameRates { get; } = new([ new(null), new(5), new(10), new(15), new(20), new(24), new(25), new(30), new(50), new(60), new(120)]); + public ObservableCollection ExposureCompensations { get; } = new([ + new(null), new(-3), new(-2), new(-5d/3), new(-4d/3), new(-1), new(-2d/3), new(-1d/3), + new(0), new(1d/3), new(2d/3), new(1), new(2), new(3)]); + public ExposureCompensationPreset SelectedExposureCompensation { get; set; } public string[] Formats { get; } = ["驱动默认", "MJPG", "YUY2"]; public ResolutionPreset SelectedResolution { get; set; } public FrameRatePreset SelectedFrameRate { get; set; } @@ -39,6 +47,7 @@ public sealed class CameraSettingsViewModel : BindableBase { _camera = camera; _store = store; SelectedResolution = Resolutions[0]; SelectedFrameRate = FrameRates[0]; + SelectedExposureCompensation = ExposureCompensations[0]; try { var settings = store.Load(camera); @@ -50,6 +59,9 @@ public sealed class CameraSettingsViewModel : BindableBase if (!FrameRates.Contains(rate)) FrameRates.Add(rate); SelectedFrameRate = FrameRates.First(r => r == rate); SelectedFormat = string.IsNullOrWhiteSpace(settings.UsbCapture.Format) ? Formats[0] : settings.UsbCapture.Format.Trim().ToUpperInvariant(); + var compensation = new ExposureCompensationPreset(settings.UsbCapture.ExposureCompensationEv); + if (!ExposureCompensations.Contains(compensation)) ExposureCompensations.Add(compensation); + SelectedExposureCompensation = ExposureCompensations.First(c => c == compensation); ExposureTimeUs = settings.ExposureTimeUs; } catch (Exception ex) { Error = "读取相机设置失败:" + ex.Message; CanSave = false; } @@ -64,7 +76,8 @@ public sealed class CameraSettingsViewModel : BindableBase UsbCapture = IsUsb ? new UvcCaptureOptions { Width = SelectedResolution.Width, Height = SelectedResolution.Height, - Fps = SelectedFrameRate.Fps, Format = SelectedFormat == Formats[0] ? null : SelectedFormat + Fps = SelectedFrameRate.Fps, Format = SelectedFormat == Formats[0] ? null : SelectedFormat, + ExposureCompensationEv = SelectedExposureCompensation.Ev } : new(), ExposureTimeUs = IsIndustrial ? ExposureTimeUs : null }); diff --git a/src/SopHelper.Avalonia/VVMs/CameraSettings/CameraSettingsWindow.axaml b/src/SopHelper.Avalonia/VVMs/CameraSettings/CameraSettingsWindow.axaml index 2a686f5..772173e 100644 --- a/src/SopHelper.Avalonia/VVMs/CameraSettings/CameraSettingsWindow.axaml +++ b/src/SopHelper.Avalonia/VVMs/CameraSettings/CameraSettingsWindow.axaml @@ -1,6 +1,6 @@ + Width="520" Height="540" MinWidth="440" MinHeight="400" Background="{StaticResource Bg}" WindowStartupLocation="CenterOwner"> @@ -21,6 +21,11 @@ + + + + + diff --git a/src/SopHelper.CrossPlatform.Engine/Camera/UvcCameraService.cs b/src/SopHelper.CrossPlatform.Engine/Camera/UvcCameraService.cs index 5638925..ecd29ff 100644 --- a/src/SopHelper.CrossPlatform.Engine/Camera/UvcCameraService.cs +++ b/src/SopHelper.CrossPlatform.Engine/Camera/UvcCameraService.cs @@ -145,6 +145,14 @@ public class UvcCameraService : ICameraService 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 exposureDescription = ""; + if (options.ExposureCompensationEv is { } ev) + { + if (!OperatingSystem.IsWindows() || capture.Get(VideoCaptureProperties.Backend) != (double)VideoCaptureAPIs.MSMF) + throw new NotSupportedException("曝光补偿目前需要 Windows MSMF 采集后端;请在相机配置中选择“不修改”继续采集"); + var actualEv = WindowsExposureCompensation.Set(Current?.Index ?? throw new InvalidOperationException("相机未连接"), ev); + exposureDescription = $";曝光补偿回读 {actualEv:+0.##;-0.##;0} EV"; + } var actualWidth = capture.Get(VideoCaptureProperties.FrameWidth); var actualHeight = capture.Get(VideoCaptureProperties.FrameHeight); var actualFps = capture.Get(VideoCaptureProperties.Fps); @@ -156,7 +164,7 @@ public class UvcCameraService : ICameraService || !string.IsNullOrWhiteSpace(options.Format) && actualFormat != options.Format.Trim().ToUpperInvariant(); ActualFps = 0; return $"USB 驱动回读:{actualWidth:F0}×{actualHeight:F0},{actualFps:F1} fps,格式 {actualFormat}(非实测帧率)" - + (mismatch ? ";与请求不一致,请调整到相机支持的模式" : ""); + + (mismatch ? ";与请求不一致,请调整到相机支持的模式" : "") + exposureDescription; } }); diff --git a/src/SopHelper.CrossPlatform.Engine/Camera/UvcCaptureOptions.cs b/src/SopHelper.CrossPlatform.Engine/Camera/UvcCaptureOptions.cs index 1f27b76..e672a24 100644 --- a/src/SopHelper.CrossPlatform.Engine/Camera/UvcCaptureOptions.cs +++ b/src/SopHelper.CrossPlatform.Engine/Camera/UvcCaptureOptions.cs @@ -7,11 +7,14 @@ public sealed record UvcCaptureOptions public int? Height { get; set; } public double? Fps { get; set; } public string? Format { get; set; } + public double? ExposureCompensationEv { get; set; } [YamlDotNet.Serialization.YamlIgnore, System.Text.Json.Serialization.JsonIgnore] - public bool IsDefault => Width is null && Height is null && Fps is null && string.IsNullOrWhiteSpace(Format); + public bool IsDefault => Width is null && Height is null && Fps is null && string.IsNullOrWhiteSpace(Format) && ExposureCompensationEv is null; public void Validate() { + if (ExposureCompensationEv is { } ev && (!double.IsFinite(ev) || ev < -10 || ev > 10)) + throw new ArgumentException("曝光补偿必须是 -10 至 +10 EV 内的有限数值,或留空不修改;实际范围由相机决定"); 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)) diff --git a/src/SopHelper.CrossPlatform.Engine/Camera/WindowsExposureCompensation.cs b/src/SopHelper.CrossPlatform.Engine/Camera/WindowsExposureCompensation.cs new file mode 100644 index 0000000..0aaf0f0 --- /dev/null +++ b/src/SopHelper.CrossPlatform.Engine/Camera/WindowsExposureCompensation.cs @@ -0,0 +1,150 @@ +using System.ComponentModel; +using System.Runtime.InteropServices; +using Microsoft.Win32.SafeHandles; + +namespace SopHelper.Engine.Camera; + +/// Windows KS EV 补偿接口。只打开控制句柄,不创建第二条视频采集流。 +internal static unsafe class WindowsExposureCompensation +{ + private const uint IoctlKsProperty = 0x002f0003; + private static readonly Guid ExtendedControl = new("1CB79112-C0D2-4213-9CA6-CD4FDB927972"); + private static readonly Guid SourceType = new("C60AC5FE-252A-478F-A0EF-BC8FA5F7CAD3"); + private static readonly Guid VideoCapture = new("8AC3587A-4AE7-42D8-99E0-0A6013EEF90F"); + private static readonly Guid SymbolicLink = new("58F0AAD8-22BF-4F8A-BB3D-D2C4978C6E2F"); + + public static double Set(int index, double ev) + { + if (!OperatingSystem.IsWindows()) throw new NotSupportedException("当前平台尚不支持 USB 曝光补偿"); + using var device = OpenDevice(index); + var payload = Read(device); + var range = new ExposureCompensationRange(payload.Min, payload.Max, payload.Capability); + var (flag, steps) = range.Encode(ev); + payload.Version = 1; payload.PinId = uint.MaxValue; payload.Size = 56; payload.Result = 0; + payload.Flags = flag; payload.Mode = 0; payload.Value = steps; payload.Reserved = 0; + var property = new KsProperty { Set = ExtendedControl, Id = 16, Flags = 2 }; + if (!DeviceIoControl(device, IoctlKsProperty, ref property, 24, ref payload, 56, out _, IntPtr.Zero)) + throw Failure("相机驱动拒绝设置曝光补偿"); + // 此扩展控制允许异步完成;只有回读一致才报告成功。 + for (var i = 0; i < 20; i++) + { + var actual = Read(device); + if (actual.Result == 997) { Thread.Sleep(50); continue; } + var value = ExposureCompensationRange.Decode(actual.Flags, actual.Value); + if (Math.Abs(value - ev) < 0.01) return value; + Thread.Sleep(50); + } + throw new InvalidOperationException("曝光补偿回读与请求不一致,请确认相机支持该设置,或选择“不修改”后重试"); + } + + public static ExposureCompensationRange Query(int index) + { + if (!OperatingSystem.IsWindows()) throw new NotSupportedException("当前平台尚不支持 USB 曝光补偿"); + using var device = OpenDevice(index); + var payload = Read(device); + return new(payload.Min, payload.Max, payload.Capability); + } + + private static SafeFileHandle OpenDevice(int index) + { + var device = CreateFile(GetMediaFoundationDevicePath(index), 0xc0000000, 3, IntPtr.Zero, 3, 0, IntPtr.Zero); + if (!device.IsInvalid) return device; + var failure = Failure("无法访问相机曝光补偿控制接口"); + device.Dispose(); throw failure; + } + + private static EvPayload Read(SafeFileHandle device) + { + var property = new KsProperty { Set = ExtendedControl, Id = 16, Flags = 1 }; + var payload = new EvPayload { Version = 1, PinId = uint.MaxValue, Size = 56 }; + if (!DeviceIoControl(device, IoctlKsProperty, ref property, 24, ref payload, 56, out var count, IntPtr.Zero)) + throw Failure("相机或驱动未提供可用的曝光补偿接口,请选择“不修改”继续使用默认设置"); + if (count < 56 || payload.Size < 56 || (payload.Result != 0 && payload.Result != 997)) + throw new NotSupportedException("相机曝光补偿接口返回的数据无效,请选择“不修改”"); + return payload; + } + + // 与 OpenCV MSMF 后端使用同一套枚举顺序,避免按其他后端的索引操作另一台相机。 + private static string GetMediaFoundationDevicePath(int index) + { + var initialized = CoInitializeEx(IntPtr.Zero, 0); + if (initialized < 0 && initialized != unchecked((int)0x80010106)) Marshal.ThrowExceptionForHR(initialized); + IntPtr attributes = IntPtr.Zero, devices = IntPtr.Zero; + uint count = 0; + var started = false; + try + { + Marshal.ThrowExceptionForHR(MFStartup(0x20070, 0)); started = true; + Marshal.ThrowExceptionForHR(MFCreateAttributes(out attributes, 1)); + var key = SourceType; var value = VideoCapture; + var setGuid = (delegate* unmanaged[Stdcall])(*(IntPtr**)attributes)[24]; + Marshal.ThrowExceptionForHR(setGuid(attributes, &key, &value)); + Marshal.ThrowExceptionForHR(MFEnumDeviceSources(attributes, out devices, out count)); + if (index < 0 || index >= count) throw new InvalidOperationException("找不到当前 USB 相机的曝光补偿控制接口,请刷新相机列表"); + var activate = Marshal.ReadIntPtr(devices, index * IntPtr.Size); + var getString = (delegate* unmanaged[Stdcall])(*(IntPtr**)activate)[13]; + key = SymbolicLink; IntPtr text = IntPtr.Zero; uint length = 0; + try + { + Marshal.ThrowExceptionForHR(getString(activate, &key, &text, &length)); + return Marshal.PtrToStringUni(text, checked((int)length)) ?? throw new InvalidOperationException("相机设备路径为空"); + } + finally { Marshal.FreeCoTaskMem(text); } + } + finally + { + if (devices != IntPtr.Zero) + { + for (var i = 0; i < count; i++) Marshal.Release(Marshal.ReadIntPtr(devices, i * IntPtr.Size)); + Marshal.FreeCoTaskMem(devices); + } + if (attributes != IntPtr.Zero) Marshal.Release(attributes); + if (started) MFShutdown(); + if (initialized >= 0) CoUninitialize(); + } + } + private static Exception Failure(string message) => new InvalidOperationException(message + "(" + new Win32Exception(Marshal.GetLastWin32Error()).Message + ")"); + + [StructLayout(LayoutKind.Sequential)] + private struct KsProperty { public Guid Set; public uint Id, Flags; } + [StructLayout(LayoutKind.Sequential)] + private struct EvPayload + { + public uint Version, PinId, Size, Result; + public ulong Flags, Capability; + public uint Mode; + public int Min, Max, Value; + public ulong Reserved; + } + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CreateFileW")] + private static extern SafeFileHandle CreateFile(string name, uint access, uint share, IntPtr security, uint creation, uint flags, IntPtr template); + [DllImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool DeviceIoControl(SafeFileHandle device, uint code, ref KsProperty input, uint inputSize, ref EvPayload output, uint outputSize, out uint returned, IntPtr overlapped); + [DllImport("ole32.dll")] private static extern int CoInitializeEx(IntPtr reserved, uint mode); + [DllImport("ole32.dll")] private static extern void CoUninitialize(); + [DllImport("mfplat.dll")] private static extern int MFStartup(uint version, uint flags); + [DllImport("mfplat.dll")] private static extern int MFShutdown(); + [DllImport("mfplat.dll")] private static extern int MFCreateAttributes(out IntPtr attributes, uint initialSize); + [DllImport("mf.dll")] private static extern int MFEnumDeviceSources(IntPtr attributes, out IntPtr devices, out uint count); +} + +/// KS 补偿范围是绝对 EV,Value 则是 Flags 指定的步数,不能直接把 EV 当步数发送。 +public sealed record ExposureCompensationRange(int MinEv, int MaxEv, ulong Capabilities) +{ + private static readonly (ulong Flag, int Denominator)[] Steps = [(1,6),(2,4),(4,3),(8,2),(16,1)]; + public (ulong Flag, int Value) Encode(double ev) + { + if (!double.IsFinite(ev) || ev < MinEv || ev > MaxEv) + throw new ArgumentOutOfRangeException(nameof(ev), $"相机曝光补偿支持范围为 {MinEv} 至 {MaxEv} EV"); + foreach (var (flag, denominator) in Steps) + if ((Capabilities & flag) != 0 && Math.Abs(ev * denominator - Math.Round(ev * denominator)) < 0.01) + return (flag, checked((int)Math.Round(ev * denominator))); + throw new NotSupportedException("相机不支持所选曝光补偿步长,请尝试整数 EV,或选择“不修改”"); + } + public static double Decode(ulong flag, int value) + { + foreach (var step in Steps) if (step.Flag == flag) return (double)value / step.Denominator; + throw new NotSupportedException("相机返回了无法识别的曝光补偿步长"); + } +} diff --git a/tests/Avalonia.Smoke/Program.cs b/tests/Avalonia.Smoke/Program.cs index 427b197..d1084a6 100644 --- a/tests/Avalonia.Smoke/Program.cs +++ b/tests/Avalonia.Smoke/Program.cs @@ -33,6 +33,16 @@ internal static class Smoke [STAThread] public static int Main(string[] args) { + if(args.Length==2&&args[0]=="--probe-usb-ev") + { + try + { + var type=typeof(UvcCameraService).Assembly.GetType("SopHelper.Engine.Camera.WindowsExposureCompensation")!; + var range=type.GetMethod("Query")!.Invoke(null,[int.Parse(args[1])]); + Console.WriteLine("USB EV capability (read only): "+range);return 0; + } + catch(Exception ex) { Console.WriteLine("USB EV probe: "+(ex.InnerException?.Message??ex.Message));return 2; } + } _visionOnly=args.Contains("--vision-only"); _processImagesOnly=args.Contains("--process-images-only"); _recipeSelectionOnly=args.Contains("--recipe-selection-only"); @@ -573,12 +583,22 @@ internal static class Smoke private static async Task CheckUsbCapture(App app) { - foreach(var invalid in new UvcCaptureOptions[] {new(){Width=1920},new(){Width=0,Height=1080},new(){Fps=double.NaN},new(){Fps=-1},new(){Format="bad"}}) + foreach(var invalid in new UvcCaptureOptions[] {new(){Width=1920},new(){Width=0,Height=1080},new(){Fps=double.NaN},new(){Fps=-1},new(){Format="bad"},new(){ExposureCompensationEv=double.NaN},new(){ExposureCompensationEv=11}}) { var rejected=false; try {invalid.Validate();} catch(ArgumentException){rejected=true;} Check(rejected,"Invalid USB capture request is rejected before reaching the driver"); } + var thirds=new ExposureCompensationRange(-2,2,4); + Check(thirds.Encode(-2d/3)==(4UL,-2)&&Math.Abs(ExposureCompensationRange.Decode(4,-2)+2d/3)<0.0001,"EV values convert to the camera's supported step units without changing exposure time"); + var wholeOnly=new ExposureCompensationRange(-2,2,16); + var rejectedFraction=false;try{wholeOnly.Encode(-1d/3);}catch(NotSupportedException){rejectedFraction=true;} + Check(rejectedFraction&&wholeOnly.Encode(-1)==(16UL,-1),"Unsupported fractional EV is rejected rather than silently rounded"); + var rejectedRange=false;try{thirds.Encode(-3);}catch(ArgumentOutOfRangeException){rejectedRange=true;} + Check(rejectedRange,"Requested EV is checked against the actual device range"); + var native=typeof(UvcCameraService).Assembly.GetType("SopHelper.Engine.Camera.WindowsExposureCompensation")!; + Check(System.Runtime.InteropServices.Marshal.SizeOf(native.GetNestedType("EvPayload",System.Reflection.BindingFlags.NonPublic)!)==56, + "Native EV payload layout matches the Windows SDK"); var lifetime=(IClassicDesktopStyleApplicationLifetime)Application.Current!.ApplicationLifetime!; var sop=app.Container.Resolve(); app.Container.Resolve().SelectedIndex=1; @@ -593,19 +613,21 @@ internal static class Smoke var resolution=dialog.FindControl("ResolutionPicker")!; var rate=dialog.FindControl("FrameRatePicker")!; var format=dialog.FindControl("FormatPicker")!; + var compensation=dialog.FindControl("ExposureCompensationPicker")!; Check(dialog.Model.Resolutions.Any(r=>r.Width==4608)&&dialog.Model.FrameRates.Any(r=>r.Fps==30),"Resolution and frame rate dropdowns contain common presets including 16 MP and 30 fps"); resolution.SelectedItem=dialog.Model.Resolutions.Single(r=>r.Width==1920&&r.Height==1080); rate.SelectedItem=dialog.Model.FrameRates.Single(r=>r.Fps==30); format.SelectedItem="MJPG"; + compensation.SelectedItem=dialog.Model.ExposureCompensations.Single(c=>c.Ev==-2d/3); await Task.Delay(60); Save(dialog,"camera-settings"); dialog.FindControl