diff --git a/PLCSharpWpf/Models/xfeat.onnx b/PLCSharpWpf/Models/xfeat.onnx
deleted file mode 100644
index fab6b7f..0000000
Binary files a/PLCSharpWpf/Models/xfeat.onnx and /dev/null differ
diff --git a/PLCSharpWpf/Models/xfeat.onnx.data b/PLCSharpWpf/Models/xfeat.onnx.data
deleted file mode 100644
index 92650a3..0000000
Binary files a/PLCSharpWpf/Models/xfeat.onnx.data and /dev/null differ
diff --git a/PLCSharpWpf/PLCSharp.csproj b/PLCSharpWpf/PLCSharp.csproj
index 4ae4e7a..fd6a747 100644
--- a/PLCSharpWpf/PLCSharp.csproj
+++ b/PLCSharpWpf/PLCSharp.csproj
@@ -21,7 +21,6 @@
-
@@ -38,12 +37,6 @@
Never
-
- PreserveNewest
-
-
- PreserveNewest
-
PreserveNewest
diff --git a/PLCSharpWpf/VVMs/Vision/VisionConfig.xaml b/PLCSharpWpf/VVMs/Vision/VisionConfig.xaml
index a92634d..2a58e32 100644
--- a/PLCSharpWpf/VVMs/Vision/VisionConfig.xaml
+++ b/PLCSharpWpf/VVMs/Vision/VisionConfig.xaml
@@ -260,7 +260,8 @@
Header="功能类型" IsReadOnly="True"
ItemsSource="{Binding Source={StaticResource FlowFromEnum}}"
SelectedItemBinding="{Binding Type}" />
-
+
+
diff --git a/PLCSharpWpf/VVMs/Vision/VisionConfigViewModel.Flows.cs b/PLCSharpWpf/VVMs/Vision/VisionConfigViewModel.Flows.cs
index b816792..6865628 100644
--- a/PLCSharpWpf/VVMs/Vision/VisionConfigViewModel.Flows.cs
+++ b/PLCSharpWpf/VVMs/Vision/VisionConfigViewModel.Flows.cs
@@ -133,9 +133,6 @@ public partial class VisionConfigViewModel
case VisionFlowType.SIFT匹配:
ContentRegion = new SiftMatch();
break;
- case VisionFlowType.XFeat匹配:
- ContentRegion = new XFeatMatch();
- break;
case VisionFlowType.矩阵生成:
ContentRegion = new MatrixGen();
break;
@@ -476,15 +473,6 @@ public partial class VisionConfigViewModel
newFlow.BoolParams["SiftMatch_OutOffset"] = true;
newFlow.BoolParams["SiftMatch_OutMat"] = true;
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.DoubleParams["MoveX"] = 0;
newFlow.DoubleParams["MoveY"] = 0;
diff --git a/PLCSharpWpf/VVMs/Vision/VisionConfigViewModel.PublicCommands.cs b/PLCSharpWpf/VVMs/Vision/VisionConfigViewModel.PublicCommands.cs
index ad21f68..2e3a0f4 100644
--- a/PLCSharpWpf/VVMs/Vision/VisionConfigViewModel.PublicCommands.cs
+++ b/PLCSharpWpf/VVMs/Vision/VisionConfigViewModel.PublicCommands.cs
@@ -757,56 +757,6 @@ 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/VisionFlow.cs b/PLCSharpWpf/VVMs/Vision/VisionFlow.cs
index 5eec6bd..491a9d2 100644
--- a/PLCSharpWpf/VVMs/Vision/VisionFlow.cs
+++ b/PLCSharpWpf/VVMs/Vision/VisionFlow.cs
@@ -119,5 +119,17 @@ namespace PLCSharp.VVMs.Vision
///
[JsonIgnore]
public CameraBase? Camera { get; set; }
+
+ private double _CT;
+ [JsonIgnore]
+
+ ///
+ ///
+ ///
+ public double CT
+ {
+ get { return _CT; }
+ set { SetProperty(ref _CT, value); }
+ }
}
}
diff --git a/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/XFeatMatch.xaml b/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/XFeatMatch.xaml
deleted file mode 100644
index 44b6c08..0000000
--- a/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/XFeatMatch.xaml
+++ /dev/null
@@ -1,136 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/XFeatMatch.xaml.cs b/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/XFeatMatch.xaml.cs
deleted file mode 100644
index 2a51529..0000000
--- a/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/XFeatMatch.xaml.cs
+++ /dev/null
@@ -1,12 +0,0 @@
-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
deleted file mode 100644
index 5973eef..0000000
--- a/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/XFeatMatchHandler.cs
+++ /dev/null
@@ -1,406 +0,0 @@
-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.FailMessage = "请先获取图片!"; 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.FailMessage = "模板未配置,请先画选区截取模板!"; 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.FailMessage = "矩形模板参数缺失!"; 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.FailMessage = "旋转矩形模板参数缺失!"; return false; }
- break;
- case "圆形":
- if (!item.DoubleParams.TryGetValue("TemplateRadius", out double radius))
- { item.Flow.FailMessage = "圆形模板参数缺失!"; return false; }
- templateW = radius * 2; templateH = radius * 2;
- break;
- default:
- item.Flow.FailMessage = $"不支持的 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.FailMessage = "模板提取失败,请先画选区截取模板!";
- 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.FailMessage = "旋转矩形模板参数缺失!"; 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.FailMessage = $"模板特征点不足({tplFeats.Length} < 4)"; return false; }
-
- var srcFeats = ExtractFeatures(session, src, maxDim, detThresh, topK);
- if (srcFeats.Length < 4)
- { item.Flow.FailMessage = $"搜索图特征点不足({srcFeats.Length} < 4)"; return false; }
-
- // ===== 5. 匹配 + RANSAC =====
- var result = MatchAndLocate(tplFeats, srcFeats,
- centerX, centerY, templateW, templateH, matchThresh);
-
- if (result == null)
- { item.Flow.FailMessage = "匹配点不足,定位失败!"; 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);
-
- // XFeat 模型要求 3 通道输入
- if (resized.Channels() == 1)
- Cv2.CvtColor(resized, resized, ColorConversionCodes.GRAY2BGR);
-
- // 预计算梯度方向(用于特征点方向)
- MatExtension.BGR2GRAY(resized, out Mat grayRs);
-
- 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 27cb3f6..5591024 100644
--- a/PLCSharpWpf/VVMs/Vision/VisionFunction.cs
+++ b/PLCSharpWpf/VVMs/Vision/VisionFunction.cs
@@ -13,6 +13,7 @@ using Prism.Mvvm;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
+using System.Diagnostics;
using System.Text.Json;
using System.Windows.Media;
@@ -245,6 +246,11 @@ namespace PLCSharp.VVMs.Vision
///
[NotMapped]
public FlowModel Flow { get; set; } = new();
+
+
+ [NotMapped]
+
+ public Stopwatch Sw { get; set; } = new();
///
/// 运行All
///
@@ -280,6 +286,7 @@ namespace PLCSharp.VVMs.Vision
break;
case 2:
{
+ Sw.Restart();
var item = VisionFlows[index];
flow.TaskBool = System.Threading.Tasks.Task.Run(() => RunItem(item));
item.Flow.StepTime = DateTime.Now;
@@ -293,6 +300,8 @@ namespace PLCSharp.VVMs.Vision
if (task == null) { flow.Step--; break; }
if (task.IsCompleted)
{
+ Sw.Stop();
+ item.CT = Math.Round(Sw.ElapsedMilliseconds / 1000.0, 3); // 转换为秒
if (task.Result)
{
flow.Step = 1; // 回到 case 1 取下一个
@@ -365,7 +374,6 @@ namespace PLCSharp.VVMs.Vision
[VisionFlowType.ORB匹配] = new ORBMatchHandler(),
[VisionFlowType.灰度模板匹配] = new GrayTemplateMatchHandler(),
[VisionFlowType.SIFT匹配] = new SiftMatchHandler(),
- [VisionFlowType.XFeat匹配] = new XFeatMatchHandler(),
[VisionFlowType.矩阵生成] = new MatrixGenHandler(),
[VisionFlowType.点到点距离] = new PointToPointDistanceHandler(),
[VisionFlowType.卡尺找圆] = new CaliperFindCircleHandler(),
diff --git a/PLCSharpWpf/VVMs/Vision/VisionType.cs b/PLCSharpWpf/VVMs/Vision/VisionType.cs
index c1b2e68..fcc1248 100644
--- a/PLCSharpWpf/VVMs/Vision/VisionType.cs
+++ b/PLCSharpWpf/VVMs/Vision/VisionType.cs
@@ -99,9 +99,6 @@
[FlowCategory("算法")]
SIFT匹配 = 42,
-
- [FlowCategory("算法")]
- XFeat匹配 = 43,
}