提交代码
This commit is contained in:
@@ -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)
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user