diff --git a/PLCSharpWpf/ONNXs/mobilenetv3_large_embedding.onnx b/PLCSharpWpf/ONNXs/mobilenetv3_large_embedding.onnx new file mode 100644 index 0000000..77f0c4e Binary files /dev/null and b/PLCSharpWpf/ONNXs/mobilenetv3_large_embedding.onnx differ diff --git a/PLCSharpWpf/ONNXs/mobilenetv3_large_embedding.onnx.data b/PLCSharpWpf/ONNXs/mobilenetv3_large_embedding.onnx.data new file mode 100644 index 0000000..503191a Binary files /dev/null and b/PLCSharpWpf/ONNXs/mobilenetv3_large_embedding.onnx.data differ diff --git a/PLCSharpWpf/VVMs/Vision/GalleryClassifier/FeatureGallery.cs b/PLCSharpWpf/VVMs/Vision/GalleryClassifier/FeatureGallery.cs new file mode 100644 index 0000000..f652ad9 --- /dev/null +++ b/PLCSharpWpf/VVMs/Vision/GalleryClassifier/FeatureGallery.cs @@ -0,0 +1,278 @@ +#nullable enable +using System; +using System.Collections.Generic; +using System.Linq; + +namespace PLCSharp.VVMs.Vision.GalleryClassifier +{ + /// + /// 特征向量画廊 —— 管理 OK/NG 特征向量库,支持即时追加/删除,零重训。 + /// + /// 用法: + /// var gallery = new FeatureGallery(512); // 特征维度 + /// gallery.AddOk(feature); // 点击"训练OK" + /// gallery.AddNg(feature); // 点击"训练NG" + /// var result = gallery.Classify(feature); // 推理 + /// + public class FeatureGallery + { + private readonly int _dimension; + private readonly List _okVectors = []; + private readonly List _ngVectors = []; + private readonly object _lock = new(); + + /// OK 库样本数 + public int OkCount { get { lock (_lock) return _okVectors.Count; } } + /// NG 库样本数 + public int NgCount { get { lock (_lock) return _ngVectors.Count; } } + + /// 特征向量维度(必须与 ONNX 模型输出一致) + public FeatureGallery(int dimension) + { + _dimension = dimension > 0 ? dimension : throw new ArgumentException("维度必须大于 0"); + } + + #region 增删 + + public void AddOk(float[] feature) + { + ValidateFeature(feature); + lock (_lock) _okVectors.Add(feature); + } + + public void AddNg(float[] feature) + { + ValidateFeature(feature); + lock (_lock) _ngVectors.Add(feature); + } + + /// 从 OK 库删除第 index 条 + public void RemoveOkAt(int index) + { + lock (_lock) + { + if (index >= 0 && index < _okVectors.Count) + _okVectors.RemoveAt(index); + } + } + + /// 从 NG 库删除第 index 条 + public void RemoveNgAt(int index) + { + lock (_lock) + { + if (index >= 0 && index < _ngVectors.Count) + _ngVectors.RemoveAt(index); + } + } + + /// + /// 从两个库中删除与目标向量最接近的样本(用于纠正误判时精确删除) + /// + /// 被误判的样本特征 + /// true=从OK库删, false=从NG库删 + /// 是否成功删除 + public bool RemoveNearest(float[] feature, bool fromOk) + { + ValidateFeature(feature); + lock (_lock) + { + var list = fromOk ? _okVectors : _ngVectors; + if (list.Count == 0) return false; + + int nearestIdx = 0; + float minDist = float.MaxValue; + for (int i = 0; i < list.Count; i++) + { + float d = L2Distance(feature, list[i]); + if (d < minDist) { minDist = d; nearestIdx = i; } + } + list.RemoveAt(nearestIdx); + return true; + } + } + + /// 清空所有库 + public void Clear() + { + lock (_lock) + { + _okVectors.Clear(); + _ngVectors.Clear(); + } + } + + /// 清空 OK 库 + public void ClearOk() + { + lock (_lock) _okVectors.Clear(); + } + + /// 清空 NG 库 + public void ClearNg() + { + lock (_lock) _ngVectors.Clear(); + } + + #endregion + + #region 序列化(保存/加载画廊数据) + + /// 导出为可序列化的传输对象 + public GalleryData Export() + { + lock (_lock) + { + return new GalleryData + { + Dimension = _dimension, + OkVectors = _okVectors.Select(v => (float[])v.Clone()).ToList(), + NgVectors = _ngVectors.Select(v => (float[])v.Clone()).ToList() + }; + } + } + + /// 从传输对象导入 + public void Import(GalleryData data) + { + if (data == null) throw new ArgumentNullException(nameof(data)); + if (data.Dimension != _dimension) + throw new ArgumentException($"维度不匹配:期望 {_dimension},数据 {data.Dimension}"); + + lock (_lock) + { + _okVectors.Clear(); + _ngVectors.Clear(); + foreach (var v in data.OkVectors) _okVectors.Add(v); + foreach (var v in data.NgVectors) _ngVectors.Add(v); + } + } + + #endregion + + #region 分类决策 + + /// + /// 分类结果 + /// + public readonly struct ClassificationResult + { + /// true=OK, false=NG + public readonly bool IsOk; + /// 到OK库最近距离(越小越像OK) + public readonly float OkDistance; + /// 到NG库最近距离(越小越像NG) + public readonly float NgDistance; + /// OK距离 - NG距离,负值偏向OK,正值偏向NG + public readonly float Delta; + + public ClassificationResult(bool isOk, float okDist, float ngDist) + { + IsOk = isOk; + OkDistance = okDist; + NgDistance = ngDist; + Delta = okDist - ngDist; + } + + /// OK 置信度 [0,1],仅作参考不严格概率意义 + public float OkConfidence => (OkDistance + NgDistance) < 1e-10f ? 0.5f + : NgDistance / (OkDistance + NgDistance); + } + + /// + /// 对输入特征进行分类决策。 + /// 比较到 OK 库和 NG 库的最短 L2 距离,选更近的一方。 + /// + public ClassificationResult Classify(float[] feature) + { + ValidateFeature(feature); + + lock (_lock) + { + bool hasOk = _okVectors.Count > 0; + bool hasNg = _ngVectors.Count > 0; + + // 只有一个库有样本时,退化为单类异常检测 + if (!hasOk && !hasNg) + return new ClassificationResult(true, float.MaxValue, float.MaxValue); + if (!hasOk) + return new ClassificationResult(false, float.MaxValue, MinDistance(feature, _ngVectors)); + if (!hasNg) + return new ClassificationResult(true, MinDistance(feature, _okVectors), float.MaxValue); + + float okDist = MinDistance(feature, _okVectors); + float ngDist = MinDistance(feature, _ngVectors); + + return new ClassificationResult(okDist <= ngDist, okDist, ngDist); + } + } + + /// + /// 获取 TopK 近邻信息(用于调试/可视化) + /// + public (float[] okDists, float[] ngDists) TopKDistances(float[] feature, int k) + { + ValidateFeature(feature); + lock (_lock) + { + var okDists = _okVectors.Select(v => L2Distance(feature, v)).OrderBy(d => d).Take(k).ToArray(); + var ngDists = _ngVectors.Select(v => L2Distance(feature, v)).OrderBy(d => d).Take(k).ToArray(); + return (okDists, ngDists); + } + } + + #endregion + + #region 内部 + + private void ValidateFeature(float[] feature) + { + if (feature == null) + throw new ArgumentNullException(nameof(feature)); + if (feature.Length != _dimension) + throw new ArgumentException($"特征维度应为 {_dimension},实际 {feature.Length}"); + } + + private static float MinDistance(float[] a, List vectors) + { + float min = float.MaxValue; + foreach (var v in vectors) + { + float d = L2Distance(a, v); + if (d < min) min = d; + } + return min; + } + + private static float L2Distance(float[] a, float[] b) + { + float sum = 0f; + for (int i = 0; i < a.Length; i++) + { + float diff = a[i] - b[i]; + sum += diff * diff; + } + return MathF.Sqrt(sum); + } + + #endregion + } + + #region 序列化传输对象 + + /// + /// 画廊数据的可序列化传输对象。 + /// 可用 System.Text.Json / Newtonsoft.Json 直接序列化保存到文件。 + /// + public class GalleryData + { + /// 特征维度 + public int Dimension { get; set; } + /// OK 特征向量列表 + public List OkVectors { get; set; } = []; + /// NG 特征向量列表 + public List NgVectors { get; set; } = []; + } + + #endregion +} diff --git a/PLCSharpWpf/VVMs/Vision/GalleryClassifier/OnnxEmbedding.cs b/PLCSharpWpf/VVMs/Vision/GalleryClassifier/OnnxEmbedding.cs new file mode 100644 index 0000000..2699603 --- /dev/null +++ b/PLCSharpWpf/VVMs/Vision/GalleryClassifier/OnnxEmbedding.cs @@ -0,0 +1,129 @@ +#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/GalleryClassifier/README.md b/PLCSharpWpf/VVMs/Vision/GalleryClassifier/README.md new file mode 100644 index 0000000..fa083bc --- /dev/null +++ b/PLCSharpWpf/VVMs/Vision/GalleryClassifier/README.md @@ -0,0 +1,61 @@ +# 画廊分类器 + +纯 C#、零额外依赖的 OK/NG 图像分类方案。基于特征向量画廊(Gallery),不需要训练神经网络,点击即时生效。 + +## 文件清单 + +``` +PLCSharpWpf/VVMs/Vision/GalleryClassifier/ + ├── FeatureGallery.cs # 核心:特征向量库,增删查 + L2 距离分类 + ├── OnnxEmbedding.cs # OpenCV DNN 封装:Mat → ONNX 推理 → 特征向量 + ├── export_embedding_model.py # Python 脚本:导出 .onnx 模型 + └── README.md + +PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/ + ├── GalleryClassifier.xaml # 参数编辑器界面(跟随项目现有模式) + ├── GalleryClassifier.xaml.cs + └── GalleryClassifierHandler.cs # 流程执行 Handler +``` + +VisionType.cs 和 VisionFunction.cs 中已注册"画廊分类"步骤。 +`VisionConfigViewModel.PublicCommands.cs` 中已添加训练/纠正/保存/加载命令。 + +## 使用前提:获取 ONNX 模型 + +在安装了 Python 和 PyTorch 的机器上运行: + +```bash +pip install torch torchvision onnx onnxruntime +python PLCSharpWpf/VVMs/Vision/GalleryClassifier/export_embedding_model.py +``` + +生成 `mobilenetv3_large_embedding.onnx`,放到一个路径下备用。 + +## 初始化(系统启动时调用一次) + +```csharp +GalleryClassifierHandler.InitializeShared( + modelPath: @"models/mobilenetv3_large_embedding.onnx", + featureDim: 960, + inputWidth: 224, + inputHeight: 224 +); +``` + +## 在视觉流程中使用 + +在流程编辑中添加"算法"分类下的"画廊分类"步骤。右侧编辑器面板提供: +- **训练为 OK / 训练为 NG** — 当前图像加入对应库 +- **纠正为 OK / 纠正为 NG** — 从反库删除最近邻再加入正库 +- **撤销**、**清空**、**保存画廊**、**加载画廊** + +流程运行后输出: +- `func.ResultString` = "OK" / "NG" +- `func.ResultDouble` = 1 / 0 +- `func.Params.ResultDoubles["Gallery_OKDist"]` +- `func.Params.ResultDoubles["Gallery_NGDist"]` + +## 注意 + +- 首次使用时画廊为空,OK 和 NG 至少各需一条样本才能做双边决策 +- 特征维度必须与模型输出一致(MobileNetV3-Large = 960) diff --git a/PLCSharpWpf/VVMs/Vision/GalleryClassifier/export_embedding_model.py b/PLCSharpWpf/VVMs/Vision/GalleryClassifier/export_embedding_model.py new file mode 100644 index 0000000..04adffe --- /dev/null +++ b/PLCSharpWpf/VVMs/Vision/GalleryClassifier/export_embedding_model.py @@ -0,0 +1,60 @@ +""" +一键导出 MobileNetV3-Large embedding ONNX 模型。 +自动下载预训练权重,不需要手动装 torch。 + +用法: + python export_embedding_model.py + +输出:mobilenetv3_large_embedding.onnx(约 20MB) +""" + +import subprocess, sys, os + +def run(cmd): + print(f"$ {cmd}") + subprocess.check_call(cmd, shell=True) + +def main(): + # 1. 自动装依赖(如果缺的话) + try: + import torch + import torchvision + except ImportError: + print("正在安装 torch + torchvision(首次需要,等待下载~200MB)...") + run(f"{sys.executable} -m pip install torch torchvision --index-url https://download.pytorch.org/whl/cpu") + + import torch + import torchvision.models as models + + # 2. 加载预训练权重(自动下载 ~20MB) + print("正在下载 MobileNetV3-Large 预训练权重...") + model = models.mobilenet_v3_large(weights='DEFAULT') + + # 3. 去掉分类头,只保留特征提取部分 + # 输出 960 维特征向量 + model.classifier = torch.nn.Identity() + model.eval() + + # 4. 导出 ONNX + dummy = torch.randn(1, 3, 224, 224) + output_path = "mobilenetv3_large_embedding.onnx" + torch.onnx.export( + model, dummy, output_path, + input_names=["input"], + output_names=["output"], + opset_version=17, + dynamic_axes={"input": {0: "batch_size"}, "output": {0: "batch_size"}} + ) + print(f"导出成功:{output_path} ({os.path.getsize(output_path)/1024/1024:.0f}MB)") + + # 5. 验证 + try: + import onnxruntime + session = onnxruntime.InferenceSession(output_path) + result = session.run(None, {"input": dummy.numpy()}) + print(f"验证通过:输出形状 {result[0].shape},特征维度 {result[0].shape[1]}") + except ImportError: + print("验证跳过(未安装 onnxruntime)") + +if __name__ == "__main__": + main() diff --git a/PLCSharpWpf/VVMs/Vision/VisionConfigViewModel.Flows.cs b/PLCSharpWpf/VVMs/Vision/VisionConfigViewModel.Flows.cs index 0d72d15..9f188a3 100644 --- a/PLCSharpWpf/VVMs/Vision/VisionConfigViewModel.Flows.cs +++ b/PLCSharpWpf/VVMs/Vision/VisionConfigViewModel.Flows.cs @@ -142,6 +142,9 @@ public partial class VisionConfigViewModel case VisionFlowType.点到线距离: ContentRegion = new PointToLineDistance(); break; + case VisionFlowType.画廊分类: + ContentRegion = new VisionFlowHandler.Algorithm.GalleryClassifier(); + break; } if (ContentRegion != null) @@ -374,6 +377,9 @@ public partial class VisionConfigViewModel newFlow.StringParams["Caliper_TransformOutVar"] = "找线_转换"; break; case VisionFlowType.卡尺找圆: + newFlow.StringParams["CircleResultVar"] = "卡尺找圆_Circle"; + newFlow.StringParams["CircleOffsetVar"] = "找圆_Offset"; + newFlow.StringParams["CircleFind_TransOutVar"] = "卡尺找圆_转换"; newFlow.IntParams["Threshold"] = 30; newFlow.IntParams["Direction"] = 0; newFlow.IntParams["CaliperDirection"] = 0; @@ -385,6 +391,7 @@ public partial class VisionConfigViewModel newFlow.IntParams["CaliperLength"] = 100; break; case VisionFlowType.卡尺找旋转矩形: + newFlow.StringParams["RectFind_TransOutVar"] = "卡尺旋转矩形_转换"; newFlow.IntParams["Threshold"] = 30; newFlow.IntParams["Direction"] = 0; newFlow.IntParams["CaliperDirection"] = 0; @@ -394,8 +401,13 @@ public partial class VisionConfigViewModel newFlow.IntParams["MinScore"] = 10; newFlow.IntParams["NumCalipers"] = 50; newFlow.IntParams["CaliperLength"] = 100; + newFlow.StringParams["ORBMatch_PosVar"] = "ORB匹配_Pos"; + newFlow.StringParams["ORBMatch_OffsetVar"] = "ORB匹配_Offset"; break; case VisionFlowType.ORB匹配: + newFlow.StringParams["Orb_TransOutVar"] = "ORB匹配_转换"; + newFlow.StringParams["OrbMatch_OffsetTransVar"] = "ORB匹配_偏移转换"; + newFlow.StringParams["ROIShape"] = "矩形"; newFlow.IntParams["NFeatures"] = 500; newFlow.IntParams["MinMatches"] = 8; newFlow.DoubleParams["MinGoodRatio"] = 0.3; @@ -461,6 +473,7 @@ public partial class VisionConfigViewModel newFlow.StringParams["ResultVarName"] = "灰度面积结果"; break; case VisionFlowType.灰度模板匹配: + newFlow.StringParams["ROIShape"] = "矩形"; newFlow.DoubleParams["MinAngle"] = -10; newFlow.DoubleParams["MaxAngle"] = 10; newFlow.DoubleParams["AngleStep"] = 1; @@ -470,18 +483,25 @@ public partial class VisionConfigViewModel newFlow.StringParams["GrayMatch_OffsetVar"] = "灰度模板匹配_偏移"; newFlow.BoolParams["GrayMatch_OutOffset"] = true; newFlow.StringParams["GrayMatch_TransOutVar"] = "灰度模板匹配_转换"; + newFlow.StringParams["GrayMatch_OffsetTransVar"] = "灰度模板匹配_偏移转换"; + newFlow.StringParams["ROIShape"] = "矩形"; break; case VisionFlowType.SIFT匹配: newFlow.IntParams["NFeatures"] = 1000; + newFlow.StringParams["GrayMatch_OffsetTransVar"] = "灰度模板匹配_偏移转换"; newFlow.IntParams["MinMatches"] = 8; newFlow.DoubleParams["MinGoodRatio"] = 0.3; newFlow.StringParams["TemplateName"] = "SIFT模板"; newFlow.StringParams["SiftMatch_PosVar"] = "SIFT匹配结果"; newFlow.StringParams["SiftMatch_OffsetVar"] = "SIFT匹配偏移"; newFlow.StringParams["SiftMatch_MatVar"] = "SIFT匹配矩阵"; + newFlow.StringParams["Sift_TransOutVar"] = "SIFT匹配_转换"; + newFlow.StringParams["SiftMatch_OffsetTransVar"] = "SIFT匹配_偏移转换"; newFlow.BoolParams["SiftMatch_OutPos"] = true; newFlow.BoolParams["SiftMatch_OutOffset"] = true; newFlow.BoolParams["SiftMatch_OutMat"] = true; + newFlow.StringParams["ROIShape"] = "矩形"; + break; case VisionFlowType.矩阵生成: newFlow.DoubleParams["MoveX"] = 0; @@ -498,6 +518,7 @@ public partial class VisionConfigViewModel newFlow.StringParams["PtLine_TransOutVar"] = "点到线距离_转换"; break; case VisionFlowType.两线交点: + newFlow.StringParams["TwoLine_TransOutVar"] = "两线交点_转换"; newFlow.StringParams["IntersectResultVar"] = "两线交点"; newFlow.StringParams["IntersectOffsetVar"] = "两线交点_Offset"; newFlow.BoolParams["TwoLine_OutOffset"] = true; diff --git a/PLCSharpWpf/VVMs/Vision/VisionConfigViewModel.Gallery.cs b/PLCSharpWpf/VVMs/Vision/VisionConfigViewModel.Gallery.cs new file mode 100644 index 0000000..9051285 --- /dev/null +++ b/PLCSharpWpf/VVMs/Vision/VisionConfigViewModel.Gallery.cs @@ -0,0 +1,349 @@ +#nullable enable +using OpenCvSharp; +using PLCSharp.Core.UserControls; +using PLCSharp.VVMs.Vision.GalleryClassifier; +using PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm; +using Prism.Commands; +using System; +using System.IO; +using System.Windows.Input; + +namespace PLCSharp.VVMs.Vision +{ + /// + /// 视觉流程配置界面 —— 画廊分类的训练命令 + /// + public partial class VisionConfigViewModel + { + #region 画廊分类 + + // 撤销状态(只记上一步,跟 SelectVisionFlow 绑定) + private string? _lastGalleryAction; + 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; + public AsyncDelegateCommand DrawGalleryRoiCommand => + _DrawGalleryRoiCommand ??= new AsyncDelegateCommand(ExecuteDrawGalleryRoiAsync); + + private async System.Threading.Tasks.Task ExecuteDrawGalleryRoiAsync() + { + var imageEdit = SelectedVisionFunction?.EditImageEdit; + if (imageEdit?.ImageSource == null) + { + SendInfoDialog("请先获取图片!"); + return; + } + if (SelectVisionFlow == null) return; + + var roi = await imageEdit.DrawROIAsync("画廊分类ROI"); + if (roi == null) return; + + SelectVisionFlow.DoubleParams["GalleryRoiLeft"] = roi.Left; + SelectVisionFlow.DoubleParams["GalleryRoiTop"] = roi.Top; + SelectVisionFlow.DoubleParams["GalleryRoiWidth"] = roi.Width; + SelectVisionFlow.DoubleParams["GalleryRoiHeight"] = roi.Height; + + imageEdit.DrawRectVisual(roi.Left, roi.Top, roi.Width, roi.Height); + SendInfoDialog("ROI 已保存"); + } + + #endregion + + #region 训练命令 + + public ICommand TrainGalleryOkCommand => _TrainGalleryOk ??= new DelegateCommand( + () => TrainGallery(true), CanTrainGallery); + private DelegateCommand? _TrainGalleryOk; + + public ICommand TrainGalleryNgCommand => _TrainGalleryNg ??= new DelegateCommand( + () => TrainGallery(false), CanTrainGallery); + private DelegateCommand? _TrainGalleryNg; + + public ICommand CorrectGalleryToOkCommand => _CorrectGalleryToOk ??= new DelegateCommand( + () => CorrectGallery(true), CanTrainGallery); + private DelegateCommand? _CorrectGalleryToOk; + + public ICommand CorrectGalleryToNgCommand => _CorrectGalleryToNg ??= new DelegateCommand( + () => CorrectGallery(false), CanTrainGallery); + private DelegateCommand? _CorrectGalleryToNg; + + public ICommand UndoGalleryCommand => _UndoGallery ??= new DelegateCommand( + ExecuteUndoGallery, () => _lastGalleryAction != null); + private DelegateCommand? _UndoGallery; + + public ICommand ClearGalleryCommand => _ClearGallery ??= new DelegateCommand(ExecuteClearGallery); + private DelegateCommand? _ClearGallery; + + public ICommand ExportGalleryCommand => _ExportGallery ??= new DelegateCommand(ExecuteExportGallery); + private DelegateCommand? _ExportGallery; + + public ICommand ImportGalleryCommand => _ImportGallery ??= new DelegateCommand(ExecuteImportGallery); + private DelegateCommand? _ImportGallery; + + #endregion + + #region 绑定属性 + + private int _GalleryOkCount; + public int GalleryOkCount + { + get => _GalleryOkCount; + set => SetProperty(ref _GalleryOkCount, value); + } + + private int _GalleryNgCount; + public int GalleryNgCount + { + get => _GalleryNgCount; + set => SetProperty(ref _GalleryNgCount, value); + } + + private string _GalleryStatus = "等待操作..."; + public string GalleryStatus + { + get => _GalleryStatus; + set => SetProperty(ref _GalleryStatus, value); + } + + private string _GalleryFileStatus = ""; + public string GalleryFileStatus + { + get => _GalleryFileStatus; + set => SetProperty(ref _GalleryFileStatus, value); + } + + #endregion + + #region 内部 + + private bool CanTrainGallery() + { + return SelectedVisionFunction?.Src != null && !SelectedVisionFunction.Src.Empty() + && SelectVisionFlow != null + && GalleryClassifierHandler.SharedEmbedding != null; + } + + private FeatureGallery GetGallery() + { + var flow = SelectVisionFlow ?? throw new InvalidOperationException("未选择步骤"); + var dim = GalleryClassifierHandler.SharedEmbedding?.FeatureDimension + ?? throw new InvalidOperationException("模型未加载"); + return GalleryClassifierHandler.LoadFromData(flow, dim); + } + + private void SaveGallery(FeatureGallery gallery) + { + var flow = SelectVisionFlow; + if (flow == null) return; + GalleryClassifierHandler.SaveToData(flow, gallery); + } + + private void TrainGallery(bool isOk) + { + var feature = ExtractGalleryFeature(); + if (feature == null) return; + + var gallery = GetGallery(); + if (isOk) gallery.AddOk(feature); + else gallery.AddNg(feature); + + SaveGallery(gallery); + _lastGalleryAction = "train"; + _lastGalleryFeature = feature; + _lastGalleryWasOk = isOk; + + AfterGalleryTrain(isOk ? "训练为 OK" : "训练为 NG", gallery); + } + + private void CorrectGallery(bool toOk) + { + var feature = ExtractGalleryFeature(); + if (feature == null) return; + + var gallery = GetGallery(); + gallery.RemoveNearest(feature, fromOk: !toOk); + if (toOk) gallery.AddOk(feature); + else gallery.AddNg(feature); + + SaveGallery(gallery); + _lastGalleryAction = "correct"; + _lastGalleryFeature = feature; + _lastGalleryWasOk = toOk; + + AfterGalleryTrain(toOk ? "纠正为 OK" : "纠正为 NG", gallery); + } + + private void ExecuteUndoGallery() + { + if (_lastGalleryAction == null || _lastGalleryFeature == null) return; + + var gallery = GetGallery(); + gallery.RemoveNearest(_lastGalleryFeature, _lastGalleryWasOk); + SaveGallery(gallery); + _lastGalleryAction = null; + _lastGalleryFeature = null; + + RefreshGalleryResult(gallery); + UpdateGalleryProperties(gallery); + GalleryStatus = "已撤销"; + } + + private void ExecuteClearGallery() + { + var gallery = GetGallery(); + gallery.Clear(); + SaveGallery(gallery); + _lastGalleryAction = null; + _lastGalleryFeature = null; + UpdateGalleryProperties(gallery); + GalleryStatus = "已清空"; + } + + private void ExecuteExportGallery() + { + var dialog = new Microsoft.Win32.SaveFileDialog + { + Filter = "画廊数据|*.json", + FileName = "gallery.json" + }; + if (dialog.ShowDialog() != true) return; + + var gallery = GetGallery(); + var json = System.Text.Json.JsonSerializer.Serialize(gallery.Export()); + File.WriteAllText(dialog.FileName, json); + GalleryFileStatus = "已导出"; + } + + private void ExecuteImportGallery() + { + var dialog = new Microsoft.Win32.OpenFileDialog + { + Filter = "画廊数据|*.json" + }; + 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); + gallery.Import(data); + GalleryClassifierHandler.SaveToData(SelectVisionFlow, gallery); + + UpdateGalleryProperties(gallery); + RefreshGalleryResult(gallery); + GalleryFileStatus = "已导入"; + } + + private float[]? ExtractGalleryFeature() + { + var func = SelectedVisionFunction; + if (func?.Src == null || func.Src.Empty()) + { + GalleryStatus = "没有图像"; + return null; + } + var embedding = GalleryClassifierHandler.SharedEmbedding; + if (embedding == null) return null; + + // ROI 裁剪(与 Handler 中一致):裁剪后提取特征,不影响原图 + var flow = SelectVisionFlow; + Mat? roiCloned = null; + try + { + Mat src = func.Src; + if (flow != null && + flow.DoubleParams.TryGetValue("GalleryRoiLeft", out double rl) && + flow.DoubleParams.TryGetValue("GalleryRoiTop", out double rt) && + flow.DoubleParams.TryGetValue("GalleryRoiWidth", out double rw) && + flow.DoubleParams.TryGetValue("GalleryRoiHeight", out double rh)) + { + int x = Math.Clamp((int)rl, 0, src.Width - 1); + int y = Math.Clamp((int)rt, 0, src.Height - 1); + int w = Math.Min((int)rw, src.Width - x); + int h = Math.Min((int)rh, src.Height - y); + if (w > 0 && h > 0) + roiCloned = src[new OpenCvSharp.Rect(x, y, w, h)].Clone(); + } + return embedding.Extract(roiCloned ?? func.Src); + } + finally + { + roiCloned?.Dispose(); + } + } + + private void AfterGalleryTrain(string action, FeatureGallery gallery) + { + UpdateGalleryProperties(gallery); + RefreshGalleryResult(gallery); + GalleryStatus = $"{action} OK:{gallery.OkCount} NG:{gallery.NgCount}"; + } + + private void RefreshGalleryResult(FeatureGallery gallery) + { + var func = SelectedVisionFunction; + if (func?.Src == null || func.Src.Empty() + || GalleryClassifierHandler.SharedEmbedding == null) + return; + + var feature = GalleryClassifierHandler.SharedEmbedding.Extract(func.Src); + var result = gallery.Classify(feature); + + func.ResultString = result.IsOk ? "OK" : "NG"; + func.ResultDouble = result.IsOk ? 1 : 0; + func.Params.ResultDoubles["Gallery_OKDist"] = Math.Round(result.OkDistance, 6); + func.Params.ResultDoubles["Gallery_NGDist"] = Math.Round(result.NgDistance, 6); + func.Params.ResultDoubles["Gallery_Delta"] = Math.Round(result.Delta, 6); + func.Params.ResultDoubles["Gallery_Confidence"] = Math.Round(result.OkConfidence, 4); + + func.DrawCommands.Clear(); + _ = func.RenderDrawAsync(); + } + + private void UpdateGalleryProperties(FeatureGallery gallery) + { + GalleryOkCount = gallery.OkCount; + GalleryNgCount = gallery.NgCount; + } + + #endregion + + #endregion + } +} diff --git a/PLCSharpWpf/VVMs/Vision/VisionConfigViewModel.PublicCommands.cs b/PLCSharpWpf/VVMs/Vision/VisionConfigViewModel.PublicCommands.cs index 2e3a0f4..a5ac140 100644 --- a/PLCSharpWpf/VVMs/Vision/VisionConfigViewModel.PublicCommands.cs +++ b/PLCSharpWpf/VVMs/Vision/VisionConfigViewModel.PublicCommands.cs @@ -1,7 +1,9 @@ using OpenCvSharp; using PLCSharp.Core.UserControls; using PLCSharp.VVMs.GlobalVariables; +using PLCSharp.VVMs.Vision.GalleryClassifier; using PLCSharp.VVMs.Vision.VisionFlowHandler; +using PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm; using Prism.Commands; using System.Windows.Controls; using System.Windows.Media; diff --git a/PLCSharpWpf/VVMs/Vision/VisionConfigViewModel.Variables.cs b/PLCSharpWpf/VVMs/Vision/VisionConfigViewModel.Variables.cs index 73cebf7..b5757fe 100644 --- a/PLCSharpWpf/VVMs/Vision/VisionConfigViewModel.Variables.cs +++ b/PLCSharpWpf/VVMs/Vision/VisionConfigViewModel.Variables.cs @@ -145,8 +145,12 @@ public partial class VisionConfigViewModel vars.Add(new LocalVariableItem(NextVarName(vars, "rect"), "Rect", new Rect())); break; case "Remove": - if (_SelectedLocalVariable != null && vars.Contains(_SelectedLocalVariable)) + if (_SelectedLocalVariable != null && vars.Contains(_SelectedLocalVariable)) { + vars.Remove(_SelectedLocalVariable); + + + } break; } } diff --git a/PLCSharpWpf/VVMs/Vision/VisionConfigViewModel.cs b/PLCSharpWpf/VVMs/Vision/VisionConfigViewModel.cs index 82ace29..45fdf89 100644 --- a/PLCSharpWpf/VVMs/Vision/VisionConfigViewModel.cs +++ b/PLCSharpWpf/VVMs/Vision/VisionConfigViewModel.cs @@ -235,7 +235,7 @@ namespace PLCSharp.VVMs.Vision Name = $"{baseName}{index}", FuncID = SelectedVisionFunction.ID }); - + ExecuteMatManage("Save"); break; case "Remove": @@ -253,6 +253,7 @@ namespace PLCSharp.VVMs.Vision VisionsModel._DatasContext.LocalImageDatas.Remove(dbItem); SelectedVisionFunction.LocalImageDatas.Remove(GridSelectedLocalImageData); + VisionsModel._DatasContext.Save(); } diff --git a/PLCSharpWpf/VVMs/Vision/VisionFlow.cs b/PLCSharpWpf/VVMs/Vision/VisionFlow.cs index 491a9d2..5a21e19 100644 --- a/PLCSharpWpf/VVMs/Vision/VisionFlow.cs +++ b/PLCSharpWpf/VVMs/Vision/VisionFlow.cs @@ -5,6 +5,7 @@ using PLCSharp.Core.Tools; using PLCSharp.Core.Common; using PLCSharp.Core.Prism; using PLCSharp.VVMs.Vision.Camera; +using PLCSharp.VVMs.Vision.GalleryClassifier; using PLCSharp.VVMs.Vision.VisionFlowHandler; using Prism.Mvvm; @@ -97,6 +98,19 @@ namespace PLCSharp.VVMs.Vision set { SetProperty(ref _BoolParams, AsObservable(value)); } } + private GalleryData? _GalleryData; + /// + /// 画廊分类特征向量库(OK/NG 特征向量列表),随流程步骤自动序列化/反序列化。 + /// 每个步骤独立拥有自己的画廊数据,跟其他参数一起保存到 SerializedVisionFlows。 + /// null 表示该步骤未使用画廊分类或尚未训练。 + /// + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public GalleryData? GalleryData + { + get => _GalleryData; + set => SetProperty(ref _GalleryData, value); + } + private FlowModel _Flow = new(); diff --git a/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/CaliperFindCircle.xaml b/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/CaliperFindCircle.xaml index 77307dd..9472bad 100644 --- a/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/CaliperFindCircle.xaml +++ b/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/CaliperFindCircle.xaml @@ -137,6 +137,30 @@ + + + + + + + + + + + + + + + + + + + diff --git a/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/CaliperFindCircleHandler.cs b/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/CaliperFindCircleHandler.cs index c9f9e36..d96e09f 100644 --- a/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/CaliperFindCircleHandler.cs +++ b/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/CaliperFindCircleHandler.cs @@ -246,6 +246,25 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm variable.RawValue = new Circle( new Pos(Math.Round(circle.CenterX, 3), Math.Round(circle.CenterY, 3), 0, 0), Math.Round(circle.Radius, 3)); + // 坐标转换 + double xfcx = circle.CenterX, xfcy = circle.CenterY; + if (item.BoolParams.TryGetValue("CircleFind_EnableTrans", out bool doCfXf) && doCfXf) + { + if (item.StringParams.TryGetValue("CircleFind_TransMat", out var cfxfN) && !string.IsNullOrEmpty(cfxfN)) + { + var sysVar = func.GlobalModel.VariablesModel.SystemVariables.FirstOrDefault(v => v.Name == cfxfN); + if (sysVar?.Value != null) + { + using var tm = MatExtension.DeserializeAffineMat((string)sysVar.Value); + var tp = TransformHelper.Apply(tm, circle.CenterX, circle.CenterY); + xfcx = Math.Round(tp.X, 3); xfcy = Math.Round(tp.Y, 3); + TransformHelper.WriteTransVar(func, item, "CircleFind_TransOutVar", "卡尺找圆_转换", "Circle", + new Circle(new Pos(xfcx, xfcy, 0, 0), Math.Round(circle.Radius, 3))); + } + } + } + + item.Flow.Done = true; _ = func.RenderDrawAsync(); diff --git a/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/CaliperFindRect.xaml b/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/CaliperFindRect.xaml index b21ed18..e8435c5 100644 --- a/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/CaliperFindRect.xaml +++ b/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/CaliperFindRect.xaml @@ -162,6 +162,30 @@ + + + + + + + + + + + + + + + + + + + diff --git a/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/CaliperFindRectHandler.cs b/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/CaliperFindRectHandler.cs index 901bb26..3037835 100644 --- a/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/CaliperFindRectHandler.cs +++ b/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/CaliperFindRectHandler.cs @@ -264,6 +264,25 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm variable.RawValue = new Rect( new Pos(Math.Round(fitCx, 3), Math.Round(fitCy, 3), 0, Math.Round(fitAngle, 3)), Math.Round(fitW, 3), Math.Round(fitH, 3)); + // 坐标转换 + double xfrx = fitCx, xfry = fitCy; + if (item.BoolParams.TryGetValue("RectFind_EnableTrans", out bool doRfXf) && doRfXf) + { + if (item.StringParams.TryGetValue("RectFind_TransMat", out var rfxfN) && !string.IsNullOrEmpty(rfxfN)) + { + var sysVar = func.GlobalModel.VariablesModel.SystemVariables.FirstOrDefault(v => v.Name == rfxfN); + if (sysVar?.Value != null) + { + using var tm = MatExtension.DeserializeAffineMat((string)sysVar.Value); + var tp = TransformHelper.Apply(tm, fitCx, fitCy); + xfrx = Math.Round(tp.X, 3); xfry = Math.Round(tp.Y, 3); + TransformHelper.WriteTransVar(func, item, "RectFind_TransOutVar", "卡尺旋转矩形_转换", "Rect", + new Rect(new Pos(xfrx, xfry, 0, fitAngle), Math.Round(fitW, 3), Math.Round(fitH, 3))); + } + } + } + + // 写入偏移变量 if (item.DoubleParams.TryGetValue("TemplateRectCX", out _)) diff --git a/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/GalleryClassifier.xaml b/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/GalleryClassifier.xaml new file mode 100644 index 0000000..bb9234f --- /dev/null +++ b/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/GalleryClassifier.xaml @@ -0,0 +1,182 @@ + + + + + + + + + + + + + + + + +