提交代码

This commit is contained in:
ldh
2026-11-25 13:35:06 +08:00
parent 162bc73395
commit 48126f7f80
25 changed files with 3471 additions and 682 deletions
@@ -4,6 +4,11 @@
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<!--
DirectML 的 build targets 仅在 PlatformTarget=x64 时复制 DirectML.dll,
AnyCPU 会导致运行时缺少该原生库而退回 CPU,因此这里固定为 x64。
-->
<PlatformTarget>x64</PlatformTarget>
</PropertyGroup>
<ItemGroup>
@@ -11,7 +16,12 @@
<PackageReference Include="LiteDB" Version="5.0.21" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.14" />
<PackageReference Include="Microsoft.Extensions.Options" Version="10.0.14" />
<PackageReference Include="Microsoft.ML.OnnxRuntime" Version="1.20.1" />
<!--
DirectML 版 ONNX Runtime:可用核显/独显推理,不支持的算子自动回退 CPU。
注意:该包与纯 CPU 版 Microsoft.ML.OnnxRuntime 的原生 dll 冲突,只能二选一;
1.24.4 是最后一个提供 DirectML 执行后端的稳定版本。
-->
<PackageReference Include="Microsoft.ML.OnnxRuntime.DirectML" Version="1.24.4" />
<PackageReference Include="OpenCvSharp4" Version="4.10.0.20241108" />
<PackageReference Include="OpenCvSharp4.runtime.win" Version="4.10.0.20241108" />
</ItemGroup>
@@ -3,19 +3,23 @@ using HardwareControl.Core.SampleAnalysis;
namespace HardwareControl.Core.HardwareServiceImpl.HardwareService
{
/// <summary>
/// 靶样轮廓与采样点分析服务:基准画面、靶样画面采集与分析。
/// 靶样轮廓与采样点分析服务:抓取相机当前画面并分析。
/// </summary>
public interface ISampleAnalysisService
{
/// <summary>连续抓取多帧并取中值作为基准背景画面。</summary>
Task<SampleBaselineInfo> CaptureBaselineAsync(CancellationToken ct = default);
/// <summary>抓取相机当前画面,提取轮廓并生成采样点。</summary>
SampleAnalysisResult Analyze();
/// <summary>
/// 关闭红外测距光源后抓取当前最新画面作为靶样画面(需先采集基准画面)。
/// 获取最近一次轮廓分析结果供扫描流程复用;
/// 尚未分析过时立即执行一次分析。
/// </summary>
Task<SampleTargetInfo> CaptureTargetAsync(CancellationToken ct = default);
SampleAnalysisResult GetLatestAnalysis();
/// <summary>基于基准画面和靶样画面提取轮廓并生成采样点。</summary>
SampleAnalysisResult Analyze();
/// <summary>
/// 前端等待轮廓识别结果的超时时间(秒),
/// 取自系统参数 camera_Identification_outtime。
/// </summary>
int GetIdentificationTimeoutSeconds();
}
}
@@ -1,3 +1,4 @@
using System.Diagnostics;
using System.Globalization;
using HardwareControl.Core.HardwareServiceImpl.HardwareService;
using HardwareControl.Core.SampleAnalysis;
@@ -8,16 +9,20 @@ using Microsoft.Extensions.Logging;
namespace HardwareControl.Core.HardwareServiceImpl
{
/// <summary>
/// 采集基准画面 / 靶样画面并调用 ONNX 模型分析。
/// 作为单例使用,保存本次检测的画面。
/// 抓取相机当前画面并调用 ONNX 模型分析。
/// 作为单例使用,保存最近一次分析结果供扫描流程复用。
/// </summary>
public sealed class SampleAnalysisService : ISampleAnalysisService
{
private const string SamplingPointConfigName = "camera_sampling_point";
private const string SamplingRadiusConfigName = "camera_sampling_radius";
private const string CameraScaleConfigName = "camera_scale";
private const string IdentificationTimeoutConfigName = "camera_Identification_outtime";
private const int DefaultSamplingPointCount = 5;
private const int MaxSamplingPointCount = 100;
private const int DefaultIdentificationTimeoutSeconds = 60;
private const int MinIdentificationTimeoutSeconds = 5;
private const int MaxIdentificationTimeoutSeconds = 300;
private readonly IUsbCameraService _camera;
private readonly ISystemConfigService _systemConfig;
@@ -25,8 +30,6 @@ namespace HardwareControl.Core.HardwareServiceImpl
private readonly ILogger<SampleAnalysisService> _logger;
private readonly object _gate = new();
private IReadOnlyList<CameraFrameSnapshot>? _baseline;
private CameraFrameSnapshot? _target;
private SampleAnalysisResult? _lastAnalysis;
public SampleAnalysisService(
@@ -41,75 +44,9 @@ namespace HardwareControl.Core.HardwareServiceImpl
_logger = logger;
}
public Task<SampleBaselineInfo> CaptureBaselineAsync(
CancellationToken ct = default)
{
ct.ThrowIfCancellationRequested();
var frame = CaptureLatestFrame();
lock (_gate)
{
_baseline = new[] { frame };
_target = null;
_lastAnalysis = null;
}
_logger.LogInformation(
"基准画面已采集:{Width}x{Height}", frame.Width, frame.Height);
return Task.FromResult(
new SampleBaselineInfo(frame.Width, frame.Height, frame.CapturedAt));
}
public Task<SampleTargetInfo> CaptureTargetAsync(
CancellationToken ct = default)
{
ct.ThrowIfCancellationRequested();
var frame = CaptureLatestFrame();
lock (_gate)
{
if (_baseline is null || _baseline.Count == 0)
{
throw new HardwareException(
HardwareErrorKind.InvalidState,
"尚未采集基准画面,请等待相机画面稳定后再试");
}
_target = frame;
_lastAnalysis = null;
}
_logger.LogInformation(
"靶样画面已采集:{Width}x{Height}", frame.Width, frame.Height);
return Task.FromResult(
new SampleTargetInfo(frame.Width, frame.Height, frame.CapturedAt));
}
public SampleAnalysisResult Analyze()
{
IReadOnlyList<CameraFrameSnapshot> baseline;
CameraFrameSnapshot target;
lock (_gate)
{
baseline = _baseline ?? throw new HardwareException(
HardwareErrorKind.InvalidState,
"尚未采集基准画面,请返回样品放置界面重新检测");
target = _target ?? throw new HardwareException(
HardwareErrorKind.InvalidState,
"尚未采集靶样画面,请返回样品放置界面重新检测");
// 同一组画面重复调用 Analyze 时直接返回缓存,避免重复执行 ONNX 推理。
if (_lastAnalysis is not null)
{
return _lastAnalysis;
}
}
var target = CaptureLatestFrame();
var pointCount = GetSamplingPointCount();
var samplingRadiusPixels = GetSamplingRadiusPixels();
@@ -121,32 +58,83 @@ namespace HardwareControl.Core.HardwareServiceImpl
? $"{samplingRadiusPixels.Value:F1}px"
: "不限制");
var watch = Stopwatch.StartNew();
var result = _analyzer.Analyze(
baseline, target, pointCount, samplingRadiusPixels);
target, pointCount, samplingRadiusPixels);
watch.Stop();
_logger.LogInformation(
"靶样轮廓分析完成:{Width}x{Height},采样点 {PointCount} 个",
"靶样轮廓分析完成:{Width}x{Height},采样点 {PointCount} 个,总耗时 {Elapsed} ms",
result.Width,
result.Height,
result.SamplingPointCount);
result.SamplingPointCount,
watch.ElapsedMilliseconds);
lock (_gate)
{
// 分析期间如果靶样画面已被重新采集,则不缓存本次结果。
if (ReferenceEquals(_target, target))
{
_lastAnalysis = result;
}
_lastAnalysis = result;
}
return result;
}
public SampleAnalysisResult GetLatestAnalysis()
{
lock (_gate)
{
if (_lastAnalysis is not null)
{
return _lastAnalysis;
}
}
return Analyze();
}
private CameraFrameSnapshot CaptureLatestFrame() =>
_camera.GetLatestFrame() ?? throw new HardwareException(
HardwareErrorKind.NotConnected,
"相机尚未产生画面,请确认相机已连接");
/// <summary>
/// 读取系统参数 camera_Identification_outtime(秒),
/// 作为前端等待轮廓识别结果的超时时间;未配置或无效时使用默认值。
/// </summary>
public int GetIdentificationTimeoutSeconds()
{
try
{
var config = _systemConfig
.GetAll()
.FirstOrDefault(c => string.Equals(
c.ConfigName,
IdentificationTimeoutConfigName,
StringComparison.OrdinalIgnoreCase));
if (double.TryParse(
config?.ConfigValue,
NumberStyles.Float,
CultureInfo.InvariantCulture,
out var seconds) &&
seconds > 0)
{
return (int)Math.Clamp(
Math.Round(seconds),
MinIdentificationTimeoutSeconds,
MaxIdentificationTimeoutSeconds);
}
}
catch (Exception ex)
{
_logger.LogWarning(
ex,
"读取系统参数 {ConfigName} 失败,使用默认识别超时时间",
IdentificationTimeoutConfigName);
}
return DefaultIdentificationTimeoutSeconds;
}
private int GetSamplingPointCount()
{
try
@@ -1,283 +0,0 @@
using HardwareControl.Core.UsbCamera;
using OpenCvSharp;
namespace HardwareControl.Core.SampleAnalysis
{
/// <summary>
/// 基于基准帧与靶样帧的 OpenCV 背景差分分割。
/// 用于 ONNX 模型置信度不足或没有输出时兜底。
/// 流程:Lab + CLAHE → 颜色/梯度双差分 → 均值+2σ阈值
/// → 闭运算 + 轮廓填充 → GrabCut 细化。
/// </summary>
public sealed class BackgroundDiffSegmenter
{
private const double MinAreaRatio = 0.0005;
public Mat? BuildMask(
CameraFrameSnapshot baseline,
CameraFrameSnapshot target)
{
using var targetImage = Decode(target, "靶样画面");
using var baselineImage = Decode(baseline, "基准画面");
if (baselineImage.Size() != targetImage.Size())
{
Cv2.Resize(baselineImage, baselineImage, targetImage.Size());
}
using var baselineLab = new Mat();
using var targetLab = new Mat();
using var baselineGray = new Mat();
using var targetGray = new Mat();
Normalize(baselineImage, baselineLab, baselineGray);
Normalize(targetImage, targetLab, targetGray);
using var colorDiff = BuildColorDifference(baselineLab, targetLab);
using var gradientDiff = BuildGradientDifference(baselineGray, targetGray);
using var combined = new Mat();
Cv2.Max(colorDiff, gradientDiff, combined);
Cv2.GaussianBlur(combined, combined, new Size(5, 5), 0);
using var mask = BuildBinaryMask(
combined, targetImage.Width, targetImage.Height);
if (Cv2.CountNonZero(mask) == 0)
{
return null;
}
return RefineWithGrabCut(targetImage, mask);
}
private static Mat Decode(CameraFrameSnapshot frame, string label)
{
var image = Cv2.ImDecode(frame.ImageData, ImreadModes.Color);
if (image.Empty())
{
image.Dispose();
throw new HardwareException(
HardwareErrorKind.InvalidArgument, $"{label}无法解码");
}
return image;
}
/// <summary>Lab 色彩空间 + CLAHE 亮度归一化。</summary>
private static void Normalize(Mat bgr, Mat lab, Mat gray)
{
Cv2.CvtColor(bgr, lab, ColorConversionCodes.BGR2Lab);
var channels = Cv2.Split(lab);
try
{
using var clahe = Cv2.CreateCLAHE(2.0, new Size(8, 8));
clahe.Apply(channels[0], channels[0]);
Cv2.Merge(channels, lab);
channels[0].CopyTo(gray);
}
finally
{
foreach (var channel in channels)
{
channel.Dispose();
}
}
}
/// <summary>Lab 三通道绝对差加权,保留低对比度颜色差异。</summary>
private static Mat BuildColorDifference(Mat lab1, Mat lab2)
{
using var diff = new Mat();
Cv2.Absdiff(lab1, lab2, diff);
var channels = Cv2.Split(diff);
try
{
using var luminance = new Mat();
Cv2.AddWeighted(channels[0], 0.6, channels[1], 0.8, 0, luminance);
var result = new Mat();
Cv2.AddWeighted(luminance, 1.0, channels[2], 0.8, 0, result);
return result;
}
finally
{
foreach (var channel in channels)
{
channel.Dispose();
}
}
}
/// <summary>梯度幅值差分,对低对比度物体边缘更敏感。</summary>
private static Mat BuildGradientDifference(Mat gray1, Mat gray2)
{
using var magnitude1 = GradientMagnitude(gray1);
using var magnitude2 = GradientMagnitude(gray2);
var diff = new Mat();
Cv2.Absdiff(magnitude1, magnitude2, diff);
return diff;
}
private static Mat GradientMagnitude(Mat gray)
{
using var gradientX = new Mat();
using var gradientY = new Mat();
Cv2.Sobel(gray, gradientX, MatType.CV_32F, 1, 0, 3);
Cv2.Sobel(gray, gradientY, MatType.CV_32F, 0, 1, 3);
using var magnitude = new Mat();
Cv2.Magnitude(gradientX, gradientY, magnitude);
var result = new Mat();
Cv2.ConvertScaleAbs(magnitude, result);
return result;
}
/// <summary>
/// 使用均值 + 2σ 阈值,并对闭合边缘做内部填充,
/// 避免低对比度靶样只留下边缘、内部为空。
/// </summary>
private static Mat BuildBinaryMask(
Mat combined, int width, int height)
{
Cv2.MeanStdDev(combined, out var mean, out var stddev);
var threshold = Math.Max(6.0, mean.Val0 + 2.0 * stddev.Val0);
using var raw = new Mat();
Cv2.Threshold(combined, raw, threshold, 255, ThresholdTypes.Binary);
var closeSize = Math.Max(5, Math.Min(width, height) / 120);
if (closeSize % 2 == 0)
{
closeSize++;
}
using (var closeKernel = Cv2.GetStructuringElement(
MorphShapes.Rect, new Size(closeSize, closeSize)))
{
Cv2.MorphologyEx(
raw, raw, MorphTypes.Close, closeKernel, iterations: 2);
}
using var contourInput = raw.Clone();
Cv2.FindContours(
contourInput,
out var contours,
out _,
RetrievalModes.External,
ContourApproximationModes.ApproxSimple);
var mask = new Mat(height, width, MatType.CV_8UC1, Scalar.All(0));
var minArea = width * (double)height * MinAreaRatio;
foreach (var contour in contours)
{
if (Cv2.ContourArea(contour) >= minArea)
{
Cv2.DrawContours(
mask, new[] { contour }, -1, Scalar.All(255), -1);
}
}
var openSize = Math.Max(3, Math.Min(width, height) / 300);
if (openSize % 2 == 0)
{
openSize++;
}
using (var openKernel = Cv2.GetStructuringElement(
MorphShapes.Rect, new Size(openSize, openSize)))
{
Cv2.MorphologyEx(mask, mask, MorphTypes.Open, openKernel);
}
return mask;
}
/// <summary>用差分掩膜初始化 GrabCut,让边界更贴合物品真实边缘。</summary>
private static Mat RefineWithGrabCut(Mat targetImage, Mat mask)
{
if (Cv2.CountNonZero(mask) == 0)
{
return mask.Clone();
}
var bounds = Cv2.BoundingRect(mask);
var padding = Math.Max(
10, Math.Min(targetImage.Width, targetImage.Height) / 100);
var left = Math.Max(0, bounds.X - padding);
var top = Math.Max(0, bounds.Y - padding);
var right = Math.Min(targetImage.Width, bounds.Right + padding);
var bottom = Math.Min(targetImage.Height, bounds.Bottom + padding);
var rect = new Rect(left, top, right - left, bottom - top);
if (rect.Width < 5 || rect.Height < 5)
{
return mask.Clone();
}
using var grabMask = new Mat(
targetImage.Size(),
MatType.CV_8UC1,
Scalar.All((byte)GrabCutClasses.PR_BGD));
grabMask.SetTo(new Scalar((byte)GrabCutClasses.PR_FGD), mask);
using var kernel = Cv2.GetStructuringElement(
MorphShapes.Rect, new Size(5, 5));
using var dilated = new Mat();
Cv2.Dilate(mask, dilated, kernel, iterations: 3);
using var definiteBackground = new Mat();
Cv2.BitwiseNot(dilated, definiteBackground);
grabMask.SetTo(new Scalar((byte)GrabCutClasses.BGD), definiteBackground);
using var backgroundModel = new Mat();
using var foregroundModel = new Mat();
try
{
Cv2.GrabCut(
targetImage,
grabMask,
rect,
backgroundModel,
foregroundModel,
3,
GrabCutModes.InitWithMask);
}
catch (Exception)
{
return mask.Clone();
}
using var foreground = new Mat();
using var probableForeground = new Mat();
Cv2.InRange(
grabMask,
new Scalar((int)GrabCutClasses.FGD),
new Scalar((int)GrabCutClasses.FGD),
foreground);
Cv2.InRange(
grabMask,
new Scalar((int)GrabCutClasses.PR_FGD),
new Scalar((int)GrabCutClasses.PR_FGD),
probableForeground);
var refined = new Mat();
Cv2.BitwiseOr(foreground, probableForeground, refined);
if (Cv2.CountNonZero(refined) == 0)
{
refined.Dispose();
return mask.Clone();
}
return refined;
}
}
}
@@ -0,0 +1,170 @@
using System.Runtime.InteropServices;
namespace HardwareControl.Core.SampleAnalysis
{
/// <summary>
/// 通过 DXGI 枚举本机显卡适配器,用于区分独立显卡与核心显卡。
/// DirectML 执行后端的 device_id 就是 DXGI 适配器序号,因此这里返回的
/// <see cref="GpuAdapter.Index"/> 可直接传给 AppendExecutionProvider_DML。
/// </summary>
internal static class GpuAdapterEnumerator
{
/// <summary>独立显卡的专用显存下限,低于该值视为核显。</summary>
private const ulong DiscreteMemoryThreshold = 1024UL * 1024 * 1024;
private const uint AdapterFlagSoftware = 0x2;
/// <summary>IDXGIFactory1::EnumAdapters1 在虚表中的槽位。</summary>
private const int EnumAdapters1VtableIndex = 12;
/// <summary>IDXGIAdapter1::GetDesc1 在虚表中的槽位。</summary>
private const int GetDesc1VtableIndex = 10;
private static readonly Guid IID_IDXGIFactory1 =
new("770aae78-f26f-4dba-a829-253c83d1b387");
internal sealed record GpuAdapter(
int Index,
string Name,
ulong DedicatedVideoMemory,
bool IsSoftware);
[DllImport("dxgi.dll")]
private static extern int CreateDXGIFactory1(ref Guid riid, out IntPtr factory);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int EnumAdapters1Delegate(
IntPtr self, uint index, out IntPtr adapter);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int GetDesc1Delegate(IntPtr self, out DxgiAdapterDesc1 desc);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct DxgiAdapterDesc1
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public string Description;
public uint VendorId;
public uint DeviceId;
public uint SubSysId;
public uint Revision;
public UIntPtr DedicatedVideoMemory;
public UIntPtr DedicatedSystemMemory;
public UIntPtr SharedSystemMemory;
public uint LuidLowPart;
public int LuidHighPart;
public uint Flags;
}
/// <summary>
/// 按硬件使用类型解析可用的显卡适配器。
/// 指定类型的显卡不存在时退回另一类显卡,完全没有可用显卡时返回 false。
/// </summary>
public static bool TryResolve(
HardwareUsageType usageType, out GpuAdapter adapter)
{
adapter = null!;
if (usageType == HardwareUsageType.Cpu)
{
return false;
}
var devices = Enumerate()
.Where(item => !item.IsSoftware)
.ToList();
if (devices.Count == 0)
{
return false;
}
var discrete = devices
.Where(item => item.DedicatedVideoMemory >= DiscreteMemoryThreshold)
.OrderByDescending(item => item.DedicatedVideoMemory)
.ToList();
var integrated = devices
.Where(item => item.DedicatedVideoMemory < DiscreteMemoryThreshold)
.OrderBy(item => item.DedicatedVideoMemory)
.ToList();
var preferred = usageType == HardwareUsageType.DiscreteGpu
? discrete.Concat(integrated).FirstOrDefault()
: integrated.Concat(discrete).FirstOrDefault();
adapter = preferred!;
return adapter is not null;
}
/// <summary>枚举全部 DXGI 适配器(包含软件适配器),失败时返回空列表。</summary>
public static IReadOnlyList<GpuAdapter> Enumerate()
{
var adapters = new List<GpuAdapter>();
IntPtr factory = IntPtr.Zero;
try
{
var factoryId = IID_IDXGIFactory1;
if (CreateDXGIFactory1(ref factoryId, out factory) < 0 ||
factory == IntPtr.Zero)
{
return adapters;
}
var enumAdapters1 = GetVtableDelegate<EnumAdapters1Delegate>(
factory, EnumAdapters1VtableIndex);
for (uint index = 0; ; index++)
{
if (enumAdapters1(factory, index, out var adapter) < 0 ||
adapter == IntPtr.Zero)
{
break;
}
try
{
var getDesc1 = GetVtableDelegate<GetDesc1Delegate>(
adapter, GetDesc1VtableIndex);
if (getDesc1(adapter, out var desc) >= 0)
{
adapters.Add(new GpuAdapter(
(int)index,
desc.Description ?? string.Empty,
desc.DedicatedVideoMemory.ToUInt64(),
(desc.Flags & AdapterFlagSoftware) != 0));
}
}
finally
{
Marshal.Release(adapter);
}
}
}
catch
{
// DXGI 不可用(老系统/远程会话限制)时返回空列表,调用方回退 CPU。
}
finally
{
if (factory != IntPtr.Zero)
{
Marshal.Release(factory);
}
}
return adapters;
}
private static T GetVtableDelegate<T>(IntPtr instance, int vtableIndex)
where T : Delegate
{
var vtable = Marshal.ReadIntPtr(instance);
var method = Marshal.ReadIntPtr(vtable, vtableIndex * IntPtr.Size);
return Marshal.GetDelegateForFunctionPointer<T>(method);
}
}
}
@@ -1,5 +1,18 @@
namespace HardwareControl.Core.SampleAnalysis
{
/// <summary>硬件使用类型,对应系统参数 hardware_usage_type。</summary>
public enum HardwareUsageType
{
/// <summary>仅使用 CPU。</summary>
Cpu = 1,
/// <summary>使用独立显卡(DirectML)。</summary>
DiscreteGpu = 2,
/// <summary>使用核心显卡(DirectML)。</summary>
IntegratedGpu = 3,
}
/// <summary>靶样 ONNX 分割模型配置。</summary>
public sealed class OnnxSegmentationOptions
{
@@ -18,11 +31,20 @@ namespace HardwareControl.Core.SampleAnalysis
public int InputHeight { get; set; } = 640;
/// <summary>
/// 推理执行后端:Auto(优先 DirectML,不可用时回退 CPU)、DirectML、Cpu。
/// DirectML 可调用核显/独显,同时保留 CPU 算子回退。
/// </summary>
public string ExecutionProvider { get; set; } = "Auto";
/// <summary>DirectML 设备序号,0 表示系统默认适配器。</summary>
public int DmlDeviceId { get; set; }
/// <summary>YOLO 分割模型的目标置信度阈值。</summary>
public double ConfidenceThreshold { get; set; } = 0.25;
/// <summary>
/// 模型置信度低于该值时,使用 OpenCV 背景差分兜底识别轮廓。
/// 模型置信度低于该值时,继续尝试后续模型,取置信度最高的结果。
/// </summary>
public double FallbackConfidenceThreshold { get; set; } = 0.6;
@@ -1,17 +1,5 @@
namespace HardwareControl.Core.SampleAnalysis
{
/// <summary>基准画面信息(放置靶样前)。</summary>
public sealed record SampleBaselineInfo(
int Width,
int Height,
DateTimeOffset CapturedAt);
/// <summary>靶样画面信息(放置靶样后)。</summary>
public sealed record SampleTargetInfo(
int Width,
int Height,
DateTimeOffset CapturedAt);
/// <summary>图像坐标系下的采样点。</summary>
public sealed record SamplePoint(int X, int Y);
@@ -1,5 +1,7 @@
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using HardwareControl.Core.HardwareServiceImpl.HardwareService;
using HardwareControl.Core.UsbCamera;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
@@ -12,34 +14,43 @@ namespace HardwareControl.Core.SampleAnalysis
/// <summary>
/// 基于多个 ONNX 模型的靶样分割与采样点规划。
/// 模型目录内按文件名前面的数字从小到大依次尝试;
/// 模型置信度不足或没有输出时,使用 OpenCV 背景差分兜底。
/// 模型置信度不足或没有输出时继续尝试后续模型。
/// 支持检测框、YOLO 分割、检测+掩膜、二值/语义分割输出。
/// </summary>
public sealed class TargetOutlineAnalyzer : IDisposable
{
private const string HardwareUsageTypeConfigName = "hardware_usage_type";
private readonly OnnxSegmentationOptions _options;
private readonly ILogger<TargetOutlineAnalyzer> _logger;
private readonly BackgroundDiffSegmenter _backgroundDiff;
private readonly ISystemConfigService _systemConfig;
private readonly object _gate = new();
private readonly Dictionary<string, InferenceSession> _sessions =
new(StringComparer.OrdinalIgnoreCase);
private ProviderSelection _provider;
private bool _providerApplied;
public TargetOutlineAnalyzer(
IOptions<OnnxSegmentationOptions> options,
BackgroundDiffSegmenter backgroundDiff,
ISystemConfigService systemConfig,
ILogger<TargetOutlineAnalyzer> logger)
{
_options = options.Value;
_backgroundDiff = backgroundDiff;
_systemConfig = systemConfig;
_logger = logger;
_provider = ResolveProviderFromOptions();
}
/// <summary>当前生效的推理后端;<see cref="ProviderSelection.Label"/> 用于日志。</summary>
private readonly record struct ProviderSelection(
bool UseDirectMl, int DeviceId, string Label);
private int InputWidth => Math.Max(32, _options.InputWidth);
private int InputHeight => Math.Max(32, _options.InputHeight);
public SampleAnalysisResult Analyze(
IReadOnlyList<CameraFrameSnapshot> baselineFrames,
CameraFrameSnapshot target,
int samplingPointCount,
double? samplingRadiusPixels = null)
@@ -52,6 +63,8 @@ namespace HardwareControl.Core.SampleAnalysis
lock (_gate)
{
ApplyHardwareUsageType();
var models = ResolveModelFiles();
CleanupSessions(models);
@@ -67,6 +80,7 @@ namespace HardwareControl.Core.SampleAnalysis
foreach (var modelPath in models)
{
var modelName = Path.GetFileName(modelPath);
var modelWatch = Stopwatch.StartNew();
try
{
var result = TryAnalyzeWithModel(
@@ -77,6 +91,12 @@ namespace HardwareControl.Core.SampleAnalysis
out var confidence,
out var failureReason);
modelWatch.Stop();
_logger.LogInformation(
"模型 {Model} 分析耗时 {Elapsed} ms",
modelName,
modelWatch.ElapsedMilliseconds);
if (result is not null)
{
if (confidence >= _options.FallbackConfidenceThreshold)
@@ -100,7 +120,7 @@ namespace HardwareControl.Core.SampleAnalysis
$"{_options.FallbackConfidenceThreshold:F2}");
_logger.LogInformation(
"模型 {Model} 置信度 {Confidence:F2} 较低," +
"继续尝试后续模型或使用 OpenCV 兜底",
"继续尝试后续模型",
modelName,
confidence);
continue;
@@ -119,57 +139,10 @@ namespace HardwareControl.Core.SampleAnalysis
}
}
// 模型置信度不足或没有结果:使用基准帧与靶样帧做 OpenCV 背景差分
if (baselineFrames.Count > 0)
{
_logger.LogInformation(
"ONNX 模型未达到置信度要求,启用 OpenCV 背景差分兜底");
try
{
using var fallbackMask = _backgroundDiff.BuildMask(
baselineFrames[0], target);
if (fallbackMask is not null)
{
var fallbackResult = BuildResultFromMask(
fallbackMask,
targetImage,
pointCount,
samplingRadiusPixels,
out var fallbackFailure);
if (fallbackResult is not null)
{
_logger.LogInformation("OpenCV 背景差分兜底识别成功");
return fallbackResult;
}
_logger.LogWarning(
"OpenCV 兜底未生成有效轮廓:{Reason}", fallbackFailure);
attempts.Add($"OpenCV 兜底:{fallbackFailure}");
}
else
{
_logger.LogWarning("OpenCV 兜底未检测到前后画面差异");
attempts.Add("OpenCV 兜底:未检测到前后画面差异");
}
}
catch (Exception ex)
{
_logger.LogWarning(ex, "OpenCV 兜底执行失败");
attempts.Add($"OpenCV 兜底:{ex.Message}");
}
}
else
{
_logger.LogWarning("没有基准画面,跳过 OpenCV 兜底");
}
if (lowConfidenceResult is not null)
{
_logger.LogWarning(
"OpenCV 兜底失败,返回置信度较低的模型结果:{Model}({Confidence:F2})",
"没有更高置信度的模型结果,返回置信度较低的模型结果:{Model}({Confidence:F2})",
lowConfidenceModel,
lowConfidence);
return lowConfidenceResult;
@@ -186,12 +159,46 @@ namespace HardwareControl.Core.SampleAnalysis
{
lock (_gate)
{
foreach (var session in _sessions.Values)
DisposeSessions();
}
}
private void DisposeSessions()
{
foreach (var session in _sessions.Values)
{
session.Dispose();
}
_sessions.Clear();
}
/// <summary>
/// 预加载首个 ONNX 模型。大模型(数百 MB)首次加载往往需要数十秒,
/// 在程序启动后放到后台执行,可避免用户点击检测时才等待模型加载。
/// </summary>
public void PreloadPrimaryModel()
{
lock (_gate)
{
ApplyHardwareUsageType();
var models = ResolveModelFiles();
CleanupSessions(models);
if (models.Count == 0)
{
session.Dispose();
return;
}
_sessions.Clear();
var watch = Stopwatch.StartNew();
GetSession(models[0]);
watch.Stop();
_logger.LogInformation(
"首个 ONNX 模型预热完成:{Model},耗时 {Elapsed} ms",
Path.GetFileName(models[0]),
watch.ElapsedMilliseconds);
}
}
@@ -240,7 +247,15 @@ namespace HardwareControl.Core.SampleAnalysis
var inputValue = CreateInputValue(
input.Key, letterboxed, inputWidth, inputHeight);
var inferenceWatch = Stopwatch.StartNew();
using var results = session.Run(new[] { inputValue });
inferenceWatch.Stop();
_logger.LogInformation(
"模型 {Model} 推理耗时 {Elapsed} ms(输入 {Width}x{Height})",
Path.GetFileName(modelPath),
inferenceWatch.ElapsedMilliseconds,
inputWidth,
inputHeight);
var outputs = new List<OutputTensor>();
foreach (var result in results)
@@ -314,13 +329,15 @@ namespace HardwareControl.Core.SampleAnalysis
lineThickness,
LineTypes.AntiAlias);
using var distanceMap = BuildDistanceMap(mask);
var points = BuildSamplingPoints(
contour,
pointCount,
CalculateSamplingMargin(contour, outputImage.Width, outputImage.Height),
samplingRadiusPixels,
outputImage.Width / 2.0,
outputImage.Height / 2.0);
outputImage.Height / 2.0,
distanceMap);
DrawSamplingPoints(outputImage, points, lineThickness);
Cv2.ImEncode(
@@ -421,15 +438,14 @@ namespace HardwareControl.Core.SampleAnalysis
try
{
var options = new SessionOptions
{
GraphOptimizationLevel = GraphOptimizationLevel.ORT_ENABLE_ALL,
};
using var options = CreateSessionOptions(out var providerName);
var session = new InferenceSession(modelPath, options);
_sessions[modelPath] = session;
_logger.LogInformation(
"ONNX Runtime 模型已加载:{Model}", Path.GetFileName(modelPath));
"ONNX Runtime 模型已加载:{Model},执行后端:{Provider}",
Path.GetFileName(modelPath),
providerName);
return session;
}
catch (Exception ex)
@@ -441,6 +457,139 @@ namespace HardwareControl.Core.SampleAnalysis
}
}
/// <summary>
/// 读取系统参数 hardware_usage_type,与当前生效配置不同时重建会话,
/// 使运行中修改该参数后下一次分析即可切换推理后端。
/// </summary>
private void ApplyHardwareUsageType()
{
var selection = ResolveProvider();
if (_providerApplied && selection == _provider)
{
return;
}
DisposeSessions();
_provider = selection;
_providerApplied = true;
_logger.LogInformation("ONNX 推理硬件模式:{Provider}", selection.Label);
}
private ProviderSelection ResolveProvider()
{
var usageType = ReadHardwareUsageType();
if (usageType is null)
{
return ResolveProviderFromOptions();
}
if (usageType == HardwareUsageType.Cpu)
{
return new ProviderSelection(
false, 0, "CPU(hardware_usage_type=1)");
}
var label = usageType == HardwareUsageType.DiscreteGpu
? "独立GPU"
: "核心GPU";
if (GpuAdapterEnumerator.TryResolve(usageType.Value, out var adapter))
{
return new ProviderSelection(
true,
adapter.Index,
$"DirectML {label}(设备 {adapter.Index}:{adapter.Name})");
}
_logger.LogWarning(
"hardware_usage_type={UsageType}({Label})未找到可用显卡,回退 CPU 推理",
(int)usageType.Value,
label);
return new ProviderSelection(false, 0, "CPU(未找到可用显卡)");
}
private ProviderSelection ResolveProviderFromOptions()
{
var requested = string.IsNullOrWhiteSpace(_options.ExecutionProvider)
? "Auto"
: _options.ExecutionProvider.Trim();
if (requested.Equals("Cpu", StringComparison.OrdinalIgnoreCase))
{
return new ProviderSelection(false, 0, "CPU");
}
var deviceId = Math.Max(0, _options.DmlDeviceId);
return new ProviderSelection(true, deviceId, $"DirectML(设备 {deviceId})");
}
private HardwareUsageType? ReadHardwareUsageType()
{
try
{
var config = _systemConfig
.GetAll()
.FirstOrDefault(item => string.Equals(
item.ConfigName,
HardwareUsageTypeConfigName,
StringComparison.OrdinalIgnoreCase));
if (int.TryParse(config?.ConfigValue?.Trim(), out var value) &&
Enum.IsDefined(typeof(HardwareUsageType), value))
{
return (HardwareUsageType)value;
}
}
catch (Exception ex)
{
_logger.LogWarning(
ex,
"读取系统参数 {ConfigName} 失败,沿用 appsettings 的推理配置",
HardwareUsageTypeConfigName);
}
return null;
}
/// <summary>
/// 按当前硬件模式创建会话选项:DirectML 不支持的算子由 ONNX Runtime 自动回退到 CPU。
/// </summary>
private SessionOptions CreateSessionOptions(out string providerName)
{
if (!_provider.UseDirectMl)
{
providerName = _provider.Label;
return CreateCpuOptions();
}
var options = new SessionOptions
{
GraphOptimizationLevel = GraphOptimizationLevel.ORT_ENABLE_ALL,
// DirectML 不支持内存复用模式
EnableMemoryPattern = false,
};
try
{
options.AppendExecutionProvider_DML(_provider.DeviceId);
providerName = _provider.Label;
return options;
}
catch (Exception ex)
{
options.Dispose();
_logger.LogWarning(ex, "DirectML 初始化失败,回退 CPU 推理");
providerName = "CPU(DirectML 不可用)";
return CreateCpuOptions();
}
}
private static SessionOptions CreateCpuOptions() => new()
{
GraphOptimizationLevel = GraphOptimizationLevel.ORT_ENABLE_ALL,
};
private void CleanupSessions(IReadOnlyCollection<string> currentModels)
{
var current = new HashSet<string>(currentModels, StringComparer.OrdinalIgnoreCase);
@@ -1243,6 +1392,18 @@ namespace HardwareControl.Core.SampleAnalysis
return Math.Max(markerRadius + 4, ratioMargin);
}
/// <summary>
/// 计算掩膜内每个像素到最近边界的距离,供采样点校验一次查表完成,
/// 避免在重试缩放间距时反复对整条轮廓做 PointPolygonTest。
/// </summary>
private static Mat BuildDistanceMap(Mat mask)
{
var distanceMap = new Mat();
Cv2.DistanceTransform(
mask, distanceMap, DistanceTypes.L2, DistanceTransformMasks.Mask5);
return distanceMap;
}
/// <summary>
/// 在轮廓内部按网格生成候选点,要求候选点到轮廓的距离不小于安全边距;
/// 配置采样半径时,候选点还须位于以画面中心为原点的半径范围内。
@@ -1254,7 +1415,8 @@ namespace HardwareControl.Core.SampleAnalysis
double margin,
double? radiusPixels,
double centerX,
double centerY)
double centerY,
Mat distanceMap)
{
var area = Cv2.ContourArea(contour);
if (area <= 0 || count <= 0)
@@ -1285,9 +1447,7 @@ namespace HardwareControl.Core.SampleAnalysis
continue;
}
var distance = Cv2.PointPolygonTest(
contour, new Point2f(point.X, point.Y), true);
if (distance >= margin)
if (distanceMap.At<float>(point.Y, point.X) >= margin)
{
candidates.Add(point);
}
@@ -1306,7 +1466,7 @@ namespace HardwareControl.Core.SampleAnalysis
{
// 极窄轮廓可能无法满足安全边距,退回到离边缘最远的内部点
var fallback = FindBestInteriorPoint(
contour, radiusPixels, centerX, centerY);
contour, radiusPixels, centerX, centerY, distanceMap);
return fallback.HasValue
? new List<Point> { fallback.Value }
: new List<Point>();
@@ -1353,7 +1513,11 @@ namespace HardwareControl.Core.SampleAnalysis
/// <summary>找到轮廓内部距边缘最远的点,作为极端情况下的兜底。</summary>
private static Point? FindBestInteriorPoint(
Point[] contour, double? radiusPixels, double centerX, double centerY)
Point[] contour,
double? radiusPixels,
double centerX,
double centerY,
Mat distanceMap)
{
var rect = Cv2.BoundingRect(contour);
var step = Math.Max(2, Math.Min(rect.Width, rect.Height) / 50);
@@ -1370,8 +1534,7 @@ namespace HardwareControl.Core.SampleAnalysis
continue;
}
var distance = Cv2.PointPolygonTest(
contour, new Point2f(x, y), true);
var distance = distanceMap.At<float>(y, x);
if (distance > bestDistance)
{
@@ -127,7 +127,7 @@ namespace HardwareControl.Core.Scanning
await _spectrometer.ConnectAsync(ct);
}
var sample = _sampleAnalysis.Analyze();
var sample = _sampleAnalysis.GetLatestAnalysis();
if (sample.SamplingPoints.Count == 0)
{
throw new HardwareException(