From 7f8cc4ecd23282042641dc3d6046c44c26f5920d Mon Sep 17 00:00:00 2001 From: tfarcraw <123211521@163.com> Date: Sun, 26 Jul 2026 10:15:22 +0800 Subject: [PATCH] =?UTF-8?q?=E6=94=B9=E8=BF=9B=E4=B8=80=E4=BA=9B=E6=98=BE?= =?UTF-8?q?=E7=A4=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../GalleryClassifier/FeatureExtractor.cs | 104 ++++++++++++++ .../Vision/GalleryClassifier/OnnxEmbedding.cs | 129 ------------------ .../Vision/VisionConfigViewModel.Gallery.cs | 57 ++------ .../Algorithm/ColorAreaHandler.cs | 6 +- .../Algorithm/GalleryClassifier.xaml | 40 +----- .../Algorithm/GalleryClassifierHandler.cs | 59 ++++---- .../Algorithm/GrayAreaHandler.cs | 6 +- .../Algorithm/GrayTemplateMatchHandler.cs | 6 +- .../Algorithm/PointToLineDistanceHandler.cs | 2 +- .../Algorithm/PointToPointDistanceHandler.cs | 2 +- .../Vision/VisionFlowHandler/DrawCommand.cs | 4 + PLCSharpWpf/VVMs/Vision/VisionFunction.cs | 8 +- 12 files changed, 163 insertions(+), 260 deletions(-) create mode 100644 PLCSharpWpf/VVMs/Vision/GalleryClassifier/FeatureExtractor.cs delete mode 100644 PLCSharpWpf/VVMs/Vision/GalleryClassifier/OnnxEmbedding.cs diff --git a/PLCSharpWpf/VVMs/Vision/GalleryClassifier/FeatureExtractor.cs b/PLCSharpWpf/VVMs/Vision/GalleryClassifier/FeatureExtractor.cs new file mode 100644 index 0000000..8a4c458 --- /dev/null +++ b/PLCSharpWpf/VVMs/Vision/GalleryClassifier/FeatureExtractor.cs @@ -0,0 +1,104 @@ +#nullable enable +using OpenCvSharp; +using System; + +namespace PLCSharp.VVMs.Vision.GalleryClassifier +{ + /// + /// 特征提取器 —— 在原始分辨率下将 ROI 区域分成格子,提取统计特征。 + /// 不缩放、不依赖 ONNX 模型,细节不丢失。 + /// + /// 每个格子提取 2 个特征:灰度均值 + 灰度标准差 + /// 默认 8x8 格子 → 128 维特征向量 + /// + public class FeatureExtractor : IDisposable + { + private readonly int _gridX; + private readonly int _gridY; + private bool _disposed; + + /// 特征向量维度 = gridX × gridY × 2 + public int FeatureDimension => _gridX * _gridY * 2; + + public FeatureExtractor(int gridX = 8, int gridY = 8) + { + _gridX = gridX > 0 ? gridX : throw new ArgumentException("gridX > 0"); + _gridY = gridY > 0 ? gridY : throw new ArgumentException("gridY > 0"); + } + + public unsafe float[] Extract(Mat image) + { + ThrowIfDisposed(); + if (image == null || image.Empty()) + throw new ArgumentException("图像为空"); + + Mat gray; + if (image.Channels() == 1) + gray = image.Clone(); + else + { + gray = new Mat(); + Cv2.CvtColor(image, gray, ColorConversionCodes.BGR2GRAY); + } + + try + { + int cellW = Math.Max(gray.Width / _gridX, 1); + int cellH = Math.Max(gray.Height / _gridY, 1); + + float[] features = new float[_gridX * _gridY * 2]; + int idx = 0; + + for (int gy = 0; gy < _gridY; gy++) + { + for (int gx = 0; gx < _gridX; gx++) + { + int x = gx * cellW; + int y = gy * cellH; + int w = (gx == _gridX - 1) ? gray.Width - x : cellW; + int h = (gy == _gridY - 1) ? gray.Height - y : cellH; + int pixelCount = w * h; + if (pixelCount <= 0) { idx += 2; continue; } + + float sum = 0f; + float sumSq = 0f; + + for (int row = y; row < y + h; row++) + { + byte* rowPtr = (byte*)gray.DataPointer + row * gray.Step(); + for (int col = x; col < x + w; col++) + { + byte v = rowPtr[col]; + sum += v; + sumSq += v * v; + } + } + + float mean = sum / pixelCount; + float variance = (sumSq / pixelCount) - (mean * mean); + + features[idx++] = mean / 255f; + features[idx++] = MathF.Sqrt(MathF.Max(variance, 0f)) / 255f; + } + } + + return features; + } + finally + { + gray?.Dispose(); + } + } + + public void Dispose() + { + _disposed = true; + } + + private void ThrowIfDisposed() + { + if (_disposed) + throw new ObjectDisposedException(nameof(FeatureExtractor)); + } + } +} diff --git a/PLCSharpWpf/VVMs/Vision/GalleryClassifier/OnnxEmbedding.cs b/PLCSharpWpf/VVMs/Vision/GalleryClassifier/OnnxEmbedding.cs deleted file mode 100644 index 2699603..0000000 --- a/PLCSharpWpf/VVMs/Vision/GalleryClassifier/OnnxEmbedding.cs +++ /dev/null @@ -1,129 +0,0 @@ -#nullable enable -using OpenCvSharp; -using OpenCvSharp.Dnn; -using System; -using System.Runtime.InteropServices; - -namespace PLCSharp.VVMs.Vision.GalleryClassifier -{ - /// - /// ONNX 特征提取器 —— 使用 OpenCvSharp DNN 模块,不依赖额外 NuGet 包。 - /// - /// 需要:一个输出 embedding 的 .onnx 模型文件 - /// 推荐:MobileNetV3-Large 去掉分类头后导出 - /// - public class OnnxEmbedding : IDisposable - { - private readonly Net _net; - private readonly int _inputWidth; - private readonly int _inputHeight; - private readonly int _featureDimension; - private bool _disposed; - - private static readonly float[] Mean = [0.485f, 0.456f, 0.406f]; - private static readonly float[] Std = [0.229f, 0.224f, 0.225f]; - - /// 输出特征向量维度 - public int FeatureDimension => _featureDimension; - - public OnnxEmbedding(string modelPath, int inputWidth = 224, int inputHeight = 224, - int featureDimension = -1) - { - _net = Cv2.Dnn.ReadNetFromONNX(modelPath); - _inputWidth = inputWidth; - _inputHeight = inputHeight; - - // 默认 CPU 推理 - - if (featureDimension > 0) - { - _featureDimension = featureDimension; - } - else - { - using var dummy = new Mat(_inputHeight, _inputWidth, MatType.CV_8UC3, Scalar.All(0)); - using var blob = BlobFromImage(dummy); - _net.SetInput(blob); - using var output = _net.Forward(); - _featureDimension = (int)output.Total(); - } - } - - /// - /// 从 BGR 图像提取 L2 归一化的特征向量 - /// - public float[] Extract(Mat image) - { - ThrowIfDisposed(); - if (image == null || image.Empty()) - throw new ArgumentException("图像为空"); - - using var blob = BlobFromImage(image); - _net.SetInput(blob); - using var output = _net.Forward(); - - int total = (int)output.Total(); - float[] feature = new float[total]; - Marshal.Copy(output.DataStart, feature, 0, total); - - return L2Normalize(feature); - } - - /// - /// 图像预处理:resize → BGR→RGB → [0,1] → (x - mean) / std - /// OpenCV blobFromImage 不支持除 std,所以先做 resize+swapRB,再手动归一化 - /// - private Mat BlobFromImage(Mat image) - { - int w = _inputWidth, h = _inputHeight; - - // resize + BGR→RGB,不做归一化 - var blob = Cv2.Dnn.BlobFromImage(image, 1.0, new Size(w, h), - new Scalar(0, 0, 0), swapRB: true, crop: false); - - int total = (int)blob.Total(); // 3 * H * W - float[] data = new float[total]; - Marshal.Copy(blob.DataStart, data, 0, total); - - // NCHW: data[c, h, w] = (pixel - mean[c] * 255) / (std[c] * 255) - // 由于 blobFromImage(scale=1.0) 时 pixel 还是 [0,255] 原始值 - int hw = h * w; - for (int i = 0; i < total; i++) - { - int c = i / hw; - data[i] = (data[i] / 255f - Mean[c]) / Std[c]; - } - - Marshal.Copy(data, 0, blob.DataStart, total); - return blob; - } - - private static float[] L2Normalize(float[] vector) - { - float sumSq = 0f; - foreach (var v in vector) sumSq += v * v; - float norm = MathF.Sqrt(sumSq); - if (norm < 1e-10f) return vector; - - var result = new float[vector.Length]; - for (int i = 0; i < vector.Length; i++) - result[i] = vector[i] / norm; - return result; - } - - public void Dispose() - { - if (!_disposed) - { - _net?.Dispose(); - _disposed = true; - } - } - - private void ThrowIfDisposed() - { - if (_disposed) - throw new ObjectDisposedException(nameof(OnnxEmbedding)); - } - } -} diff --git a/PLCSharpWpf/VVMs/Vision/VisionConfigViewModel.Gallery.cs b/PLCSharpWpf/VVMs/Vision/VisionConfigViewModel.Gallery.cs index 9051285..8b30849 100644 --- a/PLCSharpWpf/VVMs/Vision/VisionConfigViewModel.Gallery.cs +++ b/PLCSharpWpf/VVMs/Vision/VisionConfigViewModel.Gallery.cs @@ -22,36 +22,6 @@ namespace PLCSharp.VVMs.Vision private float[]? _lastGalleryFeature; private bool _lastGalleryWasOk; - #region 模型路径 - - private DelegateCommand _BrowseGalleryModelCommand; - public DelegateCommand BrowseGalleryModelCommand => - _BrowseGalleryModelCommand ??= new DelegateCommand(ExecuteBrowseGalleryModel); - private void ExecuteBrowseGalleryModel() - { - var dialog = new Microsoft.Win32.OpenFileDialog - { - Filter = "ONNX 模型|*.onnx", - Title = "选择特征提取模型" - }; - if (dialog.ShowDialog() != true) return; - if (SelectVisionFlow == null) return; - - SelectVisionFlow.StringParams["GalleryModelPath"] = dialog.FileName; - - var embedding = GalleryClassifierHandler.GetOrCreateEmbedding(dialog.FileName); - GalleryModelStatus = embedding != null ? "模型已加载" : "模型加载失败"; - } - - private string _GalleryModelStatus = "请选择 ONNX 模型文件"; - public string GalleryModelStatus - { - get => _GalleryModelStatus; - set => SetProperty(ref _GalleryModelStatus, value); - } - - #endregion - #region ROI 选区 private AsyncDelegateCommand _DrawGalleryRoiCommand; @@ -152,16 +122,13 @@ namespace PLCSharp.VVMs.Vision private bool CanTrainGallery() { return SelectedVisionFunction?.Src != null && !SelectedVisionFunction.Src.Empty() - && SelectVisionFlow != null - && GalleryClassifierHandler.SharedEmbedding != null; + && SelectVisionFlow != null; } private FeatureGallery GetGallery() { var flow = SelectVisionFlow ?? throw new InvalidOperationException("未选择步骤"); - var dim = GalleryClassifierHandler.SharedEmbedding?.FeatureDimension - ?? throw new InvalidOperationException("模型未加载"); - return GalleryClassifierHandler.LoadFromData(flow, dim); + return GalleryClassifierHandler.LoadFromData(flow, GalleryClassifierHandler.FeatureDimension); } private void SaveGallery(FeatureGallery gallery) @@ -255,13 +222,18 @@ namespace PLCSharp.VVMs.Vision }; if (dialog.ShowDialog() != true) return; if (SelectVisionFlow == null) return; - if (GalleryClassifierHandler.SharedEmbedding == null) return; var json = File.ReadAllText(dialog.FileName); var data = System.Text.Json.JsonSerializer.Deserialize(json); if (data == null) return; - var gallery = new FeatureGallery(GalleryClassifierHandler.SharedEmbedding.FeatureDimension); + if (data.Dimension != GalleryClassifierHandler.FeatureDimension) + { + GalleryFileStatus = $"导入失败:特征维度不匹配(文件 {data.Dimension},当前 {GalleryClassifierHandler.FeatureDimension})"; + return; + } + + var gallery = new FeatureGallery(GalleryClassifierHandler.FeatureDimension); gallery.Import(data); GalleryClassifierHandler.SaveToData(SelectVisionFlow, gallery); @@ -278,10 +250,8 @@ namespace PLCSharp.VVMs.Vision GalleryStatus = "没有图像"; return null; } - var embedding = GalleryClassifierHandler.SharedEmbedding; - if (embedding == null) return null; - // ROI 裁剪(与 Handler 中一致):裁剪后提取特征,不影响原图 + // ROI 裁剪(与 Handler 中一致) var flow = SelectVisionFlow; Mat? roiCloned = null; try @@ -300,7 +270,7 @@ namespace PLCSharp.VVMs.Vision if (w > 0 && h > 0) roiCloned = src[new OpenCvSharp.Rect(x, y, w, h)].Clone(); } - return embedding.Extract(roiCloned ?? func.Src); + return GalleryClassifierHandler.Extractor.Extract(roiCloned ?? func.Src); } finally { @@ -318,11 +288,10 @@ namespace PLCSharp.VVMs.Vision private void RefreshGalleryResult(FeatureGallery gallery) { var func = SelectedVisionFunction; - if (func?.Src == null || func.Src.Empty() - || GalleryClassifierHandler.SharedEmbedding == null) + if (func?.Src == null || func.Src.Empty()) return; - var feature = GalleryClassifierHandler.SharedEmbedding.Extract(func.Src); + var feature = GalleryClassifierHandler.Extractor.Extract(func.Src); var result = gallery.Classify(feature); func.ResultString = result.IsOk ? "OK" : "NG"; diff --git a/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/ColorAreaHandler.cs b/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/ColorAreaHandler.cs index a4f2bbb..c6926f2 100644 --- a/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/ColorAreaHandler.cs +++ b/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/ColorAreaHandler.cs @@ -88,7 +88,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm // 将轮廓点偏移回原图坐标系 var offsetPts = largest.Select(p => new System.Windows.Point(p.X + x, p.Y + y)).ToArray(); - func.DrawCommands.Add(DrawCommand.Polygon(offsetPts, Colors.Yellow, 2)); + func.DrawCommands.Add(DrawCommand.FilledPolygon(offsetPts, Colors.Yellow, Colors.Yellow, 2)); // 如果有多个较大轮廓,也画出来(面积大于最大轮廓20%的) double maxArea = Cv2.ContourArea(largest); @@ -97,14 +97,14 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm if (Cv2.ContourArea(contour) >= maxArea * 0.2) { var pts = contour.Select(p => new System.Windows.Point(p.X + x, p.Y + y)).ToArray(); - func.DrawCommands.Add(DrawCommand.Polygon(pts, Colors.Yellow, 1)); + func.DrawCommands.Add(DrawCommand.FilledPolygon(pts, Colors.Yellow, Colors.Yellow, 1)); } } } // 在图像上显示结果文本 string text = $"颜色面积: {areaPercent:F1}% [{result}]"; - func.DrawCommands.Add(DrawCommand.TextBlock(x, y - 20 < 0 ? y + h + 5 : y - 20, text, Colors.Cyan, 14)); + func.DrawCommands.Add(DrawCommand.TextBlock(x, y - 20 < 0 ? y + h + 5 : y - 20, text, Colors.Cyan, 48)); // 写入结果到ResultDoubles func.Params.ResultDoubles["ColorAreaPercent"] = Math.Round(areaPercent, 2); diff --git a/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/GalleryClassifier.xaml b/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/GalleryClassifier.xaml index bb9234f..c9d8c1a 100644 --- a/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/GalleryClassifier.xaml +++ b/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/GalleryClassifier.xaml @@ -9,31 +9,7 @@ d:DesignHeight="500" d:DesignWidth="300"> - - - - - - - - - - - - - -