1376 lines
46 KiB
C#
1376 lines
46 KiB
C#
using System.Runtime.InteropServices;
|
||
using System.Text.RegularExpressions;
|
||
using HardwareControl.Core.UsbCamera;
|
||
using Microsoft.Extensions.Logging;
|
||
using Microsoft.Extensions.Options;
|
||
using Microsoft.ML.OnnxRuntime;
|
||
using Microsoft.ML.OnnxRuntime.Tensors;
|
||
using OpenCvSharp;
|
||
|
||
namespace HardwareControl.Core.SampleAnalysis
|
||
{
|
||
/// <summary>
|
||
/// 基于多个 ONNX 模型的靶样分割与采样点规划。
|
||
/// 模型目录内按文件名前面的数字从小到大依次尝试;
|
||
/// 模型置信度不足或没有输出时,使用 OpenCV 背景差分兜底。
|
||
/// 支持检测框、YOLO 分割、检测+掩膜、二值/语义分割输出。
|
||
/// </summary>
|
||
public sealed class TargetOutlineAnalyzer : IDisposable
|
||
{
|
||
private readonly OnnxSegmentationOptions _options;
|
||
private readonly ILogger<TargetOutlineAnalyzer> _logger;
|
||
private readonly BackgroundDiffSegmenter _backgroundDiff;
|
||
private readonly object _gate = new();
|
||
private readonly Dictionary<string, InferenceSession> _sessions =
|
||
new(StringComparer.OrdinalIgnoreCase);
|
||
|
||
public TargetOutlineAnalyzer(
|
||
IOptions<OnnxSegmentationOptions> options,
|
||
BackgroundDiffSegmenter backgroundDiff,
|
||
ILogger<TargetOutlineAnalyzer> logger)
|
||
{
|
||
_options = options.Value;
|
||
_backgroundDiff = backgroundDiff;
|
||
_logger = logger;
|
||
}
|
||
|
||
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)
|
||
{
|
||
ArgumentNullException.ThrowIfNull(target);
|
||
|
||
var pointCount = Math.Max(1, samplingPointCount);
|
||
|
||
using var targetImage = Decode(target, "靶样画面");
|
||
|
||
lock (_gate)
|
||
{
|
||
var models = ResolveModelFiles();
|
||
CleanupSessions(models);
|
||
|
||
_logger.LogInformation(
|
||
"按顺序尝试 ONNX 模型:{Models}",
|
||
string.Join(" -> ", models.Select(Path.GetFileName)));
|
||
|
||
var attempts = new List<string>();
|
||
SampleAnalysisResult? lowConfidenceResult = null;
|
||
var lowConfidence = 0f;
|
||
string? lowConfidenceModel = null;
|
||
|
||
foreach (var modelPath in models)
|
||
{
|
||
var modelName = Path.GetFileName(modelPath);
|
||
try
|
||
{
|
||
var result = TryAnalyzeWithModel(
|
||
modelPath,
|
||
targetImage,
|
||
pointCount,
|
||
out var confidence,
|
||
out var failureReason);
|
||
|
||
if (result is not null)
|
||
{
|
||
if (confidence >= _options.FallbackConfidenceThreshold)
|
||
{
|
||
_logger.LogInformation(
|
||
"模型 {Model} 识别成功,置信度 {Confidence:F2}",
|
||
modelName,
|
||
confidence);
|
||
return result;
|
||
}
|
||
|
||
if (lowConfidenceResult is null || confidence > lowConfidence)
|
||
{
|
||
lowConfidenceResult = result;
|
||
lowConfidence = confidence;
|
||
lowConfidenceModel = modelName;
|
||
}
|
||
|
||
attempts.Add(
|
||
$"{modelName}:置信度 {confidence:F2} 低于阈值 " +
|
||
$"{_options.FallbackConfidenceThreshold:F2}");
|
||
_logger.LogInformation(
|
||
"模型 {Model} 置信度 {Confidence:F2} 较低," +
|
||
"继续尝试后续模型或使用 OpenCV 兜底",
|
||
modelName,
|
||
confidence);
|
||
continue;
|
||
}
|
||
|
||
attempts.Add($"{modelName}:{failureReason}");
|
||
_logger.LogInformation(
|
||
"模型 {Model} 未产生有效轮廓:{Reason}",
|
||
modelName,
|
||
failureReason);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
attempts.Add($"{modelName}:{ex.Message}");
|
||
_logger.LogWarning(ex, "模型 {Model} 执行失败", modelName);
|
||
}
|
||
}
|
||
|
||
// 模型置信度不足或没有结果:使用基准帧与靶样帧做 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,
|
||
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})",
|
||
lowConfidenceModel,
|
||
lowConfidence);
|
||
return lowConfidenceResult;
|
||
}
|
||
|
||
throw new HardwareException(
|
||
HardwareErrorKind.InvalidState,
|
||
$"已按顺序尝试 {models.Count} 个模型,均未识别到靶样。" +
|
||
string.Join(";", attempts));
|
||
}
|
||
}
|
||
|
||
public void Dispose()
|
||
{
|
||
lock (_gate)
|
||
{
|
||
foreach (var session in _sessions.Values)
|
||
{
|
||
session.Dispose();
|
||
}
|
||
|
||
_sessions.Clear();
|
||
}
|
||
}
|
||
|
||
private SampleAnalysisResult? TryAnalyzeWithModel(
|
||
string modelPath,
|
||
Mat targetImage,
|
||
int pointCount,
|
||
out float confidence,
|
||
out string failureReason)
|
||
{
|
||
confidence = 1f;
|
||
failureReason = string.Empty;
|
||
var session = GetSession(modelPath);
|
||
|
||
if (session.InputMetadata.Count != 1)
|
||
{
|
||
failureReason = $"模型需要 {session.InputMetadata.Count} 个输入,仅支持单图像输入";
|
||
return null;
|
||
}
|
||
|
||
var input = session.InputMetadata.First();
|
||
if (input.Value.ElementType != typeof(float))
|
||
{
|
||
failureReason = $"输入类型 {input.Value.ElementType} 不支持";
|
||
return null;
|
||
}
|
||
|
||
var dimensions = input.Value.Dimensions;
|
||
var inputHeight = dimensions.Length == 4 && dimensions[2] > 0
|
||
? dimensions[2]
|
||
: InputHeight;
|
||
var inputWidth = dimensions.Length == 4 && dimensions[3] > 0
|
||
? dimensions[3]
|
||
: InputWidth;
|
||
|
||
using var letterboxed = CreateLetterbox(
|
||
targetImage,
|
||
inputWidth,
|
||
inputHeight,
|
||
out var padX,
|
||
out var padY,
|
||
out var contentWidth,
|
||
out var contentHeight);
|
||
|
||
var inputValue = CreateInputValue(
|
||
input.Key, letterboxed, inputWidth, inputHeight);
|
||
|
||
using var results = session.Run(new[] { inputValue });
|
||
|
||
var outputs = new List<OutputTensor>();
|
||
foreach (var result in results)
|
||
{
|
||
var tensor = result.AsTensor<float>();
|
||
outputs.Add(new OutputTensor(
|
||
result.Name,
|
||
tensor.Dimensions.ToArray(),
|
||
tensor.ToArray()));
|
||
}
|
||
|
||
using var rawMask = DecodeOutputs(
|
||
outputs, inputWidth, inputHeight, out confidence, out failureReason);
|
||
|
||
if (rawMask is null)
|
||
{
|
||
return null;
|
||
}
|
||
|
||
using var mask = RestoreToOriginal(
|
||
rawMask,
|
||
inputWidth,
|
||
inputHeight,
|
||
padX,
|
||
padY,
|
||
contentWidth,
|
||
contentHeight,
|
||
targetImage.Size());
|
||
|
||
return BuildResultFromMask(
|
||
mask, targetImage, pointCount, out failureReason);
|
||
}
|
||
|
||
/// <summary>用掩膜提取轮廓、绘制采样点并编码结果图。</summary>
|
||
private SampleAnalysisResult? BuildResultFromMask(
|
||
Mat mask,
|
||
Mat targetImage,
|
||
int pointCount,
|
||
out string failureReason)
|
||
{
|
||
failureReason = string.Empty;
|
||
|
||
Cv2.FindContours(
|
||
mask,
|
||
out var contours,
|
||
out _,
|
||
RetrievalModes.External,
|
||
ContourApproximationModes.ApproxSimple);
|
||
|
||
Point[] contour;
|
||
try
|
||
{
|
||
contour = SelectContour(contours, targetImage.Width, targetImage.Height);
|
||
}
|
||
catch (HardwareException ex)
|
||
{
|
||
failureReason = ex.Message;
|
||
return null;
|
||
}
|
||
|
||
using var outputImage = targetImage.Clone();
|
||
|
||
var lineThickness = Math.Max(
|
||
2, Math.Min(outputImage.Width, outputImage.Height) / 400);
|
||
Cv2.DrawContours(
|
||
outputImage,
|
||
new[] { contour },
|
||
-1,
|
||
new Scalar(0, 255, 0),
|
||
lineThickness,
|
||
LineTypes.AntiAlias);
|
||
|
||
var points = BuildSamplingPoints(
|
||
contour,
|
||
pointCount,
|
||
CalculateSamplingMargin(contour, outputImage.Width, outputImage.Height));
|
||
DrawSamplingPoints(outputImage, points, lineThickness);
|
||
|
||
Cv2.ImEncode(
|
||
".jpg",
|
||
outputImage,
|
||
out var encoded,
|
||
new ImageEncodingParam(ImwriteFlags.JpegQuality, 92));
|
||
|
||
return new SampleAnalysisResult(
|
||
encoded,
|
||
"image/jpeg",
|
||
outputImage.Width,
|
||
outputImage.Height,
|
||
points.Count,
|
||
points.Select(p => new SamplePoint(p.X, p.Y)).ToList());
|
||
}
|
||
|
||
private List<string> ResolveModelFiles()
|
||
{
|
||
if (!string.IsNullOrWhiteSpace(_options.ModelDirectory))
|
||
{
|
||
var directory = ResolvePath(_options.ModelDirectory!);
|
||
if (!Directory.Exists(directory))
|
||
{
|
||
throw new HardwareException(
|
||
HardwareErrorKind.InvalidState,
|
||
$"未找到 ONNX 模型目录:{directory}");
|
||
}
|
||
|
||
var files = Directory
|
||
.GetFiles(directory, "*.onnx", SearchOption.AllDirectories)
|
||
.ToList();
|
||
|
||
if (files.Count == 0)
|
||
{
|
||
throw new HardwareException(
|
||
HardwareErrorKind.InvalidState,
|
||
$"ONNX 模型目录为空:{directory}");
|
||
}
|
||
|
||
var numbered = files
|
||
.Select(path => (
|
||
Path: path,
|
||
Number: ParseLeadingNumber(Path.GetFileName(path))))
|
||
.Where(item => item.Number.HasValue)
|
||
.OrderBy(item => item.Number!.Value)
|
||
.ThenBy(item => Path.GetFileName(item.Path), StringComparer.OrdinalIgnoreCase)
|
||
.Select(item => item.Path)
|
||
.ToList();
|
||
|
||
if (numbered.Count > 0)
|
||
{
|
||
return numbered;
|
||
}
|
||
|
||
return files
|
||
.OrderBy(Path.GetFileName, StringComparer.OrdinalIgnoreCase)
|
||
.ToList();
|
||
}
|
||
|
||
if (!string.IsNullOrWhiteSpace(_options.ModelPath))
|
||
{
|
||
var single = ResolvePath(_options.ModelPath!);
|
||
if (!File.Exists(single))
|
||
{
|
||
throw new HardwareException(
|
||
HardwareErrorKind.InvalidState,
|
||
$"未找到 ONNX 模型:{single}");
|
||
}
|
||
|
||
return new List<string> { single };
|
||
}
|
||
|
||
throw new HardwareException(
|
||
HardwareErrorKind.InvalidState,
|
||
"未配置 ONNX 模型目录或模型路径");
|
||
}
|
||
|
||
private static int? ParseLeadingNumber(string fileName)
|
||
{
|
||
var match = Regex.Match(fileName, @"^(\d+)");
|
||
return match.Success && int.TryParse(match.Groups[1].Value, out var value)
|
||
? value
|
||
: null;
|
||
}
|
||
|
||
private static string ResolvePath(string path) =>
|
||
Path.IsPathRooted(path)
|
||
? path
|
||
: Path.Combine(AppContext.BaseDirectory, path);
|
||
|
||
private InferenceSession GetSession(string modelPath)
|
||
{
|
||
if (_sessions.TryGetValue(modelPath, out var existing))
|
||
{
|
||
return existing;
|
||
}
|
||
|
||
try
|
||
{
|
||
var options = new SessionOptions
|
||
{
|
||
GraphOptimizationLevel = GraphOptimizationLevel.ORT_ENABLE_ALL,
|
||
};
|
||
|
||
var session = new InferenceSession(modelPath, options);
|
||
_sessions[modelPath] = session;
|
||
_logger.LogInformation(
|
||
"ONNX Runtime 模型已加载:{Model}", Path.GetFileName(modelPath));
|
||
return session;
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
throw new HardwareException(
|
||
HardwareErrorKind.InvalidState,
|
||
$"模型加载失败:{ex.Message}",
|
||
ex);
|
||
}
|
||
}
|
||
|
||
private void CleanupSessions(IReadOnlyCollection<string> currentModels)
|
||
{
|
||
var current = new HashSet<string>(currentModels, StringComparer.OrdinalIgnoreCase);
|
||
|
||
foreach (var path in _sessions.Keys.Where(p => !current.Contains(p)).ToList())
|
||
{
|
||
_sessions[path].Dispose();
|
||
_sessions.Remove(path);
|
||
}
|
||
}
|
||
|
||
private NamedOnnxValue CreateInputValue(
|
||
string inputName, Mat letterboxed, int width, int height)
|
||
{
|
||
using var rgb = new Mat();
|
||
if (_options.SwapRB)
|
||
{
|
||
Cv2.CvtColor(letterboxed, rgb, ColorConversionCodes.BGR2RGB);
|
||
}
|
||
else
|
||
{
|
||
letterboxed.CopyTo(rgb);
|
||
}
|
||
|
||
using var floatImage = new Mat();
|
||
rgb.ConvertTo(floatImage, MatType.CV_32FC3, _options.Scale);
|
||
|
||
var tensor = new DenseTensor<float>(new[] { 1, 3, height, width });
|
||
var buffer = tensor.Buffer.Span;
|
||
var plane = width * height;
|
||
var temp = new float[plane];
|
||
|
||
var channels = Cv2.Split(floatImage);
|
||
try
|
||
{
|
||
for (var i = 0; i < 3; i++)
|
||
{
|
||
Marshal.Copy(channels[i].Data, temp, 0, plane);
|
||
temp.CopyTo(buffer.Slice(i * plane, plane));
|
||
}
|
||
}
|
||
finally
|
||
{
|
||
foreach (var channel in channels)
|
||
{
|
||
channel.Dispose();
|
||
}
|
||
}
|
||
|
||
return NamedOnnxValue.CreateFromTensor(inputName, tensor);
|
||
}
|
||
|
||
private Mat CreateLetterbox(
|
||
Mat image,
|
||
int inputWidth,
|
||
int inputHeight,
|
||
out int padX,
|
||
out int padY,
|
||
out int contentWidth,
|
||
out int contentHeight)
|
||
{
|
||
var scale = Math.Min(
|
||
inputWidth / (double)image.Width,
|
||
inputHeight / (double)image.Height);
|
||
|
||
contentWidth = Math.Max(1, (int)Math.Round(image.Width * scale));
|
||
contentHeight = Math.Max(1, (int)Math.Round(image.Height * scale));
|
||
padX = (inputWidth - contentWidth) / 2;
|
||
padY = (inputHeight - contentHeight) / 2;
|
||
|
||
var canvas = new Mat(
|
||
inputHeight,
|
||
inputWidth,
|
||
MatType.CV_8UC3,
|
||
Scalar.All(_options.LetterboxPadValue));
|
||
|
||
try
|
||
{
|
||
using var resized = new Mat();
|
||
Cv2.Resize(
|
||
image,
|
||
resized,
|
||
new Size(contentWidth, contentHeight),
|
||
0,
|
||
0,
|
||
InterpolationFlags.Linear);
|
||
|
||
using var roi = new Mat(
|
||
canvas, new Rect(padX, padY, contentWidth, contentHeight));
|
||
resized.CopyTo(roi);
|
||
}
|
||
catch
|
||
{
|
||
canvas.Dispose();
|
||
throw;
|
||
}
|
||
|
||
return canvas;
|
||
}
|
||
|
||
private Mat RestoreToOriginal(
|
||
Mat mask,
|
||
int inputWidth,
|
||
int inputHeight,
|
||
int padX,
|
||
int padY,
|
||
int contentWidth,
|
||
int contentHeight,
|
||
Size originalSize)
|
||
{
|
||
using var resized = new Mat();
|
||
Cv2.Resize(
|
||
mask,
|
||
resized,
|
||
new Size(inputWidth, inputHeight),
|
||
0,
|
||
0,
|
||
InterpolationFlags.Linear);
|
||
|
||
using var roi = new Mat(
|
||
resized, new Rect(padX, padY, contentWidth, contentHeight));
|
||
|
||
var result = new Mat();
|
||
Cv2.Resize(
|
||
roi,
|
||
result,
|
||
originalSize,
|
||
0,
|
||
0,
|
||
InterpolationFlags.Linear);
|
||
Cv2.Threshold(result, result, 127, 255, ThresholdTypes.Binary);
|
||
return result;
|
||
}
|
||
|
||
private Mat? DecodeOutputs(
|
||
IReadOnlyList<OutputTensor> outputs,
|
||
int inputWidth,
|
||
int inputHeight,
|
||
out float confidence,
|
||
out string failureReason)
|
||
{
|
||
confidence = 1f;
|
||
failureReason = string.Empty;
|
||
|
||
// 检测 + 分类分数 + 掩膜(例如 dets / labels / masks)
|
||
var maskTensor = outputs.FirstOrDefault(
|
||
output => output.Dimensions.Length == 4);
|
||
var detTensor = outputs.FirstOrDefault(
|
||
output => output.Dimensions.Length == 3 &&
|
||
output.Dimensions[2] == 4);
|
||
var labelTensor = outputs.FirstOrDefault(
|
||
output => output.Dimensions.Length == 3 &&
|
||
output.Dimensions[2] > 10);
|
||
|
||
if (maskTensor is not null && detTensor is not null && labelTensor is not null)
|
||
{
|
||
return DecodeDetectionMasks(
|
||
maskTensor, labelTensor, out confidence, out failureReason);
|
||
}
|
||
|
||
// YOLO-seg:预测张量 + mask proto
|
||
var predictionTensor = outputs.FirstOrDefault(
|
||
output => output.Dimensions.Length == 3);
|
||
var protoTensor = outputs.FirstOrDefault(
|
||
output => output.Dimensions.Length == 4 &&
|
||
output.Dimensions[1] <= 64);
|
||
|
||
if (predictionTensor is not null && protoTensor is not null)
|
||
{
|
||
return DecodeYoloSeg(
|
||
predictionTensor,
|
||
protoTensor,
|
||
inputWidth,
|
||
inputHeight,
|
||
out confidence,
|
||
out failureReason);
|
||
}
|
||
|
||
if (outputs.Count != 1)
|
||
{
|
||
failureReason = "不支持的模型输出组合";
|
||
return null;
|
||
}
|
||
|
||
var only = outputs[0];
|
||
var dims = only.Dimensions;
|
||
|
||
if (dims.Length == 2)
|
||
{
|
||
failureReason = DescribeClassification(only);
|
||
return null;
|
||
}
|
||
|
||
if (dims.Length == 3)
|
||
{
|
||
if (dims[2] == 6 && dims[1] <= 1000)
|
||
{
|
||
return DecodeDetectionBoxes(
|
||
only, inputWidth, inputHeight, out confidence, out failureReason);
|
||
}
|
||
|
||
// [1,H,W] 形式的单通道掩膜;YOLO 预测张量通常第二维远大于第三维
|
||
if (dims[1] > 8 &&
|
||
dims[2] > 8 &&
|
||
dims[2] <= dims[1] * 4)
|
||
{
|
||
return CreateMaskFromSingle(only, out failureReason);
|
||
}
|
||
|
||
failureReason = "检测输出缺少 mask proto,无法生成轮廓";
|
||
return null;
|
||
}
|
||
|
||
if (dims.Length == 4 && dims[1] == 1)
|
||
{
|
||
return CreateMaskFromSingle(only, out failureReason);
|
||
}
|
||
|
||
if (dims.Length == 4 && dims[1] > 1)
|
||
{
|
||
return DecodeSemanticMask(only, out failureReason);
|
||
}
|
||
|
||
failureReason = $"不支持的输出形状:{DescribeDimensions(dims)}";
|
||
return null;
|
||
}
|
||
|
||
/// <summary>判断 [1,N,6] 输出中第 4/5 列哪一列是置信度。</summary>
|
||
private static int ResolveScoreColumn(OutputTensor tensor, int count, int stride)
|
||
{
|
||
var column4IsScore = true;
|
||
var column5IsScore = true;
|
||
|
||
for (var i = 0; i < count; i++)
|
||
{
|
||
var score4 = tensor.Data[i * stride + 4];
|
||
var score5 = tensor.Data[i * stride + 5];
|
||
|
||
if (score4 < 0 || score4 > 1)
|
||
{
|
||
column4IsScore = false;
|
||
}
|
||
|
||
if (score5 < 0 || score5 > 1)
|
||
{
|
||
column5IsScore = false;
|
||
}
|
||
}
|
||
|
||
if (column4IsScore && !column5IsScore)
|
||
{
|
||
return 4;
|
||
}
|
||
|
||
if (column5IsScore && !column4IsScore)
|
||
{
|
||
return 5;
|
||
}
|
||
|
||
return 4;
|
||
}
|
||
|
||
/// <summary>解码 [1,N,6] 检测框输出,使用最优检测框作为轮廓区域。</summary>
|
||
private Mat? DecodeDetectionBoxes(
|
||
OutputTensor tensor,
|
||
int inputWidth,
|
||
int inputHeight,
|
||
out float confidence,
|
||
out string failureReason)
|
||
{
|
||
confidence = 0f;
|
||
failureReason = string.Empty;
|
||
var dims = tensor.Dimensions;
|
||
var count = dims[1];
|
||
var stride = dims[2];
|
||
var data = tensor.Data;
|
||
|
||
var bestScore = -1f;
|
||
var bestIndex = -1;
|
||
var scoreColumn = ResolveScoreColumn(tensor, count, stride);
|
||
|
||
for (var i = 0; i < count; i++)
|
||
{
|
||
var score = data[i * stride + scoreColumn];
|
||
if (score > bestScore)
|
||
{
|
||
bestScore = score;
|
||
bestIndex = i;
|
||
}
|
||
}
|
||
|
||
if (bestIndex < 0 || bestScore < _options.ConfidenceThreshold)
|
||
{
|
||
failureReason = "未检测到目标";
|
||
return null;
|
||
}
|
||
|
||
confidence = ToProbability(bestScore);
|
||
|
||
var best = bestIndex * stride;
|
||
var x1 = data[best];
|
||
var y1 = data[best + 1];
|
||
var x2 = data[best + 2];
|
||
var y2 = data[best + 3];
|
||
|
||
// 兼容 cx,cy,w,h 格式
|
||
if (x2 <= x1 || y2 <= y1)
|
||
{
|
||
var cx = x1;
|
||
var cy = y1;
|
||
var width = x2;
|
||
var height = y2;
|
||
x1 = cx - width / 2;
|
||
y1 = cy - height / 2;
|
||
x2 = cx + width / 2;
|
||
y2 = cy + height / 2;
|
||
}
|
||
|
||
// 兼容 0~1 归一化坐标
|
||
if (Math.Max(Math.Max(x2, y2), Math.Max(x1, y1)) <= 1.5)
|
||
{
|
||
x1 *= inputWidth;
|
||
x2 *= inputWidth;
|
||
y1 *= inputHeight;
|
||
y2 *= inputHeight;
|
||
}
|
||
|
||
x1 = Math.Clamp(x1, 0f, inputWidth - 1f);
|
||
y1 = Math.Clamp(y1, 0f, inputHeight - 1f);
|
||
x2 = Math.Clamp(x2, 0f, inputWidth - 1f);
|
||
y2 = Math.Clamp(y2, 0f, inputHeight - 1f);
|
||
|
||
if (x2 - x1 < 4 || y2 - y1 < 4)
|
||
{
|
||
failureReason = "检测框无效";
|
||
return null;
|
||
}
|
||
|
||
var mask = new Mat(
|
||
inputHeight, inputWidth, MatType.CV_8UC1, Scalar.All(0));
|
||
Cv2.Rectangle(
|
||
mask,
|
||
new Rect(
|
||
(int)Math.Round(x1),
|
||
(int)Math.Round(y1),
|
||
Math.Max(1, (int)Math.Round(x2 - x1)),
|
||
Math.Max(1, (int)Math.Round(y2 - y1))),
|
||
Scalar.All(255),
|
||
-1);
|
||
|
||
return mask;
|
||
}
|
||
|
||
/// <summary>解码 dets / labels / masks 形式的实例分割输出。</summary>
|
||
private Mat? DecodeDetectionMasks(
|
||
OutputTensor maskTensor,
|
||
OutputTensor labelTensor,
|
||
out float confidence,
|
||
out string failureReason)
|
||
{
|
||
confidence = 0f;
|
||
failureReason = string.Empty;
|
||
|
||
var dims = maskTensor.Dimensions;
|
||
if (dims.Length != 4)
|
||
{
|
||
failureReason = "掩膜输出维度不正确";
|
||
return null;
|
||
}
|
||
|
||
var count = labelTensor.Dimensions[1];
|
||
var classCount = labelTensor.Dimensions[2];
|
||
var maskHeight = dims[2];
|
||
var maskWidth = dims[3];
|
||
|
||
if (labelTensor.Data.Length < count * classCount ||
|
||
maskTensor.Data.Length < count * maskHeight * maskWidth)
|
||
{
|
||
failureReason = "掩膜输出尺寸不一致";
|
||
return null;
|
||
}
|
||
|
||
var bestScore = float.MinValue;
|
||
var bestIndex = -1;
|
||
|
||
for (var i = 0; i < count; i++)
|
||
{
|
||
var offset = i * classCount;
|
||
for (var c = 0; c < classCount; c++)
|
||
{
|
||
var score = labelTensor.Data[offset + c];
|
||
if (score > bestScore)
|
||
{
|
||
bestScore = score;
|
||
bestIndex = i;
|
||
}
|
||
}
|
||
}
|
||
|
||
if (bestIndex < 0)
|
||
{
|
||
failureReason = "未检测到目标";
|
||
return null;
|
||
}
|
||
|
||
var isLogits = bestScore < -0.01 || bestScore > 1.01;
|
||
var threshold = isLogits ? 0.0 : _options.ConfidenceThreshold;
|
||
if (bestScore < threshold)
|
||
{
|
||
failureReason = "目标置信度不足";
|
||
return null;
|
||
}
|
||
|
||
confidence = ToProbability(bestScore);
|
||
|
||
var plane = maskHeight * maskWidth;
|
||
var start = bestIndex * plane;
|
||
var maskData = new float[plane];
|
||
Array.Copy(maskTensor.Data, start, maskData, 0, plane);
|
||
|
||
var mask = new Mat(maskHeight, maskWidth, MatType.CV_32FC1);
|
||
Marshal.Copy(maskData, 0, mask.Data, plane);
|
||
|
||
using (mask)
|
||
{
|
||
Cv2.MinMaxLoc(mask, out double min, out double max);
|
||
var maskThreshold = min < -0.01 || max > 1.01
|
||
? 0.0
|
||
: _options.MaskThreshold;
|
||
return ThresholdToBinaryMask(mask, maskThreshold);
|
||
}
|
||
}
|
||
|
||
/// <summary>解码 YOLO-seg 预测张量与 mask proto。</summary>
|
||
private Mat? DecodeYoloSeg(
|
||
OutputTensor predictionTensor,
|
||
OutputTensor protoTensor,
|
||
int inputWidth,
|
||
int inputHeight,
|
||
out float confidence,
|
||
out string failureReason)
|
||
{
|
||
confidence = 0f;
|
||
failureReason = string.Empty;
|
||
|
||
var predictionDims = predictionTensor.Dimensions;
|
||
var protoDims = protoTensor.Dimensions;
|
||
|
||
var dim1 = predictionDims[1];
|
||
var dim2 = predictionDims[2];
|
||
var attributeFirst = dim1 < dim2;
|
||
var attributes = attributeFirst ? dim1 : dim2;
|
||
var detections = attributeFirst ? dim2 : dim1;
|
||
|
||
var protoChannels = protoDims[1];
|
||
var protoHeight = protoDims[2];
|
||
var protoWidth = protoDims[3];
|
||
var classCount = attributes - 4 - protoChannels;
|
||
|
||
if (classCount < 1)
|
||
{
|
||
failureReason = $"预测张量属性数无效:{attributes}";
|
||
return null;
|
||
}
|
||
|
||
var prediction = predictionTensor.Data;
|
||
var bestConfidence = 0f;
|
||
var bestIndex = -1;
|
||
|
||
for (var i = 0; i < detections; i++)
|
||
{
|
||
var detectionConfidence = 0f;
|
||
for (var c = 0; c < classCount; c++)
|
||
{
|
||
var index = attributeFirst
|
||
? (4 + c) * detections + i
|
||
: i * attributes + 4 + c;
|
||
detectionConfidence = Math.Max(
|
||
detectionConfidence, prediction[index]);
|
||
}
|
||
|
||
if (detectionConfidence > bestConfidence)
|
||
{
|
||
bestConfidence = detectionConfidence;
|
||
bestIndex = i;
|
||
}
|
||
}
|
||
|
||
if (bestIndex < 0 || bestConfidence < _options.ConfidenceThreshold)
|
||
{
|
||
failureReason = "未检测到目标";
|
||
return null;
|
||
}
|
||
|
||
confidence = bestConfidence;
|
||
|
||
float GetAttribute(int attribute) => attributeFirst
|
||
? prediction[attribute * detections + bestIndex]
|
||
: prediction[bestIndex * attributes + attribute];
|
||
|
||
var centerX = GetAttribute(0);
|
||
var centerY = GetAttribute(1);
|
||
var boxWidth = GetAttribute(2);
|
||
var boxHeight = GetAttribute(3);
|
||
|
||
var coefficients = new float[protoChannels];
|
||
for (var k = 0; k < protoChannels; k++)
|
||
{
|
||
coefficients[k] = GetAttribute(4 + classCount + k);
|
||
}
|
||
|
||
var protoData = protoTensor.Data;
|
||
var protoArea = protoHeight * protoWidth;
|
||
|
||
var left = 0;
|
||
var top = 0;
|
||
var right = protoWidth;
|
||
var bottom = protoHeight;
|
||
|
||
if (boxWidth > 0 && boxHeight > 0)
|
||
{
|
||
left = Math.Clamp(
|
||
(int)Math.Floor((centerX - boxWidth / 2) * protoWidth / inputWidth),
|
||
0,
|
||
protoWidth - 1);
|
||
top = Math.Clamp(
|
||
(int)Math.Floor((centerY - boxHeight / 2) * protoHeight / inputHeight),
|
||
0,
|
||
protoHeight - 1);
|
||
right = Math.Clamp(
|
||
(int)Math.Ceiling((centerX + boxWidth / 2) * protoWidth / inputWidth),
|
||
left + 1,
|
||
protoWidth);
|
||
bottom = Math.Clamp(
|
||
(int)Math.Ceiling((centerY + boxHeight / 2) * protoHeight / inputHeight),
|
||
top + 1,
|
||
protoHeight);
|
||
}
|
||
|
||
var logits = new float[protoArea];
|
||
for (var y = top; y < bottom; y++)
|
||
{
|
||
for (var x = left; x < right; x++)
|
||
{
|
||
var pixel = y * protoWidth + x;
|
||
var sum = 0f;
|
||
for (var k = 0; k < protoChannels; k++)
|
||
{
|
||
sum += coefficients[k] * protoData[k * protoArea + pixel];
|
||
}
|
||
|
||
logits[pixel] = sum;
|
||
}
|
||
}
|
||
|
||
var logitMat = new Mat(protoHeight, protoWidth, MatType.CV_32FC1);
|
||
Marshal.Copy(logits, 0, logitMat.Data, logits.Length);
|
||
|
||
using (logitMat)
|
||
{
|
||
Cv2.MinMaxLoc(logitMat, out double min, out double max);
|
||
var threshold = min < -0.01 || max > 1.01
|
||
? 0.0
|
||
: _options.MaskThreshold;
|
||
return ThresholdToBinaryMask(logitMat, threshold);
|
||
}
|
||
}
|
||
|
||
/// <summary>解码单通道掩膜输出。</summary>
|
||
private Mat? CreateMaskFromSingle(
|
||
OutputTensor output, out string failureReason)
|
||
{
|
||
failureReason = string.Empty;
|
||
var dims = output.Dimensions;
|
||
int height;
|
||
int width;
|
||
|
||
if (dims.Length == 3)
|
||
{
|
||
height = dims[1];
|
||
width = dims[2];
|
||
}
|
||
else if (dims.Length == 4 && dims[1] == 1)
|
||
{
|
||
height = dims[2];
|
||
width = dims[3];
|
||
}
|
||
else
|
||
{
|
||
failureReason = $"不支持的掩膜形状:{DescribeDimensions(dims)}";
|
||
return null;
|
||
}
|
||
|
||
var plane = height * width;
|
||
var data = output.Data;
|
||
if (data.Length < plane)
|
||
{
|
||
failureReason = "掩膜数据长度不正确";
|
||
return null;
|
||
}
|
||
|
||
var mask = new Mat(height, width, MatType.CV_32FC1);
|
||
Marshal.Copy(data, 0, mask.Data, plane);
|
||
|
||
using (mask)
|
||
{
|
||
Cv2.MinMaxLoc(mask, out double min, out double max);
|
||
var threshold = min < -0.01 || max > 1.01
|
||
? 0.0
|
||
: _options.MaskThreshold;
|
||
return ThresholdToBinaryMask(mask, threshold);
|
||
}
|
||
}
|
||
|
||
/// <summary>多通道语义分割:类别 0 视为背景,其余视为靶样。</summary>
|
||
private Mat? DecodeSemanticMask(
|
||
OutputTensor output, out string failureReason)
|
||
{
|
||
failureReason = string.Empty;
|
||
var dims = output.Dimensions;
|
||
var channels = dims[1];
|
||
var height = dims[2];
|
||
var width = dims[3];
|
||
var plane = height * width;
|
||
|
||
if (output.Data.Length < channels * plane)
|
||
{
|
||
failureReason = "语义分割输出尺寸不正确";
|
||
return null;
|
||
}
|
||
|
||
var channelMats = new Mat[channels];
|
||
try
|
||
{
|
||
for (var i = 0; i < channels; i++)
|
||
{
|
||
var slice = new float[plane];
|
||
Array.Copy(output.Data, i * plane, slice, 0, plane);
|
||
channelMats[i] = new Mat(height, width, MatType.CV_32FC1);
|
||
Marshal.Copy(slice, 0, channelMats[i].Data, plane);
|
||
}
|
||
|
||
using var best = channelMats[0].Clone();
|
||
using var bestIndex = new Mat(
|
||
height, width, MatType.CV_8UC1, Scalar.All(0));
|
||
|
||
for (var i = 1; i < channels; i++)
|
||
{
|
||
using var better = new Mat();
|
||
Cv2.Compare(channelMats[i], best, better, CmpType.GT);
|
||
channelMats[i].CopyTo(best, better);
|
||
bestIndex.SetTo(new Scalar(Math.Min(i, 255)), better);
|
||
}
|
||
|
||
var result = new Mat();
|
||
Cv2.Threshold(bestIndex, result, 0, 255, ThresholdTypes.Binary);
|
||
return result;
|
||
}
|
||
finally
|
||
{
|
||
foreach (var channel in channelMats)
|
||
{
|
||
channel?.Dispose();
|
||
}
|
||
}
|
||
}
|
||
|
||
private string DescribeClassification(OutputTensor output)
|
||
{
|
||
var data = output.Data;
|
||
if (data.Length == 0)
|
||
{
|
||
return "分类模型输出为空";
|
||
}
|
||
|
||
var max = data.Max();
|
||
return $"分类模型无空间输出,top1={max:F3}";
|
||
}
|
||
|
||
private static string DescribeDimensions(int[] dimensions) =>
|
||
string.Join("x", dimensions);
|
||
|
||
private static float ToProbability(float value) =>
|
||
value is >= 0f and <= 1f
|
||
? value
|
||
: (float)(1.0 / (1.0 + Math.Exp(-value)));
|
||
|
||
private static Mat ThresholdToBinaryMask(Mat source, double threshold)
|
||
{
|
||
using var mask = new Mat();
|
||
Cv2.Threshold(source, mask, threshold, 255, ThresholdTypes.Binary);
|
||
|
||
var result = new Mat();
|
||
mask.ConvertTo(result, MatType.CV_8UC1);
|
||
return result;
|
||
}
|
||
|
||
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>
|
||
/// 按面积、凸性、填充率和圆度综合评分,选择最可能的靶样轮廓。
|
||
/// </summary>
|
||
private Point[] SelectContour(Point[][] contours, int width, int height)
|
||
{
|
||
var imageArea = width * (double)height;
|
||
var minArea = imageArea * _options.MinAreaRatio;
|
||
var maxArea = imageArea * _options.MaxAreaRatio;
|
||
|
||
Point[]? best = null;
|
||
var bestScore = double.MinValue;
|
||
|
||
foreach (var contour in contours)
|
||
{
|
||
if (contour.Length < 3)
|
||
{
|
||
continue;
|
||
}
|
||
|
||
var area = Cv2.ContourArea(contour);
|
||
if (area < minArea || area > maxArea)
|
||
{
|
||
continue;
|
||
}
|
||
|
||
var rect = Cv2.BoundingRect(contour);
|
||
if (rect.Width < 8 || rect.Height < 8)
|
||
{
|
||
continue;
|
||
}
|
||
|
||
var aspect = rect.Width / (double)rect.Height;
|
||
if (aspect < 0.05 || aspect > 20)
|
||
{
|
||
continue;
|
||
}
|
||
|
||
var hull = Cv2.ConvexHull(contour);
|
||
var hullArea = Cv2.ContourArea(hull);
|
||
var solidity = hullArea > 0 ? area / hullArea : 0;
|
||
|
||
var perimeter = Cv2.ArcLength(contour, true);
|
||
var circularity = perimeter > 0
|
||
? 4 * Math.PI * area / (perimeter * perimeter)
|
||
: 0;
|
||
|
||
var extent = area / (rect.Width * (double)rect.Height);
|
||
var sizeScore = Math.Min(1.0, area / (imageArea * 0.2));
|
||
|
||
var score =
|
||
sizeScore * 0.4 +
|
||
solidity * 0.3 +
|
||
extent * 0.2 +
|
||
circularity * 0.1;
|
||
|
||
var borderTouch =
|
||
rect.X <= 1 ||
|
||
rect.Y <= 1 ||
|
||
rect.Right >= width - 1 ||
|
||
rect.Bottom >= height - 1;
|
||
|
||
if (borderTouch)
|
||
{
|
||
score -= 0.1;
|
||
}
|
||
|
||
if (score > bestScore)
|
||
{
|
||
bestScore = score;
|
||
best = contour;
|
||
}
|
||
}
|
||
|
||
return best ?? throw new HardwareException(
|
||
HardwareErrorKind.InvalidState,
|
||
"未生成有效的靶样轮廓");
|
||
}
|
||
|
||
/// <summary>
|
||
/// 计算采样点距轮廓边缘的安全边距:
|
||
/// 至少留出绘制标记半径 + 4 像素,同时按轮廓短边比例留边。
|
||
/// </summary>
|
||
private double CalculateSamplingMargin(
|
||
Point[] contour, int imageWidth, int imageHeight)
|
||
{
|
||
var rect = Cv2.BoundingRect(contour);
|
||
var markerRadius = Math.Max(4, Math.Min(imageWidth, imageHeight) / 150.0);
|
||
var ratio = Math.Clamp(_options.SamplingMarginRatio, 0, 0.3);
|
||
var ratioMargin = Math.Min(rect.Width, rect.Height) * ratio;
|
||
return Math.Max(markerRadius + 4, ratioMargin);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 在轮廓内部按网格生成候选点,要求候选点到轮廓的距离不小于安全边距;
|
||
/// 点数不足时逐步缩小间距,再均匀抽取指定数量的采样点。
|
||
/// </summary>
|
||
private static List<Point> BuildSamplingPoints(
|
||
Point[] contour, int count, double margin)
|
||
{
|
||
var area = Cv2.ContourArea(contour);
|
||
if (area <= 0 || count <= 0)
|
||
{
|
||
return new List<Point>();
|
||
}
|
||
|
||
var rect = Cv2.BoundingRect(contour);
|
||
var spacing = Math.Sqrt(area / count);
|
||
var candidates = new List<Point>();
|
||
|
||
for (var attempt = 0; attempt < 40; attempt++)
|
||
{
|
||
if (spacing < 2)
|
||
{
|
||
break;
|
||
}
|
||
|
||
candidates.Clear();
|
||
|
||
for (var y = rect.Top + spacing / 2; y <= rect.Bottom; y += spacing)
|
||
{
|
||
for (var x = rect.Left + spacing / 2; x <= rect.Right; x += spacing)
|
||
{
|
||
var point = new Point((int)Math.Round(x), (int)Math.Round(y));
|
||
var distance = Cv2.PointPolygonTest(
|
||
contour, new Point2f(point.X, point.Y), true);
|
||
if (distance >= margin)
|
||
{
|
||
candidates.Add(point);
|
||
}
|
||
}
|
||
}
|
||
|
||
if (candidates.Count >= count)
|
||
{
|
||
break;
|
||
}
|
||
|
||
spacing *= 0.85;
|
||
}
|
||
|
||
if (candidates.Count == 0)
|
||
{
|
||
// 极窄轮廓可能无法满足安全边距,退回到离边缘最远的内部点
|
||
var fallback = FindBestInteriorPoint(contour);
|
||
return fallback.HasValue
|
||
? new List<Point> { fallback.Value }
|
||
: new List<Point>();
|
||
}
|
||
|
||
if (candidates.Count <= count)
|
||
{
|
||
return candidates;
|
||
}
|
||
|
||
if (count == 1)
|
||
{
|
||
return new List<Point> { candidates[candidates.Count / 2] };
|
||
}
|
||
|
||
var selected = new List<Point>(count);
|
||
for (var i = 0; i < count; i++)
|
||
{
|
||
var index = (int)Math.Round(
|
||
i * (candidates.Count - 1) / (double)(count - 1));
|
||
selected.Add(candidates[index]);
|
||
}
|
||
|
||
return selected.Distinct().ToList();
|
||
}
|
||
|
||
/// <summary>找到轮廓内部距边缘最远的点,作为极端情况下的兜底。</summary>
|
||
private static Point? FindBestInteriorPoint(Point[] contour)
|
||
{
|
||
var rect = Cv2.BoundingRect(contour);
|
||
var step = Math.Max(2, Math.Min(rect.Width, rect.Height) / 50);
|
||
|
||
var bestPoint = default(Point);
|
||
var bestDistance = double.MinValue;
|
||
|
||
for (var y = rect.Top; y <= rect.Bottom; y += step)
|
||
{
|
||
for (var x = rect.Left; x <= rect.Right; x += step)
|
||
{
|
||
var distance = Cv2.PointPolygonTest(
|
||
contour, new Point2f(x, y), true);
|
||
|
||
if (distance > bestDistance)
|
||
{
|
||
bestDistance = distance;
|
||
bestPoint = new Point(x, y);
|
||
}
|
||
}
|
||
}
|
||
|
||
return bestDistance > 0 ? bestPoint : null;
|
||
}
|
||
|
||
private static void DrawSamplingPoints(
|
||
Mat image, IReadOnlyList<Point> points, int lineThickness)
|
||
{
|
||
var radius = Math.Max(4, Math.Min(image.Width, image.Height) / 150);
|
||
var borderThickness = Math.Max(1, radius / 4);
|
||
|
||
for (var i = 0; i < points.Count; i++)
|
||
{
|
||
var point = points[i];
|
||
Cv2.Circle(image, point, radius, new Scalar(0, 0, 255), -1, LineTypes.AntiAlias);
|
||
Cv2.Circle(
|
||
image, point, radius, new Scalar(255, 255, 255),
|
||
borderThickness, LineTypes.AntiAlias);
|
||
|
||
var fontScale = Math.Max(0.4, Math.Min(image.Width, image.Height) / 2500.0);
|
||
Cv2.PutText(
|
||
image,
|
||
(i + 1).ToString(),
|
||
new Point(point.X + radius + 2, point.Y - radius),
|
||
HersheyFonts.HersheySimplex,
|
||
fontScale,
|
||
new Scalar(0, 255, 255),
|
||
Math.Max(1, lineThickness / 2),
|
||
LineTypes.AntiAlias);
|
||
}
|
||
}
|
||
|
||
private sealed record OutputTensor(
|
||
string Name,
|
||
int[] Dimensions,
|
||
float[] Data);
|
||
}
|
||
}
|