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 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/GalleryClassifier.xaml.cs b/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/GalleryClassifier.xaml.cs
new file mode 100644
index 0000000..a62922e
--- /dev/null
+++ b/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/GalleryClassifier.xaml.cs
@@ -0,0 +1,18 @@
+using System.Windows.Controls;
+
+namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
+{
+ ///
+ /// 画廊分类参数配置控件
+ ///
+ public partial class GalleryClassifier : UserControl
+ {
+ ///
+ /// 画廊分类
+ ///
+ public GalleryClassifier()
+ {
+ InitializeComponent();
+ }
+ }
+}
diff --git a/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/GalleryClassifierHandler.cs b/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/GalleryClassifierHandler.cs
new file mode 100644
index 0000000..1ce8a13
--- /dev/null
+++ b/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/GalleryClassifierHandler.cs
@@ -0,0 +1,135 @@
+#nullable enable
+using OpenCvSharp;
+using PLCSharp.VVMs.Vision.GalleryClassifier;
+using System;
+using System.IO;
+using System.Windows.Media;
+
+namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
+{
+ ///
+ /// 画廊分类 Handler。
+ /// 支持 ROI 选区:只对选区提取特征做分类,不影响原图,结果在原图上绘制。
+ /// 画廊数据存在 VisionFlow.GalleryData 中,随流程步骤自动序列化。
+ ///
+ public class GalleryClassifierHandler : IVisionFlowHandler
+ {
+ private static OnnxEmbedding? _sharedEmbedding;
+ private static string? _loadedModelPath;
+
+ public VisionFlowType Type => VisionFlowType.画廊分类;
+
+ public static OnnxEmbedding? GetOrCreateEmbedding(string modelPath)
+ {
+ if (_sharedEmbedding != null && _loadedModelPath == modelPath)
+ return _sharedEmbedding;
+ if (!File.Exists(modelPath))
+ return null;
+ _sharedEmbedding?.Dispose();
+ _sharedEmbedding = new OnnxEmbedding(modelPath, 224, 224, 960);
+ _loadedModelPath = modelPath;
+ return _sharedEmbedding;
+ }
+
+ public static OnnxEmbedding? SharedEmbedding => _sharedEmbedding;
+
+ public bool Execute(VisionFunction func, VisionFlow item)
+ {
+ var src = func.Src;
+ if (src == null || src.Empty())
+ throw new Exception("请先获取图片!");
+
+ string? modelPath = item.StringParams.TryGetValue("GalleryModelPath", out var mp)
+ && !string.IsNullOrEmpty(mp) ? mp : null;
+ if (string.IsNullOrEmpty(modelPath) || !File.Exists(modelPath))
+ throw new Exception("请先在步骤参数中点击 [浏览] 选择 .onnx 模型文件");
+
+ var embedding = GetOrCreateEmbedding(modelPath);
+ if (embedding == null)
+ throw new Exception("模型加载失败");
+
+ var gallery = LoadFromData(item, embedding.FeatureDimension);
+
+ // ROI 裁剪:从原图裁出选区用于分类,不影响 func.Src
+ Mat? roiCloned = null;
+ Mat extractSrc = src;
+ try
+ {
+ if (item.DoubleParams.TryGetValue("GalleryRoiLeft", out double rl) &&
+ item.DoubleParams.TryGetValue("GalleryRoiTop", out double rt) &&
+ item.DoubleParams.TryGetValue("GalleryRoiWidth", out double rw) &&
+ item.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();
+ extractSrc = roiCloned;
+ }
+ }
+
+ float[] feature = embedding.Extract(extractSrc);
+ 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);
+
+ // 在原图上绘制 ROI 框 + 分类结果
+ var color = result.IsOk ? Colors.Lime : Colors.Red;
+
+ // 如果有 ROI,画矩形框并标注结果
+ if (roiCloned != null)
+ {
+ double rrx = item.DoubleParams["GalleryRoiLeft"];
+ double rry = item.DoubleParams["GalleryRoiTop"];
+ double rrw = item.DoubleParams["GalleryRoiWidth"];
+ double rrh = item.DoubleParams["GalleryRoiHeight"];
+
+ func.DrawCommands.Add(DrawCommand.Polygon([
+ new(rrx, rry), new(rrx + rrw, rry),
+ new(rrx + rrw, rry + rrh), new(rrx, rry + rrh)
+ ], color, 3));
+ func.DrawCommands.Add(DrawCommand.TextBlock(rrx, rry - 30,
+ $"画廊分类: {func.ResultString} (OK:{result.OkDistance:F4} NG:{result.NgDistance:F4})",
+ color, 48));
+ }
+ else
+ {
+ // 全图分类,在左上角显示
+ func.DrawCommands.Add(DrawCommand.TextBlock(10, 100,
+ $"画廊分类: {func.ResultString}", color, 64));
+ func.DrawCommands.Add(DrawCommand.TextBlock(10, 200,
+ $"OK距离: {result.OkDistance:F6} NG距离: {result.NgDistance:F6}", color, 48));
+ }
+
+ _ = func.RenderDrawAsync();
+ item.Flow.Done = true;
+ return true;
+ }
+ finally
+ {
+ roiCloned?.Dispose();
+ }
+ }
+
+ public static FeatureGallery LoadFromData(VisionFlow item, int dimension)
+ {
+ var gallery = new FeatureGallery(dimension);
+ if (item.GalleryData != null)
+ gallery.Import(item.GalleryData);
+ return gallery;
+ }
+
+ public static void SaveToData(VisionFlow item, FeatureGallery gallery)
+ {
+ item.GalleryData = gallery.Export();
+ }
+ }
+}
diff --git a/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/GrayTemplateMatch.xaml b/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/GrayTemplateMatch.xaml
index 1eb43ce..1c75744 100644
--- a/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/GrayTemplateMatch.xaml
+++ b/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/GrayTemplateMatch.xaml
@@ -93,6 +93,7 @@
+
@@ -113,6 +114,9 @@
+
+
diff --git a/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/GrayTemplateMatchHandler.cs b/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/GrayTemplateMatchHandler.cs
index f51ef6b..aa1130b 100644
--- a/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/GrayTemplateMatchHandler.cs
+++ b/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/GrayTemplateMatchHandler.cs
@@ -106,8 +106,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
return false;
}
- // GetRotationMatrix2D 正角度 = OpenCV 顺时针 → 取反统一为视觉方向
- bestAngle = -bestAngle;
+ // ECC 输出 atan2 已为逆时针为正
// ===== 7. ECC 精调(亚像素位置 + 亚角度) =====
double matchX = bestX + etW / 2.0;
@@ -139,7 +138,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
double eccTx = eccWarp.At(0, 2), eccTy = eccWarp.At(1, 2);
matchX = eccCos * tplCX - eccSin * tplCY + eccTx + offX;
matchY = eccSin * tplCX + eccCos * tplCY + eccTy + offY;
- bestAngle = Math.Atan2(eccSin, eccCos) * 180.0 / Math.PI;
+ bestAngle = -Math.Atan2(eccSin, eccCos) * 180.0 / Math.PI;
etW = grayTemplate.Width; etH = grayTemplate.Height;
}
catch
@@ -186,7 +185,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
ov = new LocalVariableItem(offVarName, "Pos", new Pos());
System.Windows.Application.Current.Dispatcher.Invoke(() => func.Params.Variables.Add(ov));
}
- ov.RawValue = new Pos(Math.Round(offsetX, 2), Math.Round(offsetY, 2), 0, 0);
+ ov.RawValue = new Pos(Math.Round(offsetX, 2), Math.Round(offsetY, 2), 0, bestAngle);
}
// 坐标转换
@@ -223,6 +222,17 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
func.Params.ResultDoubles["GrayMatch_MatchY"] = xfMatchY;
func.Params.ResultDoubles["GrayMatch_Angle"] = Math.Round(bestAngle, 1);
+ // 偏移按比例缩放
+ double sx = Math.Sqrt(transformMat.At(0, 0) * transformMat.At(0, 0)
+ + transformMat.At(1, 0) * transformMat.At(1, 0));
+ double sy = Math.Sqrt(transformMat.At(0, 1) * transformMat.At(0, 1)
+ + transformMat.At(1, 1) * transformMat.At(1, 1));
+ double scale = (sx + sy) / 2.0;
+ double xfOffX = Math.Round(offsetX * scale, 2);
+ double xfOffY = Math.Round(offsetY * scale, 2);
+ TransformHelper.WriteTransVar(func, item, "GrayMatch_OffsetTransVar", "灰度模板匹配_偏移转换", "Pos",
+ new Pos(xfOffX, xfOffY, 0, Math.Round(func.Params.ResultDoubles["GrayMatch_OffsetAngle"], 2)));
+
// 转换变量
var xfVarName = item.StringParams.TryGetValue("GrayMatch_TransOutVar", out var xov) && !string.IsNullOrEmpty(xov) ? xov : null;
if (xfVarName != null)
@@ -253,8 +263,8 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
(-hw0, -hh0), (hw0, -hh0), (hw0, hh0), (-hw0, hh0)
};
var polyPts = corners.Select(c => new System.Windows.Point(
- matchX + c.x * cosA - c.y * sinA,
- matchY + c.x * sinA + c.y * cosA)).ToArray();
+ matchX + c.x * cosA + c.y * sinA,
+ matchY - c.x * sinA + c.y * cosA)).ToArray();
func.DrawCommands.Add(DrawCommand.Polygon(polyPts, magenta, 3));
func.DrawCommands.Add(DrawCommand.Line(matchX - 15, matchY, matchX + 15, matchY, magenta, 2));
diff --git a/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/ORBMatch.xaml b/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/ORBMatch.xaml
index e8aa64f..a41898e 100644
--- a/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/ORBMatch.xaml
+++ b/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/ORBMatch.xaml
@@ -83,6 +83,34 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/ORBMatchHandler.cs b/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/ORBMatchHandler.cs
index db4920b..a64f86a 100644
--- a/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/ORBMatchHandler.cs
+++ b/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/ORBMatchHandler.cs
@@ -1,334 +1,361 @@
-using OpenCvSharp;
-using PLCSharp.VVMs.Vision;
-
-namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
-{
- ///
- /// ORB匹配Handler
- ///
- public class ORBMatchHandler : IVisionFlowHandler
- {
- ///
- /// 类型
- ///
- public VisionFlowType Type => VisionFlowType.ORB匹配;
-
- ///
- /// 执行
- ///
- /// 视觉功能
- /// 变量项
- /// 返回布尔值
- public bool Execute(VisionFunction func, VisionFlow item)
- {
- var src = func.Src;
- if (src == null) throw new Exception("请先获取图片!");
-
- // 读取 ROI 形状
- string roiShape = item.StringParams.TryGetValue("ROIShape", out var rs)
- && !string.IsNullOrEmpty(rs) ? rs : "矩形";
-
- // 读取公共模板参数
- if (!item.DoubleParams.TryGetValue("TemplateCenterX", out double centerX) ||
- !item.DoubleParams.TryGetValue("TemplateCenterY", out double centerY) ||
- !item.DoubleParams.TryGetValue("Width", out double width) ||
- !item.DoubleParams.TryGetValue("Height", out double height))
- throw new Exception("模板未配置,请先画选区截取模板!");
-
- // 根据形状读取特有参数
- double templateW, templateH;
- switch (roiShape)
- {
- case "矩形":
- if (!item.DoubleParams.TryGetValue("TemplateLeft", out double tLeft) ||
- !item.DoubleParams.TryGetValue("TemplateTop", out double tTop) ||
- !item.DoubleParams.TryGetValue("TemplateWidth", out templateW) ||
- !item.DoubleParams.TryGetValue("TemplateHeight", out templateH))
- throw new Exception("矩形模板参数缺失!");
- centerX = tLeft + templateW / 2.0;
- centerY = tTop + templateH / 2.0;
- break;
- case "旋转矩形":
- if (!item.DoubleParams.TryGetValue("TemplateWidth", out templateW) ||
- !item.DoubleParams.TryGetValue("TemplateHeight", out templateH))
- { item.Flow.FailMessage = "旋转矩形模板参数缺失!"; return false; }
- break;
- case "圆形":
- if (!item.DoubleParams.TryGetValue("TemplateRadius", out double radius))
- throw new Exception("圆形模板参数缺失!");
- templateW = radius * 2; templateH = radius * 2;
- break;
- default:
- throw new Exception($"不支持的 ROI 形状:{roiShape}");
- }
-
- // 读取 ORB 参数
- int nfeatures = item.IntParams.TryGetValue("NFeatures", out int nf) ? Math.Max(nf, 500) : 500;
- double minGoodRatio = item.DoubleParams.TryGetValue("MinGoodRatio", out double mgr) ? Math.Clamp(mgr, 0.01, 1.0) : 0.3;
- int minMatches = item.IntParams.TryGetValue("MinMatches", out int mm) ? Math.Max(mm, 8) : 8;
-
- // 模板名称
- string templateName = item.StringParams.TryGetValue("TemplateName", out var tn) && !string.IsNullOrEmpty(tn)
- ? tn : "ORB_Template";
-
- // 动态创建的 Mat,需要 finally 中释放
- Mat graySrc = null, grayTemplate = null;
- Mat templateDescriptors = null;
- Mat srcDescriptors = null;
- Mat mask = null;
- Mat homography = null;
- Mat template = null;
- Mat templateMask = new Mat(); // 圆形模板遮罩(空 Mat = 无掩码)
-
- try
- {
- // ---------- 1. 提取或缓存模板 ----------
- template = Mat.Zeros((int)height, (int)width, MatType.CV_8UC3);
- var existing = func.LocalImageDatas.FirstOrDefault(m => m.Name == templateName);
- if (existing?.Mat != null && !existing.Mat.Empty())
- {
- if (roiShape == "旋转矩形")
- {
- // 旋转矩形:模板为外接矩形(完全包含旋转矩形),通过 BBox 参数定位
- if (!item.DoubleParams.TryGetValue("TemplateBBoxLeft", out double bbx) ||
- !item.DoubleParams.TryGetValue("TemplateBBoxTop", out double bby) ||
- !item.DoubleParams.TryGetValue("TemplateBBoxWidth", out double bbw) ||
- !item.DoubleParams.TryGetValue("TemplateBBoxHeight", out double bbh))
- throw new Exception("旋转矩形模板参数缺失!");
- OpenCvSharp.Rect bboxRoi = new((int)bbx, (int)bby, (int)bbw, (int)bbh);
- using var cloneMat = existing.Mat.Clone();
- template[bboxRoi] = cloneMat;
- }
- else
- {
- // 矩形 / 圆形:直接用 center - half 定位
- double left = centerX - templateW / 2.0;
- double top = centerY - templateH / 2.0;
- OpenCvSharp.Rect roi = new((int)left, (int)top, (int)templateW, (int)templateH);
- using var cloneMat = existing.Mat.Clone();
- template[roi] = cloneMat;
- }
- }
- else
- {
- throw new Exception("模板提取失败");
- }
-
- // 灰度化
- if (src.Channels() == 3)
- {
- graySrc = new Mat();
- Cv2.CvtColor(src, graySrc, ColorConversionCodes.BGR2GRAY);
- }
- else
- {
- graySrc = src.Clone();
- }
-
- if (template.Channels() == 3)
- {
- grayTemplate = new Mat();
- Cv2.CvtColor(template, grayTemplate, ColorConversionCodes.BGR2GRAY);
- }
- else
- {
- grayTemplate = template.Clone();
- }
-
- // 圆形模板创建遮罩(仅圆形区域参与特征检测)
- if (roiShape == "圆形")
- {
- templateMask = Mat.Zeros(grayTemplate.Size(), MatType.CV_8UC1);
- Cv2.Circle(templateMask,
- (int)(templateW / 2.0), (int)(templateH / 2.0),
- (int)(templateW / 2.0), Scalar.White, -1);
- }
-
- // ---------- 2. ORB 特征检测 ----------
- var orb = ORB.Create(nfeatures);
- // 源图特征
- srcDescriptors = new Mat();
- using Mat noMask = new Mat();
- orb.DetectAndCompute(graySrc, noMask, out KeyPoint[] srcKps, srcDescriptors);
- // 模板特征(圆形模板使用遮罩)
- templateDescriptors = new Mat();
- orb.DetectAndCompute(grayTemplate, templateMask, out KeyPoint[] templateKps, templateDescriptors);
-
- if (templateKps.Length < 2 || srcKps.Length < 2)
- throw new Exception($"特征点不足:模板 {templateKps.Length} 个,源图 {srcKps.Length} 个!");
-
- // ---------- 3. 特征匹配 ----------
- var bf = new BFMatcher(NormTypes.Hamming);
-
- DMatch[][] matchesKnn = bf.KnnMatch(templateDescriptors, srcDescriptors, 2);
-
- DMatch[] matches = [.. matchesKnn.Where(mt => mt[0].Distance < 0.7 * mt[1].Distance).Select(mt => mt[0])];
-
- if (matches.Length <= 3)
- throw new Exception("未找到任何匹配!");
-
-
- // 按距离排序,取前 N 个
- var sortedMatches = matches.OrderBy(m => m.Distance).ToArray();
-
- // 使用距离阈值:保留距离 < 2 * 最小距离 的匹配
- double minDist = sortedMatches[0].Distance;
- double maxDist = Math.Max(minDist * 2.0, 30.0);
- var goodMatches = sortedMatches.Where(m => m.Distance <= maxDist).ToArray();
-
- if (goodMatches.Length < minMatches)
- throw new Exception($"优质匹配点不足 ({goodMatches.Length} < {minMatches}),请调整参数或更换图片!");
-
- // ---------- 4. 计算变换 ----------
- // 模板上的点 (query)
- Point2f[] srcPts = [.. goodMatches.Select(m => templateKps[m.QueryIdx].Pt)];
- // 源图上的点 (train)
- Point2f[] dstPts = [.. goodMatches.Select(m => srcKps[m.TrainIdx].Pt)];
-
- // 用 FindHomography 找到透视变换矩阵
- mask = new Mat();
- homography = Cv2.FindHomography(InputArray.Create(srcPts), InputArray.Create(dstPts), HomographyMethods.Ransac, 3.0, mask);
-
- if (homography == null || homography.Empty())
- throw new Exception("计算变换矩阵失败!");
-
- // ---------- 5. 提取偏移量 ----------
- double h00 = homography.At(0, 0);
- double h01 = homography.At(0, 1);
- double h10 = homography.At(1, 0);
- double h11 = homography.At(1, 1);
-
- // 旋转角度(度)
- double angleRad = Math.Atan2(h10, h00);
- double deltaAngle = angleRad * 180.0 / Math.PI;
-
- // 将模板中心变换到源图中的位置(通过单应性矩阵)
- double[] srcCenter = { centerX, centerY, 1.0 };
- double tx = homography.At(0, 0) * srcCenter[0] + homography.At(0, 1) * srcCenter[1] + homography.At(0, 2);
- double ty = homography.At(1, 0) * srcCenter[0] + homography.At(1, 1) * srcCenter[1] + homography.At(1, 2);
- double tz = homography.At(2, 0) * srcCenter[0] + homography.At(2, 1) * srcCenter[1] + homography.At(2, 2);
- if (Math.Abs(tz) > 1e-10)
- {
- tx /= tz;
- ty /= tz;
- }
-
- double offsetX = tx - centerX;
- double offsetY = ty - centerY;
-
- // 内点比例
- int inlierCount = Cv2.CountNonZero(mask);
- double inlierRatio = (double)inlierCount / goodMatches.Length;
-
- // ---------- 6. 存储结果 ----------
- // 绝对位置:匹配到在源图中的位置和角度
- func.Params.ResultDoubles["MatchPosX"] = Math.Round(tx, 3);
- func.Params.ResultDoubles["MatchPosY"] = Math.Round(ty, 3);
- func.Params.ResultDoubles["MatchAngle"] = Math.Round(deltaAngle, 3);
- // 相对位移:相对于模板原位的偏移
- func.Params.ResultDoubles["ORBMatch_OffsetX"] = Math.Round(offsetX, 3);
- func.Params.ResultDoubles["ORBMatch_OffsetY"] = Math.Round(offsetY, 3);
- func.Params.ResultDoubles["ORBMatch_Angle"] = Math.Round(deltaAngle, 3);
- func.Params.ResultDoubles["ORBMatch_MatchCount"] = goodMatches.Length;
- func.Params.ResultDoubles["ORBMatch_InlierRatio"] = Math.Round(inlierRatio, 3);
- func.Params.ResultDoubles["ORBMatch_Score"] = Math.Round(inlierRatio * 100, 1);
-
- // ---------- 7. 写入局部变量表 ----------
- string posVarName = item.StringParams.TryGetValue("ORBMatch_PosVar", out var pn)
- && !string.IsNullOrEmpty(pn) ? pn : "ORB匹配_Pos";
- string offsetVarName = item.StringParams.TryGetValue("ORBMatch_OffsetVar", out var ov)
- && !string.IsNullOrEmpty(ov) ? ov : "ORB匹配_Offset";
-
- var posVar = func.Params.Variables.FirstOrDefault(v => v.Name == posVarName);
- if (posVar == null)
- {
- posVar = new LocalVariableItem(posVarName, "Pos", new Pos());
- System.Windows.Application.Current.Dispatcher.Invoke(() => func.Params.Variables.Add(posVar));
- }
- posVar.RawValue = new Pos(Math.Round(tx, 3), Math.Round(ty, 3), 0, Math.Round(deltaAngle, 3));
-
- var offsetVar = func.Params.Variables.FirstOrDefault(v => v.Name == offsetVarName);
- if (offsetVar == null)
- {
- offsetVar = new LocalVariableItem(offsetVarName, "Pos", new Pos());
- System.Windows.Application.Current.Dispatcher.Invoke(() => func.Params.Variables.Add(offsetVar));
- }
- offsetVar.RawValue = new Pos(Math.Round(offsetX, 3), Math.Round(offsetY, 3), 0, Math.Round(deltaAngle, 3));
-
- // ---------- 8. 可视化 ----------
- Mat colorSrc = null;
- if (func.Src.Channels() == 1)
- {
- colorSrc = new Mat();
- Cv2.CvtColor(func.Src, colorSrc, ColorConversionCodes.GRAY2BGR);
- func.Src = colorSrc;
- }
-
- // 根据形状画匹配结果
- switch (roiShape)
- {
- case "矩形":
- // 画旋转矩形(模板在源图中的位置,带旋转)
- var matchedRect = new RotatedRect(
- new Point2f((float)tx, (float)ty),
- new Size2f((float)templateW, (float)templateH),
- (float)deltaAngle);
- Cv2.Polylines(func.Src,
- [[.. matchedRect.Points().Select(p => new Point((int)p.X, (int)p.Y))]],
- true, Scalar.Magenta, 2);
- break;
-
- case "旋转矩形":
- // 读取模板原始角度,加上匹配旋转得到最终角度
- item.DoubleParams.TryGetValue("TemplateAngle", out double templateAngle);
- double finalAngle = deltaAngle + templateAngle;
- var rotatedRect = new RotatedRect(
- new Point2f((float)tx, (float)ty),
- new Size2f((float)templateW, (float)templateH),
- (float)finalAngle);
- Cv2.Polylines(func.Src,
- [[.. rotatedRect.Points().Select(p => new Point((int)p.X, (int)p.Y))]],
- true, Scalar.Magenta, 2);
- break;
-
- case "圆形":
- // 画匹配到的圆形
- Cv2.Circle(func.Src, (int)Math.Round(tx), (int)Math.Round(ty),
- (int)(templateW / 2.0), Scalar.Magenta, 2);
- Cv2.Circle(func.Src, (int)Math.Round(tx), (int)Math.Round(ty),
- 3, Scalar.Magenta, -1);
- break;
- }
-
- // 画匹配到的模板中心
- Cv2.Circle(func.Src, (int)Math.Round(tx), (int)Math.Round(ty), 8, Scalar.Magenta, 2);
- Cv2.Circle(func.Src, (int)Math.Round(tx), (int)Math.Round(ty), 3, Scalar.Magenta, -1);
-
- // 显示匹配信息
- string info = $"pos: ({tx:F1}, {ty:F1}) angle={deltaAngle:F1} | offs ({offsetX:F1}, {offsetY:F1})";
- Cv2.PutText(func.Src, info, new Point(10, 100), HersheyFonts.HersheySimplex, 1.8, Scalar.Lime, 2);
- Mat reMat = new();
- Cv2.DrawMatches(template, templateKps, func.Src, srcKps, goodMatches, reMat);
-
- // reMat 接管 func.Src,旧的 colorSrc 需要释放
- func.Src = reMat;
- colorSrc?.Dispose();
-
- item.Flow.Done = true;
- return true;
- }
- finally
- {
- // 确保异常时也释放资源
- graySrc?.Dispose();
- grayTemplate?.Dispose();
- templateDescriptors?.Dispose();
- srcDescriptors?.Dispose();
- mask?.Dispose();
- homography?.Dispose();
- template?.Dispose();
- templateMask?.Dispose();
- }
- }
- }
-}
+using OpenCvSharp;
+using PLCSharp.VVMs.Vision;
+
+namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
+{
+ ///
+ /// ORB匹配Handler
+ ///
+ public class ORBMatchHandler : IVisionFlowHandler
+ {
+ ///
+ /// 类型
+ ///
+ public VisionFlowType Type => VisionFlowType.ORB匹配;
+
+ ///
+ /// 执行
+ ///
+ /// 视觉功能
+ /// 变量项
+ /// 返回布尔值
+ public bool Execute(VisionFunction func, VisionFlow item)
+ {
+ var src = func.Src;
+ if (src == null) throw new Exception("请先获取图片!");
+
+ // 读取 ROI 形状
+ string roiShape = item.StringParams.TryGetValue("ROIShape", out var rs)
+ && !string.IsNullOrEmpty(rs) ? rs : "矩形";
+
+ // 读取公共模板参数
+ if (!item.DoubleParams.TryGetValue("TemplateCenterX", out double centerX) ||
+ !item.DoubleParams.TryGetValue("TemplateCenterY", out double centerY) ||
+ !item.DoubleParams.TryGetValue("Width", out double width) ||
+ !item.DoubleParams.TryGetValue("Height", out double height))
+ throw new Exception("模板未配置,请先画选区截取模板!");
+
+ // 根据形状读取特有参数
+ double templateW, templateH;
+ switch (roiShape)
+ {
+ case "矩形":
+ if (!item.DoubleParams.TryGetValue("TemplateLeft", out double tLeft) ||
+ !item.DoubleParams.TryGetValue("TemplateTop", out double tTop) ||
+ !item.DoubleParams.TryGetValue("TemplateWidth", out templateW) ||
+ !item.DoubleParams.TryGetValue("TemplateHeight", out templateH))
+ throw new Exception("矩形模板参数缺失!");
+ centerX = tLeft + templateW / 2.0;
+ centerY = tTop + templateH / 2.0;
+ break;
+ case "旋转矩形":
+ if (!item.DoubleParams.TryGetValue("TemplateWidth", out templateW) ||
+ !item.DoubleParams.TryGetValue("TemplateHeight", out templateH))
+ { item.Flow.FailMessage = "旋转矩形模板参数缺失!"; return false; }
+ break;
+ case "圆形":
+ if (!item.DoubleParams.TryGetValue("TemplateRadius", out double radius))
+ throw new Exception("圆形模板参数缺失!");
+ templateW = radius * 2; templateH = radius * 2;
+ break;
+ default:
+ throw new Exception($"不支持的 ROI 形状:{roiShape}");
+ }
+
+ // 读取 ORB 参数
+ int nfeatures = item.IntParams.TryGetValue("NFeatures", out int nf) ? Math.Max(nf, 500) : 500;
+ double minGoodRatio = item.DoubleParams.TryGetValue("MinGoodRatio", out double mgr) ? Math.Clamp(mgr, 0.01, 1.0) : 0.3;
+ int minMatches = item.IntParams.TryGetValue("MinMatches", out int mm) ? Math.Max(mm, 8) : 8;
+
+ // 模板名称
+ string templateName = item.StringParams.TryGetValue("TemplateName", out var tn) && !string.IsNullOrEmpty(tn)
+ ? tn : "ORB_Template";
+
+ // 动态创建的 Mat,需要 finally 中释放
+ Mat graySrc = null, grayTemplate = null;
+ Mat templateDescriptors = null;
+ Mat srcDescriptors = null;
+ Mat mask = null;
+ Mat homography = null;
+ Mat template = null;
+ Mat templateMask = new Mat(); // 圆形模板遮罩(空 Mat = 无掩码)
+
+ try
+ {
+ // ---------- 1. 提取或缓存模板 ----------
+ template = Mat.Zeros((int)height, (int)width, MatType.CV_8UC3);
+ var existing = func.LocalImageDatas.FirstOrDefault(m => m.Name == templateName);
+ if (existing?.Mat != null && !existing.Mat.Empty())
+ {
+ if (roiShape == "旋转矩形")
+ {
+ // 旋转矩形:模板为外接矩形(完全包含旋转矩形),通过 BBox 参数定位
+ if (!item.DoubleParams.TryGetValue("TemplateBBoxLeft", out double bbx) ||
+ !item.DoubleParams.TryGetValue("TemplateBBoxTop", out double bby) ||
+ !item.DoubleParams.TryGetValue("TemplateBBoxWidth", out double bbw) ||
+ !item.DoubleParams.TryGetValue("TemplateBBoxHeight", out double bbh))
+ throw new Exception("旋转矩形模板参数缺失!");
+ OpenCvSharp.Rect bboxRoi = new((int)bbx, (int)bby, (int)bbw, (int)bbh);
+ using var cloneMat = existing.Mat.Clone();
+ template[bboxRoi] = cloneMat;
+ }
+ else
+ {
+ // 矩形 / 圆形:直接用 center - half 定位
+ double left = centerX - templateW / 2.0;
+ double top = centerY - templateH / 2.0;
+ OpenCvSharp.Rect roi = new((int)left, (int)top, (int)templateW, (int)templateH);
+ using var cloneMat = existing.Mat.Clone();
+ template[roi] = cloneMat;
+ }
+ }
+ else
+ {
+ throw new Exception("模板提取失败");
+ }
+
+ // 灰度化
+ if (src.Channels() == 3)
+ {
+ graySrc = new Mat();
+ Cv2.CvtColor(src, graySrc, ColorConversionCodes.BGR2GRAY);
+ }
+ else
+ {
+ graySrc = src.Clone();
+ }
+
+ if (template.Channels() == 3)
+ {
+ grayTemplate = new Mat();
+ Cv2.CvtColor(template, grayTemplate, ColorConversionCodes.BGR2GRAY);
+ }
+ else
+ {
+ grayTemplate = template.Clone();
+ }
+
+ // 圆形模板创建遮罩(仅圆形区域参与特征检测)
+ if (roiShape == "圆形")
+ {
+ templateMask = Mat.Zeros(grayTemplate.Size(), MatType.CV_8UC1);
+ Cv2.Circle(templateMask,
+ (int)(templateW / 2.0), (int)(templateH / 2.0),
+ (int)(templateW / 2.0), Scalar.White, -1);
+ }
+
+ // ---------- 2. ORB 特征检测 ----------
+ var orb = ORB.Create(nfeatures);
+ // 源图特征
+ srcDescriptors = new Mat();
+ using Mat noMask = new Mat();
+ orb.DetectAndCompute(graySrc, noMask, out KeyPoint[] srcKps, srcDescriptors);
+ // 模板特征(圆形模板使用遮罩)
+ templateDescriptors = new Mat();
+ orb.DetectAndCompute(grayTemplate, templateMask, out KeyPoint[] templateKps, templateDescriptors);
+
+ if (templateKps.Length < 2 || srcKps.Length < 2)
+ throw new Exception($"特征点不足:模板 {templateKps.Length} 个,源图 {srcKps.Length} 个!");
+
+ // ---------- 3. 特征匹配 ----------
+ var bf = new BFMatcher(NormTypes.Hamming);
+
+ DMatch[][] matchesKnn = bf.KnnMatch(templateDescriptors, srcDescriptors, 2);
+
+ DMatch[] matches = [.. matchesKnn.Where(mt => mt[0].Distance < 0.7 * mt[1].Distance).Select(mt => mt[0])];
+
+ if (matches.Length <= 3)
+ throw new Exception("未找到任何匹配!");
+
+
+ // 按距离排序,取前 N 个
+ var sortedMatches = matches.OrderBy(m => m.Distance).ToArray();
+
+ // 使用距离阈值:保留距离 < 2 * 最小距离 的匹配
+ double minDist = sortedMatches[0].Distance;
+ double maxDist = Math.Max(minDist * 2.0, 30.0);
+ var goodMatches = sortedMatches.Where(m => m.Distance <= maxDist).ToArray();
+
+ if (goodMatches.Length < minMatches)
+ throw new Exception($"优质匹配点不足 ({goodMatches.Length} < {minMatches}),请调整参数或更换图片!");
+
+ // ---------- 4. 计算变换 ----------
+ // 模板上的点 (query)
+ Point2f[] srcPts = [.. goodMatches.Select(m => templateKps[m.QueryIdx].Pt)];
+ // 源图上的点 (train)
+ Point2f[] dstPts = [.. goodMatches.Select(m => srcKps[m.TrainIdx].Pt)];
+
+ // 用 FindHomography 找到透视变换矩阵
+ mask = new Mat();
+ homography = Cv2.FindHomography(InputArray.Create(srcPts), InputArray.Create(dstPts), HomographyMethods.Ransac, 3.0, mask);
+
+ if (homography == null || homography.Empty())
+ throw new Exception("计算变换矩阵失败!");
+
+ // ---------- 5. 提取偏移量 ----------
+ double h00 = homography.At(0, 0);
+ double h01 = homography.At(0, 1);
+ double h10 = homography.At(1, 0);
+ double h11 = homography.At(1, 1);
+
+ // 旋转角度(度)
+ double angleRad = -Math.Atan2(h10, h00);
+ double deltaAngle = angleRad * 180.0 / Math.PI;
+
+ // 将模板中心变换到源图中的位置(通过单应性矩阵)
+ double[] srcCenter = { centerX, centerY, 1.0 };
+ double tx = homography.At(0, 0) * srcCenter[0] + homography.At(0, 1) * srcCenter[1] + homography.At(0, 2);
+ double ty = homography.At(1, 0) * srcCenter[0] + homography.At(1, 1) * srcCenter[1] + homography.At(1, 2);
+ double tz = homography.At(2, 0) * srcCenter[0] + homography.At(2, 1) * srcCenter[1] + homography.At(2, 2);
+ if (Math.Abs(tz) > 1e-10)
+ {
+ tx /= tz;
+ ty /= tz;
+ }
+
+ double offsetX = tx - centerX;
+ double offsetY = ty - centerY;
+
+ // 内点比例
+ int inlierCount = Cv2.CountNonZero(mask);
+ double inlierRatio = (double)inlierCount / goodMatches.Length;
+
+ // ---------- 6. 存储结果 ----------
+ // 绝对位置:匹配到在源图中的位置和角度
+ func.Params.ResultDoubles["MatchPosX"] = Math.Round(tx, 3);
+ func.Params.ResultDoubles["MatchPosY"] = Math.Round(ty, 3);
+ func.Params.ResultDoubles["MatchAngle"] = Math.Round(deltaAngle, 3);
+ // 相对位移:相对于模板原位的偏移
+ func.Params.ResultDoubles["ORBMatch_OffsetX"] = Math.Round(offsetX, 3);
+ func.Params.ResultDoubles["ORBMatch_OffsetY"] = Math.Round(offsetY, 3);
+ func.Params.ResultDoubles["ORBMatch_Angle"] = Math.Round(deltaAngle, 3);
+ func.Params.ResultDoubles["ORBMatch_MatchCount"] = goodMatches.Length;
+ func.Params.ResultDoubles["ORBMatch_InlierRatio"] = Math.Round(inlierRatio, 3);
+ func.Params.ResultDoubles["ORBMatch_Score"] = Math.Round(inlierRatio * 100, 1);
+
+ // ---------- 7. 写入局部变量表 ----------
+ string posVarName = item.StringParams.TryGetValue("ORBMatch_PosVar", out var pn)
+ && !string.IsNullOrEmpty(pn) ? pn : "ORB匹配_Pos";
+ string offsetVarName = item.StringParams.TryGetValue("ORBMatch_OffsetVar", out var ov)
+ && !string.IsNullOrEmpty(ov) ? ov : "ORB匹配_Offset";
+
+ var posVar = func.Params.Variables.FirstOrDefault(v => v.Name == posVarName);
+ if (posVar == null)
+ {
+ posVar = new LocalVariableItem(posVarName, "Pos", new Pos());
+ System.Windows.Application.Current.Dispatcher.Invoke(() => func.Params.Variables.Add(posVar));
+ }
+ posVar.RawValue = new Pos(Math.Round(tx, 3), Math.Round(ty, 3), 0, Math.Round(deltaAngle, 3));
+
+ var offsetVar = func.Params.Variables.FirstOrDefault(v => v.Name == offsetVarName);
+ if (offsetVar == null)
+ {
+ offsetVar = new LocalVariableItem(offsetVarName, "Pos", new Pos());
+ System.Windows.Application.Current.Dispatcher.Invoke(() => func.Params.Variables.Add(offsetVar));
+ }
+ offsetVar.RawValue = new Pos(Math.Round(offsetX, 3), Math.Round(offsetY, 3), 0, Math.Round(deltaAngle, 3));
+
+ // ---------- 坐标转换 ----------
+ double orbTx = tx, orbTy = ty;
+ if (item.BoolParams.TryGetValue("Orb_EnableTrans", out bool doOrbXf) && doOrbXf)
+ {
+ if (item.StringParams.TryGetValue("Orb_TransMat", out var oxfName) && !string.IsNullOrEmpty(oxfName))
+ {
+ var sysVar = func.GlobalModel.VariablesModel.SystemVariables.FirstOrDefault(v => v.Name == oxfName);
+ if (sysVar?.Value != null)
+ {
+ using var tm = MatExtension.DeserializeAffineMat((string)sysVar.Value);
+ var tp = TransformHelper.Apply(tm, tx, ty);
+ orbTx = Math.Round(tp.X, 3); orbTy = Math.Round(tp.Y, 3);
+ func.Params.ResultDoubles["MatchPosX"] = orbTx;
+ func.Params.ResultDoubles["MatchPosY"] = orbTy;
+ TransformHelper.WriteTransVar(func, item, "Orb_TransOutVar", "ORB匹配_转换", "Pos",
+ new Pos(orbTx, orbTy, 0, Math.Round(deltaAngle, 2)));
+
+ // 偏移转换
+ double orbSx = Math.Sqrt(tm.Get(0, 0) * tm.Get(0, 0) + tm.Get(1, 0) * tm.Get(1, 0));
+ double orbSy = Math.Sqrt(tm.Get(0, 1) * tm.Get(0, 1) + tm.Get(1, 1) * tm.Get(1, 1));
+ double orbSc = (orbSx + orbSy) / 2.0;
+ TransformHelper.WriteTransVar(func, item, "OrbMatch_OffsetTransVar", "ORB匹配_偏移转换", "Pos",
+ new Pos(Math.Round(offsetX * orbSc, 2), Math.Round(offsetY * orbSc, 2), 0, Math.Round(deltaAngle, 2)));
+ }
+ }
+ }
+
+ // ---------- 8. 可视化 ----------
+ Mat colorSrc = null;
+ if (func.Src.Channels() == 1)
+ {
+ colorSrc = new Mat();
+ Cv2.CvtColor(func.Src, colorSrc, ColorConversionCodes.GRAY2BGR);
+ func.Src = colorSrc;
+ }
+
+ // 根据形状画匹配结果
+ switch (roiShape)
+ {
+ case "矩形":
+ // 画旋转矩形(模板在源图中的位置,带旋转)
+ var matchedRect = new RotatedRect(
+ new Point2f((float)tx, (float)ty),
+ new Size2f((float)templateW, (float)templateH),
+ (float)(-deltaAngle));
+ Cv2.Polylines(func.Src,
+ [[.. matchedRect.Points().Select(p => new Point((int)p.X, (int)p.Y))]],
+ true, Scalar.Magenta, 2);
+ break;
+
+ case "旋转矩形":
+ // 读取模板原始角度,加上匹配旋转得到最终角度
+ item.DoubleParams.TryGetValue("TemplateAngle", out double templateAngle);
+ double finalAngle = deltaAngle + templateAngle;
+ var rotatedRect = new RotatedRect(
+ new Point2f((float)tx, (float)ty),
+ new Size2f((float)templateW, (float)templateH),
+ (float)(-finalAngle));
+ Cv2.Polylines(func.Src,
+ [[.. rotatedRect.Points().Select(p => new Point((int)p.X, (int)p.Y))]],
+ true, Scalar.Magenta, 2);
+ break;
+
+ case "圆形":
+ // 画匹配到的圆形
+ Cv2.Circle(func.Src, (int)Math.Round(tx), (int)Math.Round(ty),
+ (int)(templateW / 2.0), Scalar.Magenta, 2);
+ Cv2.Circle(func.Src, (int)Math.Round(tx), (int)Math.Round(ty),
+ 3, Scalar.Magenta, -1);
+ break;
+ }
+
+ // 画匹配到的模板中心
+ Cv2.Circle(func.Src, (int)Math.Round(tx), (int)Math.Round(ty), 8, Scalar.Magenta, 2);
+ Cv2.Circle(func.Src, (int)Math.Round(tx), (int)Math.Round(ty), 3, Scalar.Magenta, -1);
+
+ // 显示匹配信息
+ string info = $"pos: ({tx:F1}, {ty:F1}) angle={deltaAngle:F1} | offs ({offsetX:F1}, {offsetY:F1})";
+ Cv2.PutText(func.Src, info, new Point(10, 100), HersheyFonts.HersheySimplex, 1.8, Scalar.Lime, 2);
+ Mat reMat = new();
+ Cv2.DrawMatches(template, templateKps, func.Src, srcKps, goodMatches, reMat);
+
+ // reMat 接管 func.Src,旧的 colorSrc 需要释放
+ func.Src = reMat;
+ colorSrc?.Dispose();
+
+ item.Flow.Done = true;
+ return true;
+ }
+ finally
+ {
+ // 确保异常时也释放资源
+ graySrc?.Dispose();
+ grayTemplate?.Dispose();
+ templateDescriptors?.Dispose();
+ srcDescriptors?.Dispose();
+ mask?.Dispose();
+ homography?.Dispose();
+ template?.Dispose();
+ templateMask?.Dispose();
+ }
+ }
+ }
+}
diff --git a/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/SiftMatch.xaml b/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/SiftMatch.xaml
index d9743f7..726c5e8 100644
--- a/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/SiftMatch.xaml
+++ b/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/SiftMatch.xaml
@@ -116,6 +116,34 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/SiftMatchHandler.cs b/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/SiftMatchHandler.cs
index 43dacca..24e6887 100644
--- a/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/SiftMatchHandler.cs
+++ b/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/SiftMatchHandler.cs
@@ -161,7 +161,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
double tz = h20 * c[0] + h21 * c[1] + h22;
if (Math.Abs(tz) > 1e-10) { tx /= tz; ty /= tz; }
- double deltaAngle = Math.Atan2(h10, h00) * 180.0 / Math.PI;
+ double deltaAngle = -Math.Atan2(h10, h00) * 180.0 / Math.PI;
double offsetX = tx - centerX;
double offsetY = ty - centerY;
@@ -222,7 +222,35 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
}
}
- // ===== 10. 可视化 =====
+ // ===== 10. 坐标转换 =====
+ double xfTx = tx, xfTy = ty;
+ if (item.BoolParams.TryGetValue("Sift_EnableTrans", out bool doSiftXf) && doSiftXf)
+ {
+ if (item.StringParams.TryGetValue("Sift_TransMat", out var sxfName) && !string.IsNullOrEmpty(sxfName))
+ {
+ var sysVar = func.GlobalModel.VariablesModel.SystemVariables.FirstOrDefault(v => v.Name == sxfName);
+ if (sysVar?.Value != null)
+ {
+ using var tm = MatExtension.DeserializeAffineMat((string)sysVar.Value);
+ var tp = TransformHelper.Apply(tm, tx, ty);
+ xfTx = Math.Round(tp.X, 3); xfTy = Math.Round(tp.Y, 3);
+ func.Params.ResultDoubles["MatchPosX"] = xfTx;
+ func.Params.ResultDoubles["MatchPosY"] = xfTy;
+ func.Params.ResultDoubles["MatchAngle"] = Math.Round(deltaAngle, 2);
+ TransformHelper.WriteTransVar(func, item, "Sift_TransOutVar", "SIFT匹配_转换", "Pos",
+ new Pos(xfTx, xfTy, 0, Math.Round(deltaAngle, 2)));
+
+ // 偏移转换
+ double sSx = Math.Sqrt(tm.Get(0, 0) * tm.Get(0, 0) + tm.Get(1, 0) * tm.Get(1, 0));
+ double sSy = Math.Sqrt(tm.Get(0, 1) * tm.Get(0, 1) + tm.Get(1, 1) * tm.Get(1, 1));
+ double sS = (sSx + sSy) / 2.0;
+ TransformHelper.WriteTransVar(func, item, "SiftMatch_OffsetTransVar", "SIFT匹配_偏移转换", "Pos",
+ new Pos(Math.Round(offsetX * sS, 2), Math.Round(offsetY * sS, 2), 0, Math.Round(deltaAngle, 2)));
+ }
+ }
+ }
+
+ // ===== 11. 可视化 =====
Mat colorSrc = null;
if (func.Src.Channels() == 1)
{
@@ -277,5 +305,31 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
Cv2.CvtColor(src, g, ColorConversionCodes.BGR2GRAY);
return g;
}
+
+ private static Point2f XfPt(Mat m, double px, double py)
+ {
+ if (m.Rows == 2)
+ return new Point2f(
+ (float)(px * m.At(0, 0) + py * m.At(0, 1) + m.At(0, 2)),
+ (float)(px * m.At(1, 0) + py * m.At(1, 1) + m.At(1, 2)));
+ double w = px * m.At(2, 0) + py * m.At(2, 1) + m.At(2, 2);
+ if (Math.Abs(w) < 1e-10) return new Point2f(0, 0);
+ return new Point2f(
+ (float)((px * m.At(0, 0) + py * m.At(0, 1) + m.At(0, 2)) / w),
+ (float)((px * m.At(1, 0) + py * m.At(1, 1) + m.At(1, 2)) / w));
+ }
+
+ private static void WriteTransVar(VisionFunction func, VisionFlow item, string paramKey, string defaultName, double x, double y, double ang)
+ {
+ var vn = item.StringParams.TryGetValue(paramKey, out var ov) && !string.IsNullOrEmpty(ov) ? ov : null;
+ if (vn == null) return;
+ var v = func.Params.Variables.FirstOrDefault(v => v.Name == vn);
+ if (v == null)
+ {
+ v = new LocalVariableItem(vn, "Pos", new Pos());
+ System.Windows.Application.Current.Dispatcher.Invoke(() => func.Params.Variables.Add(v));
+ }
+ v.RawValue = new Pos(x, y, 0, Math.Round(ang, 2));
+ }
}
}
diff --git a/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/TwoLineIntersect.xaml b/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/TwoLineIntersect.xaml
index 7a48bc9..c012743 100644
--- a/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/TwoLineIntersect.xaml
+++ b/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/TwoLineIntersect.xaml
@@ -107,11 +107,37 @@
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/TwoLineIntersectHandler.cs b/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/TwoLineIntersectHandler.cs
index feb0c32..bb8cab3 100644
--- a/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/TwoLineIntersectHandler.cs
+++ b/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/TwoLineIntersectHandler.cs
@@ -84,6 +84,25 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
System.Windows.Application.Current.Dispatcher.Invoke(() => func.Params.Variables.Add(resultVar));
}
resultVar.RawValue = new Pos(ix, iy, 0, intersectAngle);
+ // ---------- 坐标转换 ----------
+ double tlx = ix, tly = iy;
+ if (item.BoolParams.TryGetValue("TwoLine_EnableTrans", out bool doTlXf) && doTlXf)
+ {
+ if (item.StringParams.TryGetValue("TwoLine_TransMat", out var tlxfn) && !string.IsNullOrEmpty(tlxfn))
+ {
+ var sysVar = func.GlobalModel.VariablesModel.SystemVariables.FirstOrDefault(v => v.Name == tlxfn);
+ if (sysVar?.Value != null)
+ {
+ using var tm = MatExtension.DeserializeAffineMat((string)sysVar.Value);
+ var tp = TransformHelper.Apply(tm, ix, iy);
+ tlx = Math.Round(tp.X, 3); tly = Math.Round(tp.Y, 3);
+ TransformHelper.WriteTransVar(func, item, "TwoLine_TransOutVar", "两线交点_转换", "Pos",
+ new Pos(tlx, tly, 0, Math.Round(intersectAngle, 2)));
+ }
+ }
+ }
+
+
item.Flow.Done = true;
return true;
diff --git a/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/TransformHelper.cs b/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/TransformHelper.cs
new file mode 100644
index 0000000..cf075f4
--- /dev/null
+++ b/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/TransformHelper.cs
@@ -0,0 +1,75 @@
+using OpenCvSharp;
+
+namespace PLCSharp.VVMs.Vision.VisionFlowHandler
+{
+ ///
+ /// 坐标转换公共辅助方法
+ ///
+ public static class TransformHelper
+ {
+ ///
+ /// 应用 2x3 或 3x3 仿射/透视矩阵变换一个点
+ ///
+ public static Point2f Apply(Mat m, double px, double py)
+ {
+ if (m.Rows == 2)
+ return new Point2f(
+ (float)(px * m.At(0, 0) + py * m.At(0, 1) + m.At(0, 2)),
+ (float)(px * m.At(1, 0) + py * m.At(1, 1) + m.At(1, 2)));
+ double w = px * m.At(2, 0) + py * m.At(2, 1) + m.At(2, 2);
+ if (Math.Abs(w) < 1e-10) return new Point2f(0, 0);
+ return new Point2f(
+ (float)((px * m.At(0, 0) + py * m.At(0, 1) + m.At(0, 2)) / w),
+ (float)((px * m.At(1, 0) + py * m.At(1, 1) + m.At(1, 2)) / w));
+ }
+
+ ///
+ /// 从系统变量表中读取矩阵
+ ///
+ public static Mat? GetTransformMat(VisionFunction func, VisionFlow item, string paramKey)
+ {
+ if (!item.StringParams.TryGetValue(paramKey, out var name) || string.IsNullOrEmpty(name)) return null;
+ var sv = func.GlobalModel.VariablesModel.SystemVariables.FirstOrDefault(v => v.Name == name);
+ if (sv?.Value == null) return null;
+ return MatExtension.DeserializeAffineMat((string)sv.Value);
+ }
+
+ ///
+ /// 写入转换后变量
+ ///
+ public static void WriteTransVar(VisionFunction func, VisionFlow item, string paramKey, string defaultName, string varType, object value)
+ {
+ var vn = item.StringParams.TryGetValue(paramKey, out var ov) && !string.IsNullOrEmpty(ov) ? ov : null;
+ if (vn == null) return;
+ var v = func.Params.Variables.FirstOrDefault(v => v.Name == vn);
+ if (v == null)
+ {
+ v = new LocalVariableItem(vn, varType, value);
+ System.Windows.Application.Current.Dispatcher.Invoke(() => func.Params.Variables.Add(v));
+ }
+ else
+ v.RawValue = value;
+ }
+
+ ///
+ /// 标准坐标转换流程:读矩阵 → 变换点 → 覆盖 ResultDoubles → 写 TransOutVar
+ ///
+ public static Point2f ExecuteTransform(VisionFunction func, VisionFlow item,
+ string enableKey, string matKey, string outVarKey, string outVarDefault, string outVarType,
+ object outVarValue, Action updateResultDoubles,
+ double x, double y)
+ {
+ if (!item.BoolParams.TryGetValue(enableKey, out bool enabled) || !enabled)
+ return new Point2f((float)x, (float)y);
+
+ using var m = GetTransformMat(func, item, matKey);
+ if (m == null) return new Point2f((float)x, (float)y);
+
+ var pt = Apply(m, x, y);
+ double xfX = Math.Round(pt.X, 3), xfY = Math.Round(pt.Y, 3);
+ updateResultDoubles(xfX, xfY);
+ WriteTransVar(func, item, outVarKey, outVarDefault, outVarType, outVarValue);
+ return new Point2f((float)xfX, (float)xfY);
+ }
+ }
+}
diff --git a/PLCSharpWpf/VVMs/Vision/VisionFunction.cs b/PLCSharpWpf/VVMs/Vision/VisionFunction.cs
index d84717a..6fe6376 100644
--- a/PLCSharpWpf/VVMs/Vision/VisionFunction.cs
+++ b/PLCSharpWpf/VVMs/Vision/VisionFunction.cs
@@ -391,6 +391,7 @@ namespace PLCSharp.VVMs.Vision
[VisionFlowType.坐标转换] = new CoordinateTransformHandler(),
[VisionFlowType.ROI解码] = new BarcodeDecodeHandler(),
[VisionFlowType.微信解码] = new WeChatDecodeHandler(),
+ [VisionFlowType.画廊分类] = new GalleryClassifierHandler(),
[VisionFlowType.颜色面积] = new ColorAreaHandler(),
[VisionFlowType.灰度面积] = new GrayAreaHandler(),
[VisionFlowType.图像翻转] = new ImageFlipHandler(),
@@ -599,7 +600,6 @@ namespace PLCSharp.VVMs.Vision
set { SetProperty(ref _Variables, value); }
}
-
}
diff --git a/PLCSharpWpf/VVMs/Vision/VisionType.cs b/PLCSharpWpf/VVMs/Vision/VisionType.cs
index 9241633..97d641b 100644
--- a/PLCSharpWpf/VVMs/Vision/VisionType.cs
+++ b/PLCSharpWpf/VVMs/Vision/VisionType.cs
@@ -102,6 +102,9 @@
[FlowCategory("算法")]
SIFT匹配 = 42,
+
+ [FlowCategory("算法")]
+ 画廊分类 = 46,
}