diff --git a/PLCSharpWpf/Models/xfeat.onnx b/PLCSharpWpf/Models/xfeat.onnx
new file mode 100644
index 0000000..fab6b7f
Binary files /dev/null and b/PLCSharpWpf/Models/xfeat.onnx differ
diff --git a/PLCSharpWpf/Models/xfeat.onnx.data b/PLCSharpWpf/Models/xfeat.onnx.data
new file mode 100644
index 0000000..92650a3
Binary files /dev/null and b/PLCSharpWpf/Models/xfeat.onnx.data differ
diff --git a/PLCSharpWpf/PLCSharp.csproj b/PLCSharpWpf/PLCSharp.csproj
index 33fb3c6..a9d7dce 100644
--- a/PLCSharpWpf/PLCSharp.csproj
+++ b/PLCSharpWpf/PLCSharp.csproj
@@ -20,7 +20,8 @@
-
+
+
@@ -37,6 +38,12 @@
Never
+
+ PreserveNewest
+
+
+ PreserveNewest
+
PreserveNewest
diff --git a/PLCSharpWpf/VVMs/Vision/VisionConfigViewModel.Flows.cs b/PLCSharpWpf/VVMs/Vision/VisionConfigViewModel.Flows.cs
index 3925779..24bd4c1 100644
--- a/PLCSharpWpf/VVMs/Vision/VisionConfigViewModel.Flows.cs
+++ b/PLCSharpWpf/VVMs/Vision/VisionConfigViewModel.Flows.cs
@@ -123,6 +123,9 @@ public partial class VisionConfigViewModel
case VisionFlowType.SIFT匹配:
ContentRegion = new SiftMatch();
break;
+ case VisionFlowType.XFeat匹配:
+ ContentRegion = new XFeatMatch();
+ break;
case VisionFlowType.点到点距离:
ContentRegion = new PointToPointDistance();
break;
@@ -444,6 +447,15 @@ public partial class VisionConfigViewModel
newFlow.StringParams["SiftMatch_PosVar"] = "SIFT匹配_Pos";
newFlow.StringParams["SiftMatch_OffsetVar"] = "SIFT匹配_Offset";
break;
+ case VisionFlowType.XFeat匹配:
+ newFlow.DoubleParams["DetectThresh"] = 0.01;
+ newFlow.DoubleParams["MatchThresh"] = 0.6;
+ newFlow.IntParams["TopK"] = 4096;
+ newFlow.IntParams["MaxDim"] = 640;
+ newFlow.StringParams["TemplateName"] = "XFeat_Template";
+ newFlow.StringParams["XFeatMatch_PosVar"] = "XFeat匹配_Pos";
+ newFlow.StringParams["XFeatMatch_OffsetVar"] = "XFeat匹配_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 6437cb2..7b930a7 100644
--- a/PLCSharpWpf/VVMs/Vision/VisionConfigViewModel.PublicCommands.cs
+++ b/PLCSharpWpf/VVMs/Vision/VisionConfigViewModel.PublicCommands.cs
@@ -755,6 +755,56 @@ public partial class VisionConfigViewModel
}
}
+ private AsyncDelegateCommand _DrawXFeatMatchROI;
+ public AsyncDelegateCommand DrawXFeatMatchROI =>
+ _DrawXFeatMatchROI ??= new AsyncDelegateCommand(ExecuteDrawXFeatMatchROIAsync);
+
+ private async Task ExecuteDrawXFeatMatchROIAsync()
+ {
+ 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("XFeat匹配");
+ 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/XFeatMatch.xaml b/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/XFeatMatch.xaml
new file mode 100644
index 0000000..44b6c08
--- /dev/null
+++ b/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/XFeatMatch.xaml
@@ -0,0 +1,136 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/XFeatMatch.xaml.cs b/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/XFeatMatch.xaml.cs
new file mode 100644
index 0000000..2a51529
--- /dev/null
+++ b/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/XFeatMatch.xaml.cs
@@ -0,0 +1,12 @@
+using System.Windows.Controls;
+
+namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
+{
+ public partial class XFeatMatch : UserControl
+ {
+ public XFeatMatch()
+ {
+ InitializeComponent();
+ }
+ }
+}
diff --git a/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/XFeatMatchHandler.cs b/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/XFeatMatchHandler.cs
new file mode 100644
index 0000000..5e0f205
--- /dev/null
+++ b/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/XFeatMatchHandler.cs
@@ -0,0 +1,402 @@
+using OpenCvSharp;
+using Microsoft.ML.OnnxRuntime;
+using Microsoft.ML.OnnxRuntime.Tensors;
+
+namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
+{
+ public class XFeatMatchHandler : IVisionFlowHandler
+ {
+ public VisionFlowType Type => VisionFlowType.XFeat匹配;
+
+ // 全局共享 session(只加载一次)
+ private static InferenceSession? _session;
+ private static readonly object _lock = new();
+ private static readonly string ModelPath = "Models/xfeat.onnx";
+
+ private static InferenceSession GetSession()
+ {
+ if (_session == null)
+ {
+ lock (_lock)
+ {
+ _session ??= new InferenceSession(ModelPath);
+ }
+ }
+ return _session;
+ }
+
+ // 特征点结构
+ private struct XFeatPoint(int x, int y, float score, float theta, float[] desc)
+ {
+ public int X = x;
+ public int Y = y;
+ public float Score = score;
+ public float Theta = theta;
+ public float[] Desc = desc;
+ }
+
+ public bool Execute(VisionFunction func, VisionFlow item)
+ {
+ var src = func.Src;
+ if (src == null || src.Empty()) { item.Flow.ErrorState = "请先获取图片!"; return false; }
+
+ // ===== 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))
+ { item.Flow.ErrorState = "模板未配置,请先画选区截取模板!"; return false; }
+
+ 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))
+ { item.Flow.ErrorState = "矩形模板参数缺失!"; return false; }
+ 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.ErrorState = "旋转矩形模板参数缺失!"; return false; }
+ break;
+ case "圆形":
+ if (!item.DoubleParams.TryGetValue("TemplateRadius", out double radius))
+ { item.Flow.ErrorState = "圆形模板参数缺失!"; return false; }
+ templateW = radius * 2; templateH = radius * 2;
+ break;
+ default:
+ item.Flow.ErrorState = $"不支持的 ROI 形状:{roiShape}"; return false;
+ }
+
+ float matchThresh = (float)(item.DoubleParams.TryGetValue("MatchThresh", out double mt) ? mt : 0.6);
+ float detThresh = (float)(item.DoubleParams.TryGetValue("DetectThresh", out double dt) ? dt : 0.01);
+ int topK = item.IntParams.TryGetValue("TopK", out int tk) ? Math.Clamp(tk, 64, 8192) : 4096;
+ int maxDim = item.IntParams.TryGetValue("MaxDim", out int md) ? Math.Clamp(md, 240, 1200) : 640;
+
+ string templateName = item.StringParams.TryGetValue("TemplateName", out var tn)
+ && !string.IsNullOrEmpty(tn) ? tn : "XFeat_Template";
+ string posVarName = item.StringParams.TryGetValue("XFeatMatch_PosVar", out var pn)
+ && !string.IsNullOrEmpty(pn) ? pn : "XFeat匹配_Pos";
+ string offsetVarName = item.StringParams.TryGetValue("XFeatMatch_OffsetVar", out var ov)
+ && !string.IsNullOrEmpty(ov) ? ov : "XFeat匹配_Offset";
+
+ // ===== 资源 =====
+ Mat template = null;
+
+ try
+ {
+ // ===== 2. 加载模板(黑背景原图大小) =====
+ 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))
+ { item.Flow.ErrorState = "旋转矩形模板参数缺失!"; return false; }
+ using var cloneMat = existing.Mat.Clone();
+ template[new OpenCvSharp.Rect((int)bbx, (int)bby, (int)bbw, (int)bbh)] = 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. 加载 ONNX 模型 =====
+ var session = GetSession();
+
+ // ===== 4. 特征提取 =====
+ var tplFeats = ExtractFeatures(session, template, maxDim, detThresh, topK);
+ if (tplFeats.Length < 4)
+ { item.Flow.ErrorState = $"模板特征点不足({tplFeats.Length} < 4)"; return false; }
+
+ var srcFeats = ExtractFeatures(session, src, maxDim, detThresh, topK);
+ if (srcFeats.Length < 4)
+ { item.Flow.ErrorState = $"搜索图特征点不足({srcFeats.Length} < 4)"; return false; }
+
+ // ===== 5. 匹配 + RANSAC =====
+ var result = MatchAndLocate(tplFeats, srcFeats,
+ centerX, centerY, templateW, templateH, matchThresh);
+
+ if (result == null)
+ { item.Flow.ErrorState = "匹配点不足,定位失败!"; return false; }
+
+ // ===== 6. 结果 =====
+ double matchX = result.Value.X;
+ double matchY = result.Value.Y;
+ double deltaAngle = result.Value.Angle;
+ double offsetX = matchX - centerX;
+ double offsetY = matchY - centerY;
+
+ func.Params.ResultDoubles["MatchPosX"] = Math.Round(matchX, 2);
+ func.Params.ResultDoubles["MatchPosY"] = Math.Round(matchY, 2);
+ func.Params.ResultDoubles["MatchAngle"] = Math.Round(deltaAngle, 2);
+ func.Params.ResultDoubles["XFeatMatch_OffsetX"] = Math.Round(offsetX, 2);
+ func.Params.ResultDoubles["XFeatMatch_OffsetY"] = Math.Round(offsetY, 2);
+ func.Params.ResultDoubles["XFeatMatch_Angle"] = Math.Round(deltaAngle, 2);
+ func.Params.ResultDoubles["XFeatMatch_MatchCount"] = result.Value.Matches;
+ func.Params.ResultDoubles["XFeatMatch_Inliers"] = result.Value.Inliers;
+ func.Params.ResultDoubles["XFeatMatch_Score"] = Math.Round((double)result.Value.Inliers / Math.Max(1, result.Value.Matches) * 100, 1);
+
+ // ===== 7. 局部变量 =====
+ 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(matchX, 2), Math.Round(matchY, 2), 0, Math.Round(deltaAngle, 2));
+
+ 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, 2), Math.Round(offsetY, 2), 0, Math.Round(deltaAngle, 2));
+
+ // ===== 8. 可视化 =====
+ var cyan = System.Windows.Media.Colors.Cyan;
+ var lime = System.Windows.Media.Colors.Lime;
+ var yellow = System.Windows.Media.Color.FromArgb(180, 255, 255, 0);
+
+ // WPF Y轴向下,绘制时角度取反使视觉方向一致
+ double rad = -deltaAngle * Math.PI / 180.0;
+ double cosA = Math.Cos(rad), sinA = Math.Sin(rad);
+ double hw0 = templateW / 2.0, hh0 = templateH / 2.0;
+
+ var corners = new (double x, double y)[]
+ {
+ (-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();
+
+ func.DrawCommands.Add(DrawCommand.Polygon(polyPts, cyan, 3));
+ func.DrawCommands.Add(DrawCommand.FilledCircle(matchX, matchY, 4, cyan));
+
+ // 绘制匹配上的特征点(内点)
+ if (result.Value.InlierPts.Length > 0)
+ {
+ foreach (var pt in result.Value.InlierPts)
+ {
+ func.DrawCommands.Add(DrawCommand.FilledCircle(pt.X, pt.Y, 3, yellow));
+ }
+ }
+
+ func.DrawCommands.Add(DrawCommand.TextBlock(10, 60,
+ $"x:{matchX:F1} y:{matchY:F1} a:{deltaAngle:F1} deg", lime, 18));
+ func.DrawCommands.Add(DrawCommand.TextBlock(10, 84,
+ $"offset: ({offsetX:+0.0;-0.0}, {offsetY:+0.0;-0.0}) inliers:{result.Value.Inliers}/{result.Value.Matches}", lime, 14));
+
+ _ = func.RenderDrawAsync();
+ item.Flow.Done = true;
+ return true;
+ }
+ finally
+ {
+ template?.Dispose();
+ }
+ }
+
+ // ===== ONNX 特征提取 =====
+ private static XFeatPoint[] ExtractFeatures(InferenceSession session, Mat img,
+ int maxDim, float detThresh, int topK)
+ {
+ float scale = Math.Min((float)maxDim / img.Width, (float)maxDim / img.Height);
+ int newW = (int)(img.Width * scale / 32) * 32;
+ int newH = (int)(img.Height * scale / 32) * 32;
+ float scaleW = (float)newW / img.Width;
+ float scaleH = (float)newH / img.Height;
+
+ using Mat resized = new();
+ Cv2.Resize(img, resized, new Size(newW, newH), 0, 0, InterpolationFlags.Linear);
+
+ // 预计算梯度方向(用于特征点方向)
+ using Mat grayRs = new();
+ Cv2.CvtColor(resized, grayRs, ColorConversionCodes.BGR2GRAY);
+ using Mat dx = new(), dy = new();
+ Cv2.Sobel(grayRs, dx, MatType.CV_32F, 1, 0, 3, 1, 0, BorderTypes.Replicate);
+ Cv2.Sobel(grayRs, dy, MatType.CV_32F, 0, 1, 3, 1, 0, BorderTypes.Replicate);
+
+ var input = new DenseTensor([1, 3, newH, newW]);
+ unsafe
+ {
+ byte* pSrc = (byte*)resized.Data;
+ int step = (int)resized.Step();
+ for (int y = 0; y < newH; y++)
+ for (int x = 0; x < newW; x++)
+ {
+ int idx = y * step + x * 3;
+ input[0, 0, y, x] = pSrc[idx + 2] / 255f;
+ input[0, 1, y, x] = pSrc[idx + 1] / 255f;
+ input[0, 2, y, x] = pSrc[idx + 0] / 255f;
+ }
+ }
+
+ using var outputs = session.Run([NamedOnnxValue.CreateFromTensor("input", input)]);
+ var descTensor = outputs[0].AsTensor(); // [1, 64, H/8, W/8] descriptors
+ var kptLogits = outputs[1].AsTensor(); // [1, 65, H/8, W/8] keypoint logits
+ // output[2] = reliability, not used here
+
+ int Hc = kptLogits.Dimensions[2]; // coarse grid (H/8)
+ int Wc = kptLogits.Dimensions[3];
+ int Hf = Hc * 8, Wf = Wc * 8;
+
+ // 手动实现 get_kpts_heatmap: softmax 65ch → 取前64ch → 重排为 [H*8, W*8]
+ var heatmap = new float[Hf * Wf];
+
+ for (int h = 0; h < Hc; h++)
+ {
+ for (int w = 0; w < Wc; w++)
+ {
+ // softmax
+ float maxVal = float.MinValue;
+ for (int c = 0; c < 65; c++)
+ maxVal = Math.Max(maxVal, kptLogits[0, c, h, w]);
+
+ double sum = 0;
+ for (int c = 0; c < 65; c++)
+ sum += Math.Exp(kptLogits[0, c, h, w] - maxVal);
+
+ // 前 64 通道 → 8x8 子块
+ for (int sy = 0; sy < 8; sy++)
+ for (int sx = 0; sx < 8; sx++)
+ {
+ int c = sy * 8 + sx;
+ float prob = (float)(Math.Exp(kptLogits[0, c, h, w] - maxVal) / sum);
+ heatmap[(h * 8 + sy) * Wf + (w * 8 + sx)] = prob;
+ }
+ }
+ }
+
+ // 在全分辨率热力图上做 NMS 提取特征点
+ int halfNms = 4;
+ var pts = new List();
+
+ for (int y = halfNms; y < Hf - halfNms; y++)
+ {
+ for (int x = halfNms; x < Wf - halfNms; x++)
+ {
+ float score = heatmap[y * Wf + x];
+ if (score < detThresh) continue;
+
+ bool isMax = true;
+ for (int yy = -halfNms; yy <= halfNms && isMax; yy++)
+ for (int xx = -halfNms; xx <= halfNms; xx++)
+ if ((xx != 0 || yy != 0) && score < heatmap[(y + yy) * Wf + (x + xx)])
+ { isMax = false; break; }
+ if (!isMax) continue;
+
+ // 描述子坐标 (对应到网格)
+ int dgy = y / 8, dgx = x / 8;
+
+ var desc = new float[64];
+ for (int c = 0; c < 64; c++)
+ desc[c] = descTensor[0, c, dgy, dgx];
+
+ // 计算梯度方向(在缩放后的图像坐标上)
+ float gxVal = 0, gyVal = 0;
+ if (x < newW && y < newH)
+ {
+ unsafe
+ {
+ float* pDx = (float*)dx.Data;
+ float* pDy = (float*)dy.Data;
+ int step = (int)(dx.Step() / sizeof(float));
+ gxVal = pDx[y * step + x];
+ gyVal = pDy[y * step + x];
+ }
+ }
+ float theta = (float)(Math.Atan2(gyVal, gxVal) * 180.0 / Math.PI);
+
+ pts.Add(new XFeatPoint(
+ (int)(x / scaleW), (int)(y / scaleH), score, theta, desc));
+ }
+ }
+
+ pts.Sort((a, b) => b.Score.CompareTo(a.Score));
+ return pts.Take(Math.Min(topK, pts.Count)).ToArray();
+ }
+
+ // ===== 匹配 + 定位 =====
+ private record struct LocateResult(double X, double Y, double Angle, int Matches, int Inliers, Point2f[] InlierPts);
+
+ private static LocateResult? MatchAndLocate(XFeatPoint[] tpl, XFeatPoint[] src,
+ double cx, double cy, double tw, double th, float matchThresh)
+ {
+ if (tpl.Length < 4 || src.Length < 4) return null;
+
+ var matches = new List<(int ti, int si)>();
+ for (int ti = 0; ti < tpl.Length; ti++)
+ {
+ float best = float.MaxValue;
+ int bestSi = -1;
+ for (int si = 0; si < src.Length; si++)
+ {
+ float dot = 0, nt = 0, ns = 0;
+ for (int ch = 0; ch < 64; ch++)
+ {
+ dot += tpl[ti].Desc[ch] * src[si].Desc[ch];
+ nt += tpl[ti].Desc[ch] * tpl[ti].Desc[ch];
+ ns += src[si].Desc[ch] * src[si].Desc[ch];
+ }
+ float dist = 1 - dot / (float)(Math.Sqrt(nt) * Math.Sqrt(ns) + 1e-10f);
+ if (dist < best) { best = dist; bestSi = si; }
+ }
+ if (bestSi >= 0 && best < matchThresh)
+ matches.Add((ti, bestSi));
+ }
+
+ if (matches.Count < 4) return null;
+
+ var srcPts = matches.Select(m => new Point2f(tpl[m.ti].X, tpl[m.ti].Y)).ToArray();
+ var dstPts = matches.Select(m => new Point2f(src[m.si].X, src[m.si].Y)).ToArray();
+
+ using Mat mask = new();
+ using Mat H = Cv2.FindHomography(
+ InputArray.Create(srcPts), InputArray.Create(dstPts),
+ HomographyMethods.Ransac, 3.0, mask);
+
+ if (H == null || H.Empty()) return null;
+ int inliers = Cv2.CountNonZero(mask);
+ if (inliers < 4) return null;
+
+ // 收集内点(搜索图中匹配上的特征点)
+ var inlierPts = new List();
+ for (int i = 0; i < mask.Rows; i++)
+ if (mask.At(i, 0) != 0)
+ inlierPts.Add(dstPts[i]);
+
+ double[] c = { cx, cy, 1.0 };
+ double tx = H.At(0, 0) * c[0] + H.At(0, 1) * c[1] + H.At(0, 2);
+ double ty = H.At(1, 0) * c[0] + H.At(1, 1) * c[1] + H.At(1, 2);
+ double tz = H.At(2, 0) * c[0] + H.At(2, 1) * c[1] + H.At(2, 2);
+ if (Math.Abs(tz) > 1e-10) { tx /= tz; ty /= tz; }
+
+ double angle = Math.Atan2(H.At(1, 0), H.At(0, 0)) * 180.0 / Math.PI;
+ angle = -angle; // OpenCV 坐标系 Y 向下,取反使逆时针旋转为正角度
+ return new LocateResult(tx, ty, angle, matches.Count, inliers, [.. inlierPts]);
+ }
+ }
+}
diff --git a/PLCSharpWpf/VVMs/Vision/VisionFunction.cs b/PLCSharpWpf/VVMs/Vision/VisionFunction.cs
index f211c88..4d04a29 100644
--- a/PLCSharpWpf/VVMs/Vision/VisionFunction.cs
+++ b/PLCSharpWpf/VVMs/Vision/VisionFunction.cs
@@ -368,6 +368,7 @@ namespace PLCSharp.VVMs.Vision
[VisionFlowType.ORB匹配] = new ORBMatchHandler(),
[VisionFlowType.灰度模板匹配] = new GrayTemplateMatchHandler(),
[VisionFlowType.SIFT匹配] = new SiftMatchHandler(),
+ [VisionFlowType.XFeat匹配] = new XFeatMatchHandler(),
[VisionFlowType.点到点距离] = new PointToPointDistanceHandler(),
[VisionFlowType.卡尺找圆] = new CaliperFindCircleHandler(),
[VisionFlowType.卡尺找旋转矩形] = new CaliperFindRectHandler(),
diff --git a/PLCSharpWpf/VVMs/Vision/VisionType.cs b/PLCSharpWpf/VVMs/Vision/VisionType.cs
index ed804b3..b325824 100644
--- a/PLCSharpWpf/VVMs/Vision/VisionType.cs
+++ b/PLCSharpWpf/VVMs/Vision/VisionType.cs
@@ -87,6 +87,9 @@
[FlowCategory("算法")]
SIFT匹配 = 42,
+
+ [FlowCategory("算法")]
+ XFeat匹配 = 43,
}