集成USB相机低亮度补偿开关并支持静默回退

This commit is contained in:
tfarcraw 2026-11-18 17:26:25 +08:00
parent fbe5a0090b
commit 89db34bc18
7 changed files with 117 additions and 13 deletions

View File

@ -20,7 +20,7 @@ pwsh -File tools/Start-HandAiD3.ps1
## 操作流程
1. 在“运行设置”中选择 UVC 或海康相机,新建或选择配方。设置页保留相机、配方和抽帧参数。
2. 配方编辑器包含“步骤、区域、全局设置、SOP流程视频、Agent助手”五页。在原始相机画面上绘制区域;相机设置独立于配方,在“运行设置”中点击相机后面的“配置”按钮打开专用窗口。USB 分辨率、目标帧率、视频格式和曝光补偿使用下拉菜单选择,列表提供常用配置,不代表设备均支持;海康相机可设置曝光时间。设置按设备保存在 workspace/camera-settings.json,保存后下次开启采集、取图或录像预览时生效。SOP 日志显示驱动回读模式,状态栏分别显示 USB 实测采集和渲染 fps。曝光补偿以 EV 为单位,负值压低自动曝光;选择“不修改”保留当前值,0 EV 清除补偿。当前通过 Windows MSMF 对应设备的 KS 扩展接口写入并回读确认,不支持的设备、步长或平台,以及曝光补偿设置失败时,均静默跳过,不提示、不阻断采集。
2. 配方编辑器包含“步骤、区域、全局设置、SOP流程视频、Agent助手”五页。在原始相机画面上绘制区域;相机设置独立于配方,在“运行设置”中点击相机后面的“配置”按钮打开专用窗口。USB 分辨率、目标帧率、视频格式、曝光补偿和低亮度补偿使用下拉菜单选择,列表提供常用配置,不代表设备均支持;海康相机可设置曝光时间。设置按设备保存在 workspace/camera-settings.json,保存后下次开启采集、取图或录像预览时生效。SOP 日志显示驱动回读模式,状态栏分别显示 USB 实测采集和渲染 fps。曝光补偿以 EV 为单位,负值压低自动曝光;选择“不修改”保留当前值,0 EV 清除补偿。当前通过 Windows MSMF 对应设备的 KS 扩展接口写入并回读确认,不支持的设备、步长或平台,以及曝光补偿设置失败时,均静默跳过,不提示、不阻断采集。低亮度补偿提供“不修改/关闭/开启”,对应 UVC 属性页同名开关(自动曝光优先级),按设备保存,并在采集、取图、录像预览启动前应用;不支持或设置失败时同样静默跳过,成功回读后记录运行日志。
3. 步骤名描述操作,“说明”填写送检单帧能看到的静态完成状态,AI 用说明判断图片。触发规则支持手在区域内、手进入后离开区域、A→B 移动和持续计时。
4. 送检可选整张画面、固定区域或跟随手部;跟随手部可以设置扩展距离、最小范围和位置保留时间。
5. 保存、应用后开始采集。规则满足只触发送图;AI 确认且完成概率达标后才推进。步骤说明为空、接口失败或证据不足时不会按规则直接完成。

View File

@ -17,6 +17,10 @@ public sealed record ExposureCompensationPreset(double? Ev)
{
public override string ToString() => Ev is null ? "不修改" : $"{Ev:+0.##;-0.##;0} EV";
}
public sealed record LowLightCompensationPreset(bool? Enabled)
{
public override string ToString() => Enabled switch { true => "开启", false => "关闭", null => "不修改" };
}
public sealed class CameraSettingsViewModel : BindableBase
{
private readonly CameraInfo _camera;
@ -35,6 +39,8 @@ public sealed class CameraSettingsViewModel : BindableBase
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 LowLightCompensationPreset[] LowLightCompensations { get; } = [new(null), new(false), new(true)];
public LowLightCompensationPreset SelectedLowLightCompensation { get; set; }
public string[] Formats { get; } = ["驱动默认", "MJPG", "YUY2"];
public ResolutionPreset SelectedResolution { get; set; }
public FrameRatePreset SelectedFrameRate { get; set; }
@ -48,6 +54,7 @@ public sealed class CameraSettingsViewModel : BindableBase
_camera = camera; _store = store;
SelectedResolution = Resolutions[0]; SelectedFrameRate = FrameRates[0];
SelectedExposureCompensation = ExposureCompensations[0];
SelectedLowLightCompensation = LowLightCompensations[0];
try
{
var settings = store.Load(camera);
@ -62,6 +69,7 @@ public sealed class CameraSettingsViewModel : BindableBase
var compensation = new ExposureCompensationPreset(settings.UsbCapture.ExposureCompensationEv);
if (!ExposureCompensations.Contains(compensation)) ExposureCompensations.Add(compensation);
SelectedExposureCompensation = ExposureCompensations.First(c => c == compensation);
SelectedLowLightCompensation = LowLightCompensations.Single(p => p.Enabled == settings.UsbCapture.LowLightCompensation);
ExposureTimeUs = settings.ExposureTimeUs;
}
catch (Exception ex) { Error = "读取相机设置失败:" + ex.Message; CanSave = false; }
@ -77,7 +85,8 @@ public sealed class CameraSettingsViewModel : BindableBase
{
Width = SelectedResolution.Width, Height = SelectedResolution.Height,
Fps = SelectedFrameRate.Fps, Format = SelectedFormat == Formats[0] ? null : SelectedFormat,
ExposureCompensationEv = SelectedExposureCompensation.Ev
ExposureCompensationEv = SelectedExposureCompensation.Ev,
LowLightCompensation = SelectedLowLightCompensation.Enabled
} : new(),
ExposureTimeUs = IsIndustrial ? ExposureTimeUs : null
});

View File

@ -1,6 +1,6 @@
<Window xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="SopHelper.VVMs.CameraSettings.CameraSettingsWindow" Title="相机配置"
Width="520" Height="540" MinWidth="440" MinHeight="400" Background="{StaticResource Bg}" WindowStartupLocation="CenterOwner">
Width="520" Height="600" MinWidth="440" MinHeight="400" Background="{StaticResource Bg}" WindowStartupLocation="CenterOwner">
<Grid Margin="24" RowDefinitions="Auto,*,Auto">
<StackPanel Spacing="8">
<TextBlock Text="相机配置" Classes="Title" />
@ -26,6 +26,11 @@
<ComboBox x:Name="ExposureCompensationPicker" Grid.Column="1" ItemsSource="{Binding ExposureCompensations}" SelectedItem="{Binding SelectedExposureCompensation, Mode=TwoWay}" HorizontalAlignment="Stretch" />
</Grid>
<TextBlock Text="自动曝光偏亮可先试 −0.33 或 −0.67 EV;0 EV 为无补偿,“不修改”保留相机当前值。" TextWrapping="Wrap" Foreground="{StaticResource FgDim}" FontSize="12" />
<Grid ColumnDefinitions="100,*">
<TextBlock Text="低亮度补偿" VerticalAlignment="Center" />
<ComboBox x:Name="LowLightCompensationPicker" Grid.Column="1" ItemsSource="{Binding LowLightCompensations}" SelectedItem="{Binding SelectedLowLightCompensation, Mode=TwoWay}" HorizontalAlignment="Stretch" />
</Grid>
<TextBlock Text="对应相机属性页的同名开关。选择“关闭”可关闭低亮度补偿;“不修改”保留相机当前值。" TextWrapping="Wrap" Foreground="{StaticResource FgDim}" FontSize="12" />
<TextBlock Text="列表为常用配置,不代表当前相机均支持。选择“驱动默认”可保留默认模式;实际协商结果见运行日志。" TextWrapping="Wrap" Foreground="{StaticResource FgDim}" FontSize="12" />
</StackPanel>
<StackPanel IsVisible="{Binding IsIndustrial}" Spacing="8">

View File

@ -149,8 +149,14 @@ public class UvcCameraService : ICameraService
if (options.ExposureCompensationEv is { } ev && OperatingSystem.IsWindows()
&& capture.Get(VideoCaptureProperties.Backend) == (double)VideoCaptureAPIs.MSMF
&& Current is { } current
&& WindowsExposureCompensation.TrySet(current.Index, ev) is { } actualEv)
&& WindowsUvcControls.TrySet(current.Index, ev) is { } actualEv)
exposureDescription = $";曝光补偿回读 {actualEv:+0.##;-0.##;0} EV";
var lowLightDescription = "";
if (options.LowLightCompensation is { } lowLight && OperatingSystem.IsWindows()
&& capture.Get(VideoCaptureProperties.Backend) == (double)VideoCaptureAPIs.MSMF
&& Current is { } lowLightCamera
&& WindowsUvcControls.TrySetLowLightCompensation(lowLightCamera.Index, lowLight) is { } actualLowLight)
lowLightDescription = actualLowLight ? ";低亮度补偿已开启" : ";低亮度补偿已关闭";
var actualWidth = capture.Get(VideoCaptureProperties.FrameWidth);
var actualHeight = capture.Get(VideoCaptureProperties.FrameHeight);
var actualFps = capture.Get(VideoCaptureProperties.Fps);
@ -162,7 +168,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 ? ";与请求不一致,请调整到相机支持的模式" : "") + exposureDescription;
+ (mismatch ? ";与请求不一致,请调整到相机支持的模式" : "") + exposureDescription + lowLightDescription;
}
});

View File

@ -8,8 +8,9 @@ public sealed record UvcCaptureOptions
public double? Fps { get; set; }
public string? Format { get; set; }
public double? ExposureCompensationEv { get; set; }
public bool? LowLightCompensation { 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) && ExposureCompensationEv is null;
public bool IsDefault => Width is null && Height is null && Fps is null && string.IsNullOrWhiteSpace(Format) && ExposureCompensationEv is null && LowLightCompensation is null;
public void Validate()
{

View File

@ -4,11 +4,12 @@ using Microsoft.Win32.SafeHandles;
namespace SopHelper.Engine.Camera;
/// <summary>Windows KS EV 补偿接口。只打开控制句柄,不创建第二条视频采集流。</summary>
internal static unsafe class WindowsExposureCompensation
/// <summary>Windows KS 相机控制接口。只打开控制句柄,不创建第二条视频采集流。</summary>
internal static unsafe class WindowsUvcControls
{
private const uint IoctlKsProperty = 0x002f0003;
private static readonly Guid ExtendedControl = new("1CB79112-C0D2-4213-9CA6-CD4FDB927972");
private static readonly Guid CameraControlSet = new("C6E13370-30AC-11D0-A18C-00A0C9118956");
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");
@ -20,6 +21,51 @@ internal static unsafe class WindowsExposureCompensation
catch (Exception) { return null; }
}
// KSPROPERTY_CAMERACONTROL_AUTO_EXPOSURE_PRIORITY(19)即 UVC 属性页的低亮度补偿。
// https://learn.microsoft.com/windows-hardware/drivers/stream/ksproperty-cameracontrol-auto-exposure-priority
public static bool? TrySetLowLightCompensation(int index, bool enabled)
{
try
{
if (!OperatingSystem.IsWindows()) return null;
using var device = OpenDevice(index);
var current = ReadLowLightCompensation(device);
if ((current.Value != 0) == enabled) return enabled;
var request = new CameraControlProperty
{
Property = new KsProperty { Set = CameraControlSet, Id = 19, Flags = 2 },
Value = enabled ? 1 : 0, Flags = 2
};
var response = request;
if (!CameraControlIoctl(device, IoctlKsProperty, ref request, 40, ref response, 40, out _, IntPtr.Zero))
return null;
var actual = ReadLowLightCompensation(device);
return (actual.Value != 0) == enabled ? enabled : null;
}
catch (Exception) { return null; }
}
public static bool? QueryLowLightCompensation(int index)
{
if (!OperatingSystem.IsWindows()) return null;
using var device = OpenDevice(index);
return ReadLowLightCompensation(device).Value != 0;
}
private static CameraControlProperty ReadLowLightCompensation(SafeFileHandle device)
{
var request = new CameraControlProperty
{
Property = new KsProperty { Set = CameraControlSet, Id = 19, Flags = 1 }
};
var response = request;
if (!CameraControlIoctl(device, IoctlKsProperty, ref request, 40, ref response, 40, out var count, IntPtr.Zero))
throw Failure("无法读取相机低亮度补偿");
if (count < 40 || response.Value is not (0 or 1))
throw new NotSupportedException($"低亮度补偿返回值无效:长度 {count},值 {response.Value}");
return response;
}
private static double Set(int index, double ev)
{
if (!OperatingSystem.IsWindows()) throw new NotSupportedException("当前平台尚不支持 USB 曝光补偿");
@ -114,6 +160,18 @@ internal static unsafe class WindowsExposureCompensation
[StructLayout(LayoutKind.Sequential)]
private struct KsProperty { public Guid Set; public uint Id, Flags; }
// KSIDENTIFIER 包含 LONGLONG 对齐成员,原生相机控制结构尾部需补齐到 40 字节。
[StructLayout(LayoutKind.Sequential, Size = 40)]
private struct CameraControlProperty
{
public KsProperty Property;
public int Value;
public uint Flags, Capabilities;
}
[DllImport("kernel32.dll", SetLastError = true, EntryPoint = "DeviceIoControl")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CameraControlIoctl(SafeFileHandle device, uint code, ref CameraControlProperty input,
uint inputSize, ref CameraControlProperty output, uint outputSize, out uint returned, IntPtr overlapped);
[StructLayout(LayoutKind.Sequential)]
private struct EvPayload
{

View File

@ -37,12 +37,23 @@ internal static class Smoke
{
try
{
var type=typeof(UvcCameraService).Assembly.GetType("SopHelper.Engine.Camera.WindowsExposureCompensation")!;
var type=typeof(UvcCameraService).Assembly.GetType("SopHelper.Engine.Camera.WindowsUvcControls")!;
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; }
}
if(args.Length==2&&args[0]=="--probe-usb-low-light")
{
try
{
var type=typeof(UvcCameraService).Assembly.GetType("SopHelper.Engine.Camera.WindowsUvcControls")!;
var value=type.GetMethod("QueryLowLightCompensation")!.Invoke(null,[int.Parse(args[1])]);
Console.WriteLine("USB low-light compensation (read only): "+(value is bool enabled ? (enabled ? "on" : "off") : "unavailable"));
}
catch(Exception ex){Console.WriteLine("USB low-light probe: "+(ex.InnerException?.Message??ex.Message));}
return 0;
}
_visionOnly=args.Contains("--vision-only");
_processImagesOnly=args.Contains("--process-images-only");
_recipeSelectionOnly=args.Contains("--recipe-selection-only");
@ -596,9 +607,15 @@ internal static class Smoke
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")!;
var native=typeof(UvcCameraService).Assembly.GetType("SopHelper.Engine.Camera.WindowsUvcControls")!;
Check(native.GetMethod("TrySet")!.Invoke(null,[-1,-1d]) is null,
"Unavailable exposure compensation silently returns without throwing or writing to a camera");
Check(native.GetMethod("TrySetLowLightCompensation")!.Invoke(null,[-1,false]) is null,
"Unavailable low-light compensation is silently skipped");
Check(System.Runtime.InteropServices.Marshal.SizeOf(native.GetNestedType("CameraControlProperty",System.Reflection.BindingFlags.NonPublic)!)==40,
"Low-light control layout matches the Windows SDK");
Check(!new UvcCaptureOptions {LowLightCompensation=false}.IsDefault,
"Explicitly disabling low-light compensation is distinct from leaving the camera unchanged");
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!;
@ -616,20 +633,22 @@ internal static class Smoke
var rate=dialog.FindControl<ComboBox>("FrameRatePicker")!;
var format=dialog.FindControl<ComboBox>("FormatPicker")!;
var compensation=dialog.FindControl<ComboBox>("ExposureCompensationPicker")!;
var lowLight=dialog.FindControl<ComboBox>("LowLightCompensationPicker")!;
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);
lowLight.SelectedItem=dialog.Model.LowLightCompensations.Single(p=>p.Enabled==false);
await Task.Delay(60);
Save(dialog,"camera-settings");
dialog.FindControl<Button>("SaveCameraSettingsButton")!.RaiseEvent(new Avalonia.Interactivity.RoutedEventArgs(Button.ClickEvent));
await Task.Delay(80);
var store=CameraSettingsStore.Current;
var settings=store.Load(sop.SelectedCamera!);
Check(settings.UsbCapture is {Width:1920,Height:1080,Fps:30,Format:"MJPG",ExposureCompensationEv:var savedEv} && Math.Abs(savedEv!.Value+2d/3)<0.0001,"Camera dialog saves selected dropdown values independently of recipes");
Check(settings.UsbCapture is {Width:1920,Height:1080,Fps:30,Format:"MJPG",LowLightCompensation:false,ExposureCompensationEv:var savedEv} && Math.Abs(savedEv!.Value+2d/3)<0.0001,"Camera dialog saves selected dropdown values independently of recipes");
var reopened=new SopHelper.VVMs.CameraSettings.CameraSettingsViewModel(sop.SelectedCamera!,store);
Check(reopened.SelectedResolution.Width==1920&&reopened.SelectedFrameRate.Fps==30&&reopened.SelectedFormat=="MJPG"&&Math.Abs(reopened.SelectedExposureCompensation.Ev!.Value+2d/3)<0.0001,"Camera settings restore on reopening the dialog");
Check(reopened.SelectedResolution.Width==1920&&reopened.SelectedFrameRate.Fps==30&&reopened.SelectedFormat=="MJPG"&&reopened.SelectedLowLightCompensation.Enabled==false&&Math.Abs(reopened.SelectedExposureCompensation.Ev!.Value+2d/3)<0.0001,"Camera settings restore on reopening the dialog");
reopened.SelectedResolution=reopened.Resolutions[0];
Check(store.Load(sop.SelectedCamera!).UsbCapture.Width==1920,"Unsaved changes do not overwrite stored camera settings");
Check(store.Load(new CameraInfo{Index=9}).UsbCapture.IsDefault,"Each camera keeps its own independent settings");
@ -637,7 +656,13 @@ internal static class Smoke
Check(!yaml.Contains("usb_capture")&&!yaml.Contains("exposure_time_us"),"Recipe YAML contains no camera settings");
using var probe=new FakeCamera();
await store.ApplyAsync(probe,sop.SelectedCamera!);
Check(probe.LastUsbOptions is {Width:1920,Height:1080,Fps:30,Format:"MJPG",ExposureCompensationEv:var appliedEv} && Math.Abs(appliedEv!.Value+2d/3)<0.0001,"Acquisition receives settings from the per-camera store");
Check(probe.LastUsbOptions is {Width:1920,Height:1080,Fps:30,Format:"MJPG",LowLightCompensation:false,ExposureCompensationEv:var appliedEv} && Math.Abs(appliedEv!.Value+2d/3)<0.0001,"Acquisition receives settings from the per-camera store");
reopened.SelectedLowLightCompensation=reopened.LowLightCompensations.Single(p=>p.Enabled==true);
Check(reopened.Save()&&store.Load(sop.SelectedCamera!).UsbCapture.LowLightCompensation==true,
"Low-light compensation can also be enabled and saved");
reopened.SelectedLowLightCompensation=reopened.LowLightCompensations.Single(p=>p.Enabled is null);
Check(reopened.Save()&&store.Load(sop.SelectedCamera!).UsbCapture.LowLightCompensation is null,
"Leaving low-light compensation unchanged is preserved independently from on and off");
sop.IsRunning=true;await Task.Delay(20);
Check(!button.IsEffectivelyEnabled&&!sop.ConfigureCameraCommand.CanExecute(),"Camera configuration is disabled while running");
sop.IsRunning=false;