siftMatch
This commit is contained in:
parent
ccaf5415b4
commit
87c6960e9b
@ -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;
|
||||
|
||||
@ -686,6 +686,75 @@ public partial class VisionConfigViewModel
|
||||
}
|
||||
}
|
||||
|
||||
private AsyncDelegateCommand _DrawSiftMatchROI;
|
||||
/// <summary>
|
||||
/// 绘制 SIFT 匹配模板 ROI
|
||||
/// </summary>
|
||||
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}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 保存模板 Mat 到 Params(替换同名旧模板)
|
||||
/// </summary>
|
||||
|
||||
@ -0,0 +1,156 @@
|
||||
<UserControl x:Class="PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm.SiftMatch"
|
||||
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:local="clr-namespace:PLCSharp.VVMs.Vision.VisionFlowHandler"
|
||||
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 DrawSiftMatchROI}" 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.Row="0" Grid.Column="2" Margin="5,0" Text="Top" VerticalAlignment="Center" />
|
||||
<TextBox Grid.Row="0" 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=SIFT_Template}" />
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
</GroupBox>
|
||||
|
||||
<GroupBox Header="SIFT 参数">
|
||||
<Grid Margin="5">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition />
|
||||
<RowDefinition />
|
||||
<RowDefinition />
|
||||
</Grid.RowDefinitions>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="80" />
|
||||
<ColumnDefinition />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="特征点数量" VerticalAlignment="Center" ToolTip="提取的特征点越多越精确,但速度越慢" />
|
||||
<TextBox Grid.Column="1" Text="{Binding SelectVisionFlow.IntParams[NFeatures], Mode=TwoWay, TargetNullValue=1000, UpdateSourceTrigger=LostFocus}" />
|
||||
|
||||
<TextBlock Grid.Row="1" Text="最小匹配数" VerticalAlignment="Center" ToolTip="最少需要的优质匹配点数" />
|
||||
<TextBox Grid.Row="1" Grid.Column="1" Text="{Binding SelectVisionFlow.IntParams[MinMatches], Mode=TwoWay, TargetNullValue=8, UpdateSourceTrigger=LostFocus}" />
|
||||
|
||||
<TextBlock Grid.Row="2" Text="优质匹配比例" VerticalAlignment="Center" ToolTip="匹配距离 < 最小距离×此系数的视为优质匹配" />
|
||||
<TextBox Grid.Row="2" Grid.Column="1" Text="{Binding SelectVisionFlow.DoubleParams[MinGoodRatio], Mode=TwoWay, TargetNullValue=0.3, UpdateSourceTrigger=LostFocus}" />
|
||||
</Grid>
|
||||
</GroupBox>
|
||||
|
||||
<GroupBox Header="变量设置">
|
||||
<Grid Margin="5">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition />
|
||||
<RowDefinition />
|
||||
</Grid.RowDefinitions>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="80" />
|
||||
<ColumnDefinition />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Grid.Row="0" Text="绝对位置变量" VerticalAlignment="Center" ToolTip="匹配到的绝对位置写入此 Pos 变量" />
|
||||
<TextBox Grid.Row="0" Grid.Column="1" Text="{Binding SelectVisionFlow.StringParams[SiftMatch_PosVar], Mode=TwoWay, TargetNullValue=SIFT匹配_Pos}" />
|
||||
|
||||
<TextBlock Grid.Row="1" Text="相对位移变量" VerticalAlignment="Center" ToolTip="相对位移写入此 Pos 变量" />
|
||||
<TextBox Grid.Row="1" Grid.Column="1" Text="{Binding SelectVisionFlow.StringParams[SiftMatch_OffsetVar], Mode=TwoWay, TargetNullValue=SIFT匹配_Offset}" />
|
||||
</Grid>
|
||||
</GroupBox>
|
||||
|
||||
<GroupBox Header="匹配结果">
|
||||
<Grid Margin="5">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition />
|
||||
<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[SiftMatch_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[SiftMatch_OffsetY], Mode=OneWay}"
|
||||
IsReadOnly="True" Background="#FFF0F0F0" />
|
||||
|
||||
<TextBlock Grid.Row="5" Margin="5,0" Text="角度偏移" VerticalAlignment="Center" />
|
||||
<TextBox Grid.Row="5" Grid.Column="1"
|
||||
Text="{Binding SelectedVisionFunction.Params.ResultDoubles[SiftMatch_Angle], Mode=OneWay}"
|
||||
IsReadOnly="True" Background="#FFF0F0F0" />
|
||||
|
||||
<TextBlock Grid.Row="6" Grid.ColumnSpan="2" Margin="5,0" Text="匹配点数" VerticalAlignment="Center" />
|
||||
<TextBox Grid.Row="6" Grid.Column="2" Grid.ColumnSpan="2"
|
||||
Text="{Binding SelectedVisionFunction.Params.ResultDoubles[SiftMatch_MatchCount], Mode=OneWay}"
|
||||
IsReadOnly="True" Background="#FFF0F0F0" />
|
||||
</Grid>
|
||||
</GroupBox>
|
||||
</StackPanel>
|
||||
</ScrollViewer>
|
||||
</UserControl>
|
||||
@ -0,0 +1,12 @@
|
||||
using System.Windows.Controls;
|
||||
|
||||
namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
|
||||
{
|
||||
public partial class SiftMatch : UserControl
|
||||
{
|
||||
public SiftMatch()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,256 @@
|
||||
using OpenCvSharp;
|
||||
|
||||
namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
|
||||
{
|
||||
/// <summary>
|
||||
/// SIFT + FLANN + Homography 特征匹配定位。
|
||||
/// 对纹理丰富的物体鲁棒,天然支持旋转和尺度变化。
|
||||
/// </summary>
|
||||
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<double>(0, 0), h01 = H.At<double>(0, 1), h02 = H.At<double>(0, 2);
|
||||
double h10 = H.At<double>(1, 0), h11 = H.At<double>(1, 1), h12 = H.At<double>(1, 2);
|
||||
double h20 = H.At<double>(2, 0), h21 = H.At<double>(2, 1), h22 = H.At<double>(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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -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(),
|
||||
|
||||
@ -84,6 +84,9 @@
|
||||
|
||||
[FlowCategory("算法")]
|
||||
点到点距离 = 41,
|
||||
|
||||
[FlowCategory("算法")]
|
||||
SIFT匹配 = 42,
|
||||
}
|
||||
|
||||
|
||||
|
||||
Loading…
Reference in New Issue
Block a user