删除xFeat

This commit is contained in:
tfarcraw 2026-07-23 12:22:57 +08:00
parent e703d865a2
commit 9c83b13673
12 changed files with 23 additions and 628 deletions

Binary file not shown.

Binary file not shown.

View File

@ -21,7 +21,6 @@
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="9.0.17" />
<PackageReference Include="MiniExcel" Version="1.45.0" />
<PackageReference Include="OpenCvSharp5.Windows" Version="5.0.0.20260718" />
<PackageReference Include="Microsoft.ML.OnnxRuntime" Version="1.21.0" />
<PackageReference Include="Prism.DryIoc" Version="9.0.537" />
<PackageReference Include="RoslynPad.Editor.Windows" Version="5.0.0" />
<!--<PackageReference Include="SourceGear.sqlite3" Version="3.50.4.5" />-->
@ -38,12 +37,6 @@
<None Update="SDK\Camera\MvCameraControl.Net.XML">
<CopyToOutputDirectory>Never</CopyToOutputDirectory>
</None>
<None Update="Models\xfeat.onnx">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="Models\xfeat.onnx.data">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="SDK\MotionControl\EMC\LTDMC.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>

View File

@ -260,7 +260,8 @@
Header="功能类型" IsReadOnly="True"
ItemsSource="{Binding Source={StaticResource FlowFromEnum}}"
SelectedItemBinding="{Binding Type}" />
<DataGridTextColumn MinWidth=" 100" Binding="{Binding Comment, UpdateSourceTrigger=LostFocus}" Header="备注" />
<DataGridTextColumn MinWidth="30" IsReadOnly="True" Binding="{Binding CT}" Header="耗时" />
<DataGridTextColumn MinWidth="100" Binding="{Binding Comment, UpdateSourceTrigger=LostFocus}" Header="备注" />
</DataGrid.Columns>

View File

@ -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;

View File

@ -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}"); }
}
/// <summary>
/// 保存模板 Mat 到 Params(替换同名旧模板)
/// </summary>

View File

@ -119,5 +119,17 @@ namespace PLCSharp.VVMs.Vision
/// </summary>
[JsonIgnore]
public CameraBase? Camera { get; set; }
private double _CT;
[JsonIgnore]
/// <summary>
///
/// </summary>
public double CT
{
get { return _CT; }
set { SetProperty(ref _CT, value); }
}
}
}

View File

@ -1,136 +0,0 @@
<UserControl x:Class="PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm.XFeatMatch"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:vision="clr-namespace:PLCSharp.VVMs.Vision"
mc:Ignorable="d"
d:DataContext="{d:DesignInstance Type=vision:VisionConfigViewModel}"
d:DesignHeight="500" d:DesignWidth="300">
<ScrollViewer VerticalScrollBarVisibility="Auto">
<StackPanel>
<GroupBox Header="模板">
<StackPanel>
<Grid Margin="5">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="ROI 形状" VerticalAlignment="Center" />
<ComboBox Grid.Column="1" Margin="5,0,0,0"
SelectedValue="{Binding SelectVisionFlow.StringParams[ROIShape], TargetNullValue=矩形}"
SelectedValuePath="Content">
<ComboBoxItem Content="矩形" IsSelected="True" />
<ComboBoxItem Content="旋转矩形" />
<ComboBoxItem Content="圆形" />
</ComboBox>
</Grid>
<Button Height="25" Margin="5" Command="{Binding DrawXFeatMatchROI}" Content="画选区截取模板" />
<Grid Margin="5">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<TextBlock Margin="5,0" Text="Left" VerticalAlignment="Center" />
<TextBox Grid.Column="1" Text="{Binding SelectVisionFlow.DoubleParams[TemplateLeft], UpdateSourceTrigger=LostFocus}" />
<TextBlock Grid.Column="2" Margin="5,0" Text="Top" VerticalAlignment="Center" />
<TextBox Grid.Column="3" Text="{Binding SelectVisionFlow.DoubleParams[TemplateTop], UpdateSourceTrigger=LostFocus}" />
<TextBlock Grid.Row="1" Margin="5,0" Text="宽度" VerticalAlignment="Center" />
<TextBox Grid.Row="1" Grid.Column="1" Text="{Binding SelectVisionFlow.DoubleParams[TemplateWidth], UpdateSourceTrigger=LostFocus}" />
<TextBlock Grid.Row="1" Grid.Column="2" Margin="5,0" Text="高度" VerticalAlignment="Center" />
<TextBox Grid.Row="1" Grid.Column="3" Text="{Binding SelectVisionFlow.DoubleParams[TemplateHeight], UpdateSourceTrigger=LostFocus}" />
<TextBlock Grid.Row="2" Text="模板名称" VerticalAlignment="Center" />
<TextBox Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="3" Text="{Binding SelectVisionFlow.StringParams[TemplateName], Mode=TwoWay, TargetNullValue=XFeat_Template}" />
</Grid>
</StackPanel>
</GroupBox>
<GroupBox Header="XFeat 参数">
<Grid Margin="5">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="90" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<TextBlock Text="检测阈值" VerticalAlignment="Center" ToolTip="关键点检测阈值(0~1),越低特征越多" />
<TextBox Grid.Column="1" Text="{Binding SelectVisionFlow.DoubleParams[DetectThresh], Mode=TwoWay, TargetNullValue=0.01, UpdateSourceTrigger=LostFocus}" />
<TextBlock Grid.Row="1" Text="匹配阈值" VerticalAlignment="Center" ToolTip="描述子余弦距离阈值(0~1),越低匹配越严格" />
<TextBox Grid.Row="1" Grid.Column="1" Text="{Binding SelectVisionFlow.DoubleParams[MatchThresh], Mode=TwoWay, TargetNullValue=0.6, UpdateSourceTrigger=LostFocus}" />
<TextBlock Grid.Row="2" Text="最大特征数" VerticalAlignment="Center" ToolTip="每张图保留的最大特征点数" />
<TextBox Grid.Row="2" Grid.Column="1" Text="{Binding SelectVisionFlow.IntParams[TopK], Mode=TwoWay, TargetNullValue=4096, UpdateSourceTrigger=LostFocus}" />
<TextBlock Grid.Row="3" Text="输入分辨率" VerticalAlignment="Center" ToolTip="输入图片的最大边长,越大越慢但特征越多" />
<TextBox Grid.Row="3" Grid.Column="1" Text="{Binding SelectVisionFlow.IntParams[MaxDim], Mode=TwoWay, TargetNullValue=640, UpdateSourceTrigger=LostFocus}" />
</Grid>
</GroupBox>
<GroupBox Header="变量设置">
<Grid Margin="5">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="90" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<TextBlock Text="绝对位置变量" VerticalAlignment="Center" ToolTip="匹配到的绝对位置写入此 Pos 变量" />
<TextBox Grid.Column="1" Text="{Binding SelectVisionFlow.StringParams[XFeatMatch_PosVar], Mode=TwoWay, TargetNullValue=XFeat匹配_Pos}" />
<TextBlock Grid.Row="1" Text="相对位移变量" VerticalAlignment="Center" ToolTip="相对位移写入此 Pos 变量" />
<TextBox Grid.Row="1" Grid.Column="1" Text="{Binding SelectVisionFlow.StringParams[XFeatMatch_OffsetVar], Mode=TwoWay, TargetNullValue=XFeat匹配_Offset}" />
</Grid>
</GroupBox>
<GroupBox Header="匹配结果">
<Grid Margin="5">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<TextBlock Grid.ColumnSpan="4" Text="— 绝对位置 —" FontWeight="Bold" HorizontalAlignment="Center" />
<TextBlock Grid.Row="1" Margin="5,0" Text="匹配 X" VerticalAlignment="Center" />
<TextBox Grid.Row="1" Grid.Column="1" Text="{Binding SelectedVisionFunction.Params.ResultDoubles[MatchPosX], Mode=OneWay}" IsReadOnly="True" Background="#FFF0F0F0" />
<TextBlock Grid.Row="1" Grid.Column="2" Margin="5,0" Text="匹配 Y" VerticalAlignment="Center" />
<TextBox Grid.Row="1" Grid.Column="3" Text="{Binding SelectedVisionFunction.Params.ResultDoubles[MatchPosY], Mode=OneWay}" IsReadOnly="True" Background="#FFF0F0F0" />
<TextBlock Grid.Row="2" Margin="5,0" Text="角度" VerticalAlignment="Center" />
<TextBox Grid.Row="2" Grid.Column="1" Text="{Binding SelectedVisionFunction.Params.ResultDoubles[MatchAngle], Mode=OneWay}" IsReadOnly="True" Background="#FFF0F0F0" />
<TextBlock Grid.Row="3" Grid.ColumnSpan="4" Text="— 相对位移 —" FontWeight="Bold" HorizontalAlignment="Center" />
<TextBlock Grid.Row="4" Margin="5,0" Text="X 偏移" VerticalAlignment="Center" />
<TextBox Grid.Row="4" Grid.Column="1" Text="{Binding SelectedVisionFunction.Params.ResultDoubles[XFeatMatch_OffsetX], Mode=OneWay}" IsReadOnly="True" Background="#FFF0F0F0" />
<TextBlock Grid.Row="4" Grid.Column="2" Margin="5,0" Text="Y 偏移" VerticalAlignment="Center" />
<TextBox Grid.Row="4" Grid.Column="3" Text="{Binding SelectedVisionFunction.Params.ResultDoubles[XFeatMatch_OffsetY], Mode=OneWay}" IsReadOnly="True" Background="#FFF0F0F0" />
<TextBlock Grid.Row="5" Grid.ColumnSpan="2" Margin="5,0" Text="内点数" VerticalAlignment="Center" />
<TextBox Grid.Row="5" Grid.Column="2" Grid.ColumnSpan="2" Text="{Binding SelectedVisionFunction.Params.ResultDoubles[XFeatMatch_Inliers], Mode=OneWay}" IsReadOnly="True" Background="#FFF0F0F0" />
</Grid>
</GroupBox>
</StackPanel>
</ScrollViewer>
</UserControl>

View File

@ -1,12 +0,0 @@
using System.Windows.Controls;
namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
{
public partial class XFeatMatch : UserControl
{
public XFeatMatch()
{
InitializeComponent();
}
}
}

View File

@ -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<float>([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<float>(); // [1, 64, H/8, W/8] descriptors
var kptLogits = outputs[1].AsTensor<float>(); // [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<XFeatPoint>();
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<Point2f>();
for (int i = 0; i < mask.Rows; i++)
if (mask.At<byte>(i, 0) != 0)
inlierPts.Add(dstPts[i]);
double[] c = { cx, cy, 1.0 };
double tx = H.At<double>(0, 0) * c[0] + H.At<double>(0, 1) * c[1] + H.At<double>(0, 2);
double ty = H.At<double>(1, 0) * c[0] + H.At<double>(1, 1) * c[1] + H.At<double>(1, 2);
double tz = H.At<double>(2, 0) * c[0] + H.At<double>(2, 1) * c[1] + H.At<double>(2, 2);
if (Math.Abs(tz) > 1e-10) { tx /= tz; ty /= tz; }
double angle = Math.Atan2(H.At<double>(1, 0), H.At<double>(0, 0)) * 180.0 / Math.PI;
angle = -angle; // OpenCV 坐标系 Y 向下,取反使逆时针旋转为正角度
return new LocateResult(tx, ty, angle, matches.Count, inliers, [.. inlierPts]);
}
}
}

View File

@ -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
/// </summary>
[NotMapped]
public FlowModel Flow { get; set; } = new();
[NotMapped]
public Stopwatch Sw { get; set; } = new();
/// <summary>
/// 运行All
/// </summary>
@ -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(),

View File

@ -99,9 +99,6 @@
[FlowCategory("算法")]
SIFT匹配 = 42,
[FlowCategory("算法")]
XFeat匹配 = 43,
}