From 87c6960e9b851bc558231fcde948c0c360ab0be6 Mon Sep 17 00:00:00 2001
From: tfarcraw <123211521@163.com>
Date: Wed, 22 Jul 2026 09:06:20 +0800
Subject: [PATCH] siftMatch
---
.../Vision/VisionConfigViewModel.Flows.cs | 11 +
.../VisionConfigViewModel.PublicCommands.cs | 69 +++++
.../Algorithm/SiftMatch.xaml | 156 +++++++++++
.../Algorithm/SiftMatch.xaml.cs | 12 +
.../Algorithm/SiftMatchHandler.cs | 256 ++++++++++++++++++
PLCSharpWpf/VVMs/Vision/VisionFunction.cs | 1 +
PLCSharpWpf/VVMs/Vision/VisionType.cs | 3 +
7 files changed, 508 insertions(+)
create mode 100644 PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/SiftMatch.xaml
create mode 100644 PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/SiftMatch.xaml.cs
create mode 100644 PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/SiftMatchHandler.cs
diff --git a/PLCSharpWpf/VVMs/Vision/VisionConfigViewModel.Flows.cs b/PLCSharpWpf/VVMs/Vision/VisionConfigViewModel.Flows.cs
index 0a037de..3925779 100644
--- a/PLCSharpWpf/VVMs/Vision/VisionConfigViewModel.Flows.cs
+++ b/PLCSharpWpf/VVMs/Vision/VisionConfigViewModel.Flows.cs
@@ -120,6 +120,9 @@ public partial class VisionConfigViewModel
case VisionFlowType.灰度模板匹配:
ContentRegion = new GrayTemplateMatch();
break;
+ case VisionFlowType.SIFT匹配:
+ ContentRegion = new SiftMatch();
+ break;
case VisionFlowType.点到点距离:
ContentRegion = new PointToPointDistance();
break;
@@ -433,6 +436,14 @@ public partial class VisionConfigViewModel
newFlow.StringParams["TemplateName"] = "GrayMatch_Template";
newFlow.StringParams["GrayTemplateMatch_PosVar"] = "灰度模板匹配_Pos";
break;
+ case VisionFlowType.SIFT匹配:
+ newFlow.IntParams["NFeatures"] = 1000;
+ newFlow.IntParams["MinMatches"] = 8;
+ newFlow.DoubleParams["MinGoodRatio"] = 0.3;
+ newFlow.StringParams["TemplateName"] = "SIFT_Template";
+ newFlow.StringParams["SiftMatch_PosVar"] = "SIFT匹配_Pos";
+ newFlow.StringParams["SiftMatch_OffsetVar"] = "SIFT匹配_Offset";
+ break;
case VisionFlowType.点到点距离:
newFlow.StringParams["ResultVar"] = "点到点距离";
break;
diff --git a/PLCSharpWpf/VVMs/Vision/VisionConfigViewModel.PublicCommands.cs b/PLCSharpWpf/VVMs/Vision/VisionConfigViewModel.PublicCommands.cs
index 720fa32..6437cb2 100644
--- a/PLCSharpWpf/VVMs/Vision/VisionConfigViewModel.PublicCommands.cs
+++ b/PLCSharpWpf/VVMs/Vision/VisionConfigViewModel.PublicCommands.cs
@@ -686,6 +686,75 @@ public partial class VisionConfigViewModel
}
}
+ private AsyncDelegateCommand _DrawSiftMatchROI;
+ ///
+ /// 绘制 SIFT 匹配模板 ROI
+ ///
+ public AsyncDelegateCommand DrawSiftMatchROI =>
+ _DrawSiftMatchROI ??= new AsyncDelegateCommand(ExecuteDrawSiftMatchROIAsync);
+
+ private async Task ExecuteDrawSiftMatchROIAsync()
+ {
+ var imageEdit = SelectedVisionFunction?.EditImageEdit;
+ if (imageEdit?.ImageSource == null)
+ {
+ SendInfoDialog("请先获取图片!");
+ return;
+ }
+
+ try
+ {
+ if (SelectVisionFlow == null) return;
+
+ string roiShape = SelectVisionFlow.StringParams.TryGetValue("ROIShape", out var rs)
+ && !string.IsNullOrEmpty(rs) ? rs : "矩形";
+
+ double centerX = 0, centerY = 0;
+
+ switch (roiShape)
+ {
+ case "矩形":
+ {
+ var roi = await imageEdit.DrawROIAsync("SIFT匹配");
+ if (roi == null) return;
+
+ SelectVisionFlow.DoubleParams["TemplateLeft"] = roi.Left;
+ SelectVisionFlow.DoubleParams["TemplateTop"] = roi.Top;
+ SelectVisionFlow.DoubleParams["TemplateWidth"] = roi.Width;
+ SelectVisionFlow.DoubleParams["TemplateHeight"] = roi.Height;
+
+ centerX = roi.Left + roi.Width / 2.0;
+ centerY = roi.Top + roi.Height / 2.0;
+
+ var srcMat = SelectedVisionFunction.Src;
+ if (srcMat != null && !srcMat.Empty())
+ {
+ int x = Math.Clamp((int)roi.Left, 0, srcMat.Width - 1);
+ int y = Math.Clamp((int)roi.Top, 0, srcMat.Height - 1);
+ int w = Math.Min((int)roi.Width, srcMat.Width - x);
+ int h = Math.Min((int)roi.Height, srcMat.Height - y);
+ if (w > 0 && h > 0)
+ SaveTemplateMat(srcMat[new OpenCvSharp.Rect(x, y, w, h)].Clone());
+ }
+
+ imageEdit.DrawRectVisual(roi.Left, roi.Top, roi.Width, roi.Height);
+ break;
+ }
+ }
+
+ SelectVisionFlow.DoubleParams["Width"] = imageEdit.ImageSource.Width;
+ SelectVisionFlow.DoubleParams["Height"] = imageEdit.ImageSource.Height;
+ SelectVisionFlow.DoubleParams["TemplateCenterX"] = centerX;
+ SelectVisionFlow.DoubleParams["TemplateCenterY"] = centerY;
+
+ SendInfoDialog("模板已保存");
+ }
+ catch (Exception ex)
+ {
+ SendInfoDialog($"模板绘制失败:{ex.Message}");
+ }
+ }
+
///
/// 保存模板 Mat 到 Params(替换同名旧模板)
///
diff --git a/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/SiftMatch.xaml b/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/SiftMatch.xaml
new file mode 100644
index 0000000..f54d8da
--- /dev/null
+++ b/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/SiftMatch.xaml
@@ -0,0 +1,156 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/SiftMatch.xaml.cs b/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/SiftMatch.xaml.cs
new file mode 100644
index 0000000..d200a3d
--- /dev/null
+++ b/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/SiftMatch.xaml.cs
@@ -0,0 +1,12 @@
+using System.Windows.Controls;
+
+namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
+{
+ public partial class SiftMatch : UserControl
+ {
+ public SiftMatch()
+ {
+ InitializeComponent();
+ }
+ }
+}
diff --git a/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/SiftMatchHandler.cs b/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/SiftMatchHandler.cs
new file mode 100644
index 0000000..31ae806
--- /dev/null
+++ b/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/SiftMatchHandler.cs
@@ -0,0 +1,256 @@
+using OpenCvSharp;
+
+namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
+{
+ ///
+ /// SIFT + FLANN + Homography 特征匹配定位。
+ /// 对纹理丰富的物体鲁棒,天然支持旋转和尺度变化。
+ ///
+ public class SiftMatchHandler : IVisionFlowHandler
+ {
+ public VisionFlowType Type => VisionFlowType.SIFT匹配;
+
+ public bool Execute(VisionFunction func, VisionFlow item)
+ {
+ var src = func.Src;
+ if (src == null || src.Empty()) throw new Exception("请先获取图片!");
+
+ // ===== 1. 读取参数 =====
+ 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 imgW) ||
+ !item.DoubleParams.TryGetValue("Height", out double imgH))
+ 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))
+ throw new Exception("旋转矩形模板参数缺失!");
+ 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}");
+ }
+
+ int nFeatures = item.IntParams.TryGetValue("NFeatures", out int nf) ? Math.Max(nf, 500) : 1000;
+ 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 : "SIFT_Template";
+
+ string posVarName = item.StringParams.TryGetValue("SiftMatch_PosVar", out var pn)
+ && !string.IsNullOrEmpty(pn) ? pn : "SIFT匹配_Pos";
+ string offsetVarName = item.StringParams.TryGetValue("SiftMatch_OffsetVar", out var ov)
+ && !string.IsNullOrEmpty(ov) ? ov : "SIFT匹配_Offset";
+
+ // ===== 资源 =====
+ Mat graySrc = null, grayTemplate = null;
+ Mat tplDesc = null, srcDesc = null;
+ Mat mask = null, H = null;
+ Mat template = null;
+
+ try
+ {
+ // ===== 2. 加载模板(黑背景原图大小,ROI 位置放模板内容) =====
+ template = Mat.Zeros((int)imgH, (int)imgW, MatType.CV_8UC3);
+ var existing = func.LocalImageDatas.FirstOrDefault(m => m.Name == templateName);
+ if (existing?.Mat == null || existing.Mat.Empty())
+ {
+ item.Flow.ErrorState = "模板提取失败,请先画选区截取模板!";
+ return false;
+ }
+
+ if (roiShape == "旋转矩形")
+ {
+ 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
+ {
+ 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;
+ }
+
+ // ===== 3. 灰度化 =====
+ graySrc = ToGray(src);
+ grayTemplate = ToGray(template);
+
+ // ===== 4. SIFT 特征检测 =====
+ var sift = SIFT.Create(nFeatures);
+
+ tplDesc = new Mat();
+ using Mat noMask = new();
+ sift.DetectAndCompute(grayTemplate, noMask, out KeyPoint[] tplKps, tplDesc);
+
+ srcDesc = new Mat();
+ sift.DetectAndCompute(graySrc, noMask, out KeyPoint[] srcKps, srcDesc);
+
+ if (tplKps.Length < 2 || srcKps.Length < 2)
+ throw new Exception($"特征点不足:模板 {tplKps.Length} 个,搜索图 {srcKps.Length} 个!");
+
+ // ===== 5. FLANN 匹配 + Lowe's ratio test =====
+ var matcher = new FlannBasedMatcher();
+ DMatch[][] knnMatches = matcher.KnnMatch(tplDesc, srcDesc, 2);
+
+ var goodMatches = knnMatches
+ .Where(m => m.Length >= 2 && m[0].Distance < minGoodRatio * m[1].Distance)
+ .Select(m => m[0])
+ .ToArray();
+
+ if (goodMatches.Length < minMatches)
+ {
+ goodMatches = knnMatches
+ .Where(m => m.Length >= 2 && m[0].Distance < 0.85 * m[1].Distance)
+ .Select(m => m[0])
+ .ToArray();
+ }
+
+ if (goodMatches.Length < 4)
+ throw new Exception($"优质匹配点不足({goodMatches.Length} < 4),请确认物体纹理充足!");
+
+ // ===== 6. RANSAC 单应性 =====
+ Point2f[] srcPts = goodMatches.Select(m => tplKps[m.QueryIdx].Pt).ToArray();
+ Point2f[] dstPts = goodMatches.Select(m => srcKps[m.TrainIdx].Pt).ToArray();
+
+ mask = new Mat();
+ H = Cv2.FindHomography(
+ InputArray.Create(srcPts), InputArray.Create(dstPts),
+ HomographyMethods.Ransac, 3.0, mask);
+
+ if (H == null || H.Empty())
+ throw new Exception("计算单应性矩阵失败!");
+
+ // ===== 7. 计算偏移和角度 =====
+ double h00 = H.At(0, 0), h01 = H.At(0, 1), h02 = H.At(0, 2);
+ double h10 = H.At(1, 0), h11 = H.At(1, 1), h12 = H.At(1, 2);
+ double h20 = H.At(2, 0), h21 = H.At(2, 1), h22 = H.At(2, 2);
+
+ double[] c = { centerX, centerY, 1.0 };
+ double tx = h00 * c[0] + h01 * c[1] + h02;
+ double ty = h10 * c[0] + h11 * c[1] + h12;
+ 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 offsetX = tx - centerX;
+ double offsetY = ty - centerY;
+
+ int inlierCount = Cv2.CountNonZero(mask);
+ double inlierRatio = (double)inlierCount / goodMatches.Length;
+
+ // ===== 8. 存储结果 =====
+ 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["SiftMatch_OffsetX"] = Math.Round(offsetX, 3);
+ func.Params.ResultDoubles["SiftMatch_OffsetY"] = Math.Round(offsetY, 3);
+ func.Params.ResultDoubles["SiftMatch_Angle"] = Math.Round(deltaAngle, 3);
+ func.Params.ResultDoubles["SiftMatch_MatchCount"] = goodMatches.Length;
+ func.Params.ResultDoubles["SiftMatch_InlierRatio"] = Math.Round(inlierRatio, 3);
+ func.Params.ResultDoubles["SiftMatch_Score"] = Math.Round(inlierRatio * 100, 1);
+
+ // ===== 9. 局部变量 =====
+ 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 offVar = func.Params.Variables.FirstOrDefault(v => v.Name == offsetVarName);
+ if (offVar == null)
+ {
+ offVar = new LocalVariableItem(offsetVarName, "Pos", new Pos());
+ System.Windows.Application.Current.Dispatcher.Invoke(() => func.Params.Variables.Add(offVar));
+ }
+ offVar.RawValue = new Pos(Math.Round(offsetX, 3), Math.Round(offsetY, 3), 0, Math.Round(deltaAngle, 3));
+
+ // ===== 10. 可视化 =====
+ Mat colorSrc = null;
+ if (func.Src.Channels() == 1)
+ {
+ colorSrc = new Mat();
+ Cv2.CvtColor(func.Src, colorSrc, ColorConversionCodes.GRAY2BGR);
+ func.Src = colorSrc;
+ }
+
+ // 画矩形边框
+ var corners = new Point2f[]
+ {
+ new((float)(centerX - templateW / 2.0), (float)(centerY - templateH / 2.0)),
+ new((float)(centerX + templateW / 2.0), (float)(centerY - templateH / 2.0)),
+ new((float)(centerX + templateW / 2.0), (float)(centerY + templateH / 2.0)),
+ new((float)(centerX - templateW / 2.0), (float)(centerY + templateH / 2.0))
+ };
+ var dstCorners = Cv2.PerspectiveTransform(corners, H);
+ Cv2.Polylines(func.Src,
+ [[.. dstCorners.Select(p => new Point((int)p.X, (int)p.Y))]],
+ true, Scalar.Magenta, 2);
+
+ 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, tplKps, func.Src, srcKps, goodMatches, reMat);
+ func.Src = reMat;
+ colorSrc?.Dispose();
+
+ item.Flow.Done = true;
+ return true;
+ }
+ finally
+ {
+ graySrc?.Dispose();
+ grayTemplate?.Dispose();
+ tplDesc?.Dispose();
+ srcDesc?.Dispose();
+ mask?.Dispose();
+ H?.Dispose();
+ template?.Dispose();
+ }
+ }
+
+ private static Mat ToGray(Mat src)
+ {
+ if (src.Channels() == 1) return src.Clone();
+ var g = new Mat();
+ Cv2.CvtColor(src, g, ColorConversionCodes.BGR2GRAY);
+ return g;
+ }
+ }
+}
diff --git a/PLCSharpWpf/VVMs/Vision/VisionFunction.cs b/PLCSharpWpf/VVMs/Vision/VisionFunction.cs
index bc8c1e5..f211c88 100644
--- a/PLCSharpWpf/VVMs/Vision/VisionFunction.cs
+++ b/PLCSharpWpf/VVMs/Vision/VisionFunction.cs
@@ -367,6 +367,7 @@ namespace PLCSharp.VVMs.Vision
[VisionFlowType.卡尺寻边] = new CaliperFindEdgeHandler(),
[VisionFlowType.ORB匹配] = new ORBMatchHandler(),
[VisionFlowType.灰度模板匹配] = new GrayTemplateMatchHandler(),
+ [VisionFlowType.SIFT匹配] = new SiftMatchHandler(),
[VisionFlowType.点到点距离] = new PointToPointDistanceHandler(),
[VisionFlowType.卡尺找圆] = new CaliperFindCircleHandler(),
[VisionFlowType.卡尺找旋转矩形] = new CaliperFindRectHandler(),
diff --git a/PLCSharpWpf/VVMs/Vision/VisionType.cs b/PLCSharpWpf/VVMs/Vision/VisionType.cs
index fd4dfd3..ed804b3 100644
--- a/PLCSharpWpf/VVMs/Vision/VisionType.cs
+++ b/PLCSharpWpf/VVMs/Vision/VisionType.cs
@@ -84,6 +84,9 @@
[FlowCategory("算法")]
点到点距离 = 41,
+
+ [FlowCategory("算法")]
+ SIFT匹配 = 42,
}