增加灰度模板匹配,更改局部图像存储方式

This commit is contained in:
tfarcraw 2026-07-21 05:46:36 +08:00
parent fd943321fb
commit 859551b39b
17 changed files with 821 additions and 46 deletions

View File

@ -57,8 +57,13 @@ namespace PLCSharp.Models
/// 全局图像列表
/// </summary>
public DbSet<ImageData> ImageDatas { get; set; }
/// <summary>
/// 连接模型
/// 局部图像列表
/// </summary>
public DbSet<LocalImageData> LocalImageDatas { get; set; }
/// <summary>
/// 连接模型·
/// </summary>
public DbSet<Connect> Connects { get; set; }
/// <summary>

View File

@ -1,4 +1,4 @@

using Newtonsoft.Json;
using OpenCvSharp;
using Prism.Mvvm;
@ -67,6 +67,99 @@ namespace PLCSharp.VVMs.Vision
}
/// <summary>
/// 序列化后的图像数据
/// </summary>
[Column("Mat")]
public byte[] SerializedMat
{
get
{
byte[] imageBytes = [];
if (_Mat != null && !_Mat.Empty())
{
Cv2.ImEncode(".png", _Mat, out imageBytes);
}
return imageBytes;
}// 序列化
set
{
try
{
Mat = value != null ? Cv2.ImDecode(value, ImreadModes.Color) : new(); // 自动反序列化
}
catch (global::System.Exception)
{
Mat = new();
}
}
}
}
public class LocalImageData : BindableBase
{
/// <summary>
/// 唯一标识
/// </summary>
[Key]
public Guid ID { get; set; } = Guid.NewGuid();
/// <summary>
/// 功能标识
/// </summary>
public Guid FuncID { get; set; }
private string _Name;
/// <summary>
/// 名称
/// </summary>
public string Name
{
get { return _Name; }
set { SetProperty(ref _Name, value); }
}
private string _Comment;
/// <summary>
/// 备注
/// </summary>
public string Comment
{
get { return _Comment; }
set { SetProperty(ref _Comment, value); }
}
private string _Prompt;
/// <summary>
/// 提示
/// </summary>
[NotMapped]
public string Prompt
{
get { return _Prompt; }
set { SetProperty(ref _Prompt, value); }
}
private Mat _Mat;
/// <summary>
/// 图像矩阵
/// </summary>
[NotMapped]
[JsonIgnore]
public Mat Mat
{
get { return _Mat; }
set { SetProperty(ref _Mat, value); }
}
/// <summary>
/// 序列化后的图像数据
/// </summary>

View File

@ -101,7 +101,7 @@
HorizontalAlignment="Left" VerticalAlignment="Center"
AutoGenerateColumns="False" CanUserAddRows="False"
CanUserDeleteRows="False" CanUserSortColumns="False"
ItemsSource="{Binding SelectedVisionFunction.Params.ImageDatas}"
ItemsSource="{Binding SelectedVisionFunction.LocalImageDatas}"
ScrollViewer.VerticalScrollBarVisibility="Auto"
SelectedItem="{Binding GridSelectedLocalImageData}"
Unloaded="DataGrid_Unloaded">

View File

@ -117,7 +117,9 @@ public partial class VisionConfigViewModel
case VisionFlowType.灰度面积:
ContentRegion = new GrayArea();
break;
case VisionFlowType.灰度模板匹配:
ContentRegion = new GrayTemplateMatch();
break;
}
if (ContentRegion != null)
@ -420,6 +422,14 @@ public partial class VisionConfigViewModel
newFlow.DoubleParams["AreaMaxPercent"] = 100;
newFlow.StringParams["ResultVarName"] = "灰度面积_Result";
break;
case VisionFlowType.灰度模板匹配:
newFlow.DoubleParams["MinAngle"] = -10;
newFlow.DoubleParams["MaxAngle"] = 10;
newFlow.DoubleParams["AngleStep"] = 1;
newFlow.DoubleParams["MatchScoreMax"] = 0.9;
newFlow.StringParams["TemplateName"] = "GrayMatch_Template";
newFlow.StringParams["GrayTemplateMatch_PosVar"] = "灰度模板匹配_Pos";
break;
default:
break;
}

View File

@ -1,5 +1,4 @@
using OpenCvSharp;
using PLCSharp.Core.Tools;
using PLCSharp.Core.UserControls;
using PLCSharp.VVMs.GlobalVariables;
using PLCSharp.VVMs.Vision.VisionFlowHandler;
@ -291,7 +290,7 @@ public partial class VisionConfigViewModel
private async Task ExecuteDrawFindRectROIAsync()
{
var imageEdit = SelectedVisionFunction?.EditImageEdit;
if (imageEdit?.ImageSource == null)
{
@ -693,21 +692,218 @@ public partial class VisionConfigViewModel
private void SaveTemplateMat(Mat templateMat)
{
string templateName = SelectVisionFlow.StringParams.TryGetValue("TemplateName", out var tn)
&& !string.IsNullOrEmpty(tn) ? tn : "ORB_Template";
&& !string.IsNullOrEmpty(tn) ? tn : "Template";
var existing = SelectedVisionFunction.Params.ImageDatas
var existing = SelectedVisionFunction.LocalImageDatas
.FirstOrDefault(m => m.Name == templateName);
if (existing != null)
{
existing.Mat?.Dispose();
SelectedVisionFunction.Params.ImageDatas.Remove(existing);
existing.Mat = templateMat;
}
else
{
SelectedVisionFunction.LocalImageDatas.Add(new LocalImageData
{
FuncID = SelectedVisionFunction.ID,
Name = templateName,
Mat = templateMat
});
}
SelectedVisionFunction.Params.ImageDatas.Add(new ImageData
var localImageData = VisionsModel.
_DatasContext.
LocalImageDatas.
FirstOrDefault(m => m.Name == templateName
&& m.FuncID == SelectedVisionFunction.ID);
if (localImageData != null)
{
Name = templateName,
Mat = templateMat
});
localImageData.Mat = templateMat;
}
else
{
VisionsModel._DatasContext.Add(new LocalImageData
{
FuncID = SelectedVisionFunction.ID,
Name = templateName,
Mat = templateMat
});
}
VisionsModel._DatasContext.Save();
}
private AsyncDelegateCommand _DrawGrayTemplateMatchROI;
/// <summary>
/// 绘制灰度模板匹配模板 ROI
/// </summary>
public AsyncDelegateCommand DrawGrayTemplateMatchROI =>
_DrawGrayTemplateMatchROI ??= new AsyncDelegateCommand(ExecuteDrawGrayTemplateMatchROIAsync);
private async Task ExecuteDrawGrayTemplateMatchROIAsync()
{
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;
double templateW = 0, templateH = 0;
switch (roiShape)
{
case "矩形":
{
var roi = await imageEdit.DrawROIAsync("灰度模板匹配");
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;
templateW = roi.Width;
templateH = roi.Height;
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;
}
case "旋转矩形":
{
var roi = await imageEdit.DrawRotateRectROIAsync("灰度模板匹配");
if (roi == null) return;
SelectVisionFlow.DoubleParams["TemplateCenterX"] = roi.CenterX;
SelectVisionFlow.DoubleParams["TemplateCenterY"] = roi.CenterY;
SelectVisionFlow.DoubleParams["TemplateWidth"] = roi.RectWidth;
SelectVisionFlow.DoubleParams["TemplateHeight"] = roi.RectHeight;
SelectVisionFlow.DoubleParams["TemplateAngle"] = roi.RectAngle;
centerX = roi.CenterX;
centerY = roi.CenterY;
templateW = roi.RectWidth;
templateH = roi.RectHeight;
var srcMat = SelectedVisionFunction.Src;
if (srcMat != null && !srcMat.Empty())
{
double cx = roi.CenterX, cy = roi.CenterY;
double w = roi.RectWidth, h = roi.RectHeight;
double rad = roi.RectAngle * Math.PI / 180.0;
double cosA = Math.Cos(rad), sinA = Math.Sin(rad);
double hw = w / 2.0, hh = h / 2.0;
Point2f[] corners =
[
new((float)(cx + (-hw * cosA - (-hh) * sinA)), (float)(cy + (-hw * sinA + (-hh) * cosA))),
new((float)(cx + ( hw * cosA - (-hh) * sinA)), (float)(cy + ( hw * sinA + (-hh) * cosA))),
new((float)(cx + ( hw * cosA - hh * sinA)), (float)(cy + ( hw * sinA + hh * cosA))),
new((float)(cx + (-hw * cosA - hh * sinA)), (float)(cy + (-hw * sinA + hh * cosA))),
];
float minX = corners.Min(p => p.X), maxX = corners.Max(p => p.X);
float minY = corners.Min(p => p.Y), maxY = corners.Max(p => p.Y);
int bx = Math.Clamp((int)Math.Floor(minX), 0, srcMat.Width - 1);
int by = Math.Clamp((int)Math.Floor(minY), 0, srcMat.Height - 1);
int bw = Math.Min((int)Math.Ceiling(maxX) - bx, srcMat.Width - bx);
int bh = Math.Min((int)Math.Ceiling(maxY) - by, srcMat.Height - by);
if (bw > 0 && bh > 0)
{
SelectVisionFlow.DoubleParams["TemplateBBoxLeft"] = bx;
SelectVisionFlow.DoubleParams["TemplateBBoxTop"] = by;
SelectVisionFlow.DoubleParams["TemplateBBoxWidth"] = bw;
SelectVisionFlow.DoubleParams["TemplateBBoxHeight"] = bh;
using var cropped = srcMat[new OpenCvSharp.Rect(bx, by, bw, bh)].Clone();
using var mask = new Mat(cropped.Size(), MatType.CV_8UC1, Scalar.Black);
var rr = new RotatedRect(
new Point2f((float)(cx - bx), (float)(cy - by)),
new Size2f((float)w, (float)h),
(float)roi.RectAngle);
var rrPts = rr.Points();
Cv2.FillPoly(mask, [rrPts.Select(p => new OpenCvSharp.Point((int)p.X, (int)p.Y)).ToArray()], Scalar.White);
Mat result = Mat.Zeros(cropped.Size(), cropped.Type());
cropped.CopyTo(result, mask);
SaveTemplateMat(result);
}
}
break;
}
case "圆形":
{
var roi = await imageEdit.DrawCircleAsync("灰度模板匹配");
if (roi == null) return;
SelectVisionFlow.DoubleParams["TemplateCenterX"] = roi.CenterX;
SelectVisionFlow.DoubleParams["TemplateCenterY"] = roi.CenterY;
SelectVisionFlow.DoubleParams["TemplateRadius"] = roi.Radius;
SelectVisionFlow.DoubleParams["TemplateWidth"] = roi.Radius * 2;
SelectVisionFlow.DoubleParams["TemplateHeight"] = roi.Radius * 2;
centerX = roi.CenterX;
centerY = roi.CenterY;
templateW = roi.Radius * 2;
templateH = roi.Radius * 2;
var srcMat = SelectedVisionFunction.Src;
if (srcMat != null && !srcMat.Empty())
{
double r = roi.Radius;
int x = Math.Clamp((int)(roi.CenterX - r), 0, srcMat.Width - 1);
int y = Math.Clamp((int)(roi.CenterY - r), 0, srcMat.Height - 1);
int size = Math.Min((int)(r * 2), Math.Min(srcMat.Width - x, srcMat.Height - y));
if (size > 0)
{
using var cropped = srcMat[new OpenCvSharp.Rect(x, y, size, size)].Clone();
using var mask = new Mat(cropped.Size(), MatType.CV_8UC1, Scalar.Black);
Cv2.Circle(mask, new OpenCvSharp.Point(size / 2, size / 2), size / 2, Scalar.White, -1);
Mat result = Mat.Zeros(cropped.Size(), cropped.Type());
cropped.CopyTo(result, mask);
SaveTemplateMat(result);
}
}
imageEdit.DrawCircleVisual(roi.CenterX, roi.CenterY, roi.Radius);
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}");
}
}
private AsyncDelegateCommand _DrawBarcodeROI;

View File

@ -3,13 +3,10 @@ using OpenCvSharp.WpfExtensions;
using PLCSharp.Core.Prism;
using PLCSharp.Core.UserControls;
using PLCSharp.Models;
using PLCSharp.VVMs.GlobalVariables;
using PLCSharp.VVMs.Vision.Camera;
using Prism.Commands;
using Prism.Dialogs;
using Prism.Events;
using Prism.Ioc;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
@ -96,7 +93,7 @@ namespace PLCSharp.VVMs.Vision
SelectedVisionFunction.EditImageEdit = null;
}
/// <summary>
/// Line 类型局部变量列表(供 ComboBox 选择)
/// </summary>
@ -230,29 +227,36 @@ namespace PLCSharp.VVMs.Vision
case "New":
var baseName = "temp";
int index = 1;
while (SelectedVisionFunction.Params.ImageDatas.Where(w => w.Name == $"{baseName}{index}").Any())
while (SelectedVisionFunction.LocalImageDatas.Where(w => w.Name == $"{baseName}{index}").Any())
index++;
SelectedVisionFunction.Params.ImageDatas.Add(new ImageData { Name = $"{baseName}{index}" });
SelectedVisionFunction.LocalImageDatas.Add(
new LocalImageData
{
Name = $"{baseName}{index}",
FuncID = SelectedVisionFunction.ID
});
break;
case "Remove":
if (GridSelectedLocalImageData == null) return;
if (SelectedVisionFunction.Params.ImageDatas.Contains(GridSelectedLocalImageData))
SelectedVisionFunction.Params.ImageDatas.Remove(GridSelectedLocalImageData);
if (SelectedVisionFunction.LocalImageDatas.Contains(GridSelectedLocalImageData))
SelectedVisionFunction.LocalImageDatas.Remove(GridSelectedLocalImageData);
break;
case "Show":
if (GridSelectedLocalImageData.Mat != null && GridSelectedLocalImageData.Mat.Empty() == false)
ShowMat = GridSelectedLocalImageData.Mat;
if (GridSelectedLocalImageData == null) return;
if (GridSelectedLocalImageData.Mat == null) return;
if (GridSelectedLocalImageData.Mat.Empty()) return;
ShowMat = GridSelectedLocalImageData.Mat;
break;
}
}
private ImageData _GridSelectedLocalImageData;
private LocalImageData _GridSelectedLocalImageData;
/// <summary>
/// 在表格中选择的局部图像
/// </summary>
public ImageData GridSelectedLocalImageData
public LocalImageData GridSelectedLocalImageData
{
get { return _GridSelectedLocalImageData; }
set { SetProperty(ref _GridSelectedLocalImageData, value); }
@ -315,6 +319,6 @@ namespace PLCSharp.VVMs.Vision
}
#endregion
}
}

View File

@ -19,7 +19,7 @@
{
if (item.StringParams.TryGetValue("Image", out string imageName))
{
var theMat = func.Params.ImageDatas.Where(w => w.Name == imageName).FirstOrDefault();
var theMat = func.LocalImageDatas.Where(w => w.Name == imageName).FirstOrDefault();
if (theMat != null)
{
func.Src = theMat.Mat.Clone();

View File

@ -10,7 +10,7 @@
d:DesignHeight="100" d:DesignWidth="300">
<StackPanel>
<Label Content="局部图像名称" />
<ComboBox IsEditable="False" ItemsSource="{Binding SelectedVisionFunction.Params.ImageDatas}" SelectedItem="{Binding SelectedLocalImageData}" DisplayMemberPath="Name" />
<ComboBox IsEditable="False" ItemsSource="{Binding SelectedVisionFunction.LocalImageDatas}" SelectedItem="{Binding SelectedLocalImageData}" DisplayMemberPath="Name" />
<TextBlock Text="{Binding Path=SelectVisionFlow.StringParams[Image]}" />
</StackPanel>

View File

@ -19,9 +19,9 @@
{
if (item.StringParams.TryGetValue("Image", out string imageName))
{
if (func.Params.ImageDatas.Where(w => w.Name == imageName).Any())
if (func.LocalImageDatas.Where(w => w.Name == imageName).Any())
{
func.Params.ImageDatas.Where(w => w.Name == imageName).FirstOrDefault().Mat = func.Src.Clone();
func.LocalImageDatas.Where(w => w.Name == imageName).FirstOrDefault().Mat = func.Src.Clone();
item.Flow.Done = true;
return true;
}

View File

@ -0,0 +1,155 @@
<UserControl x:Class="PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm.GrayTemplateMatch"
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="550" 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 DrawGrayTemplateMatchROI}" 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=GrayMatch_Template}" />
</Grid>
</StackPanel>
</GroupBox>
<!-- ========== 参数 ========== -->
<GroupBox Header="参数">
<StackPanel>
<Grid Margin="5">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
<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.DoubleParams[MinAngle], Mode=TwoWay, TargetNullValue=-10, UpdateSourceTrigger=LostFocus}" />
<TextBlock Grid.Row="1" Text="最大角度" VerticalAlignment="Center" ToolTip="角度搜索终止值(度)" />
<TextBox Grid.Row="1" Grid.Column="1" Text="{Binding SelectVisionFlow.DoubleParams[MaxAngle], Mode=TwoWay, TargetNullValue=10, UpdateSourceTrigger=LostFocus}" />
<TextBlock Grid.Row="2" Text="角度步长" VerticalAlignment="Center" ToolTip="生成模板的角度步长(度)。越小精度越高但预处理越慢" />
<TextBox Grid.Row="2" Grid.Column="1" Text="{Binding SelectVisionFlow.DoubleParams[AngleStep], Mode=TwoWay, TargetNullValue=1, UpdateSourceTrigger=LostFocus}" />
<TextBlock Grid.Row="3" Text="分数下限" VerticalAlignment="Center" ToolTip="CCorrNormed 分数下限(-1~1)。越高匹配越好,低于此值则拒绝" />
<TextBox Grid.Row="3" Grid.Column="1" Text="{Binding SelectVisionFlow.DoubleParams[MatchScoreMax], Mode=TwoWay, TargetNullValue=0.5, UpdateSourceTrigger=LostFocus}" />
</Grid>
</StackPanel>
</GroupBox>
<!-- ========== 变量设置 ========== -->
<GroupBox Header="变量设置">
<Grid Margin="5">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="80" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<TextBlock Text="位置变量" VerticalAlignment="Center" ToolTip="匹配到的位置 (X,Y,角度) 写入此 Pos 变量" />
<TextBox Grid.Column="1" Text="{Binding SelectVisionFlow.StringParams[GrayTemplateMatch_PosVar], Mode=TwoWay, TargetNullValue=灰度模板匹配_Pos}" />
</Grid>
</GroupBox>
<!-- ========== 匹配结果 ========== -->
<GroupBox Header="匹配结果">
<Grid Margin="5">
<Grid.RowDefinitions>
<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[GrayMatch_MatchX], 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[GrayMatch_MatchY], Mode=OneWay}"
IsReadOnly="True" Background="#FFF0F0F0" />
<TextBlock Grid.Row="2" Margin="5,0" Text="偏移 X" VerticalAlignment="Center" />
<TextBox Grid.Row="2" Grid.Column="1"
Text="{Binding SelectedVisionFunction.Params.ResultDoubles[GrayMatch_OffsetX], Mode=OneWay}"
IsReadOnly="True" Background="#FFF0F0F0" />
<TextBlock Grid.Row="2" Grid.Column="2" Margin="5,0" Text="偏移 Y" VerticalAlignment="Center" />
<TextBox Grid.Row="2" Grid.Column="3"
Text="{Binding SelectedVisionFunction.Params.ResultDoubles[GrayMatch_OffsetY], Mode=OneWay}"
IsReadOnly="True" Background="#FFF0F0F0" />
<TextBlock Grid.Row="3" Margin="5,0" Text="相似度" VerticalAlignment="Center" ToolTip="CCorrNormed 分数(-1~1),越高匹配越好" />
<TextBox Grid.Row="3" Grid.Column="1"
Text="{Binding SelectedVisionFunction.Params.ResultDoubles[GrayMatch_Score], Mode=OneWay}"
IsReadOnly="True" Background="#FFF0F0F0" />
<TextBlock Grid.Row="3" Grid.Column="2" Margin="5,0" Text="角度" VerticalAlignment="Center" />
<TextBox Grid.Row="3" Grid.Column="3"
Text="{Binding SelectedVisionFunction.Params.ResultDoubles[GrayMatch_Angle], Mode=OneWay}"
IsReadOnly="True" Background="#FFF0F0F0" />
<TextBlock Grid.Row="4" Grid.ColumnSpan="2" Margin="5,0" Text="模板数量" VerticalAlignment="Center" ToolTip="本次生成的有效模板总数" />
<TextBox Grid.Row="4" Grid.Column="2" Grid.ColumnSpan="2"
Text="{Binding SelectedVisionFunction.Params.ResultDoubles[GrayMatch_Count], Mode=OneWay}"
IsReadOnly="True" Background="#FFF0F0F0" />
</Grid>
</GroupBox>
</StackPanel>
</ScrollViewer>
</UserControl>

View File

@ -0,0 +1,18 @@
using System.Windows.Controls;
namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
{
/// <summary>
/// 灰度模板匹配参数配置控件
/// </summary>
public partial class GrayTemplateMatch : UserControl
{
/// <summary>
/// 灰度模板匹配
/// </summary>
public GrayTemplateMatch()
{
InitializeComponent();
}
}
}

View File

@ -0,0 +1,284 @@
using OpenCvSharp;
using System.Windows.Media;
namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
{
/// <summary>
/// 灰度模板匹配 Handler —— 灰度模板旋转 + CCorrNormed 匹配。
/// 预生成多角度灰度模板(BBox裁剪),在源图上做归一化互相关匹配。
/// </summary>
public class GrayTemplateMatchHandler : IVisionFlowHandler
{
public VisionFlowType Type => VisionFlowType.灰度模板匹配;
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))
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}");
}
double minAngle = item.DoubleParams.TryGetValue("MinAngle", out double minA) ? minA : 0;
double maxAngle = item.DoubleParams.TryGetValue("MaxAngle", out double maxA) ? maxA : 360;
double angleStep = item.DoubleParams.TryGetValue("AngleStep", out double aStep) ? Math.Max(aStep, 0.1) : 5;
// CCorrNormed: 分数越高越好,阈值是最低分
double scoreMin = item.DoubleParams.TryGetValue("MatchScoreMax", out double msm) ? msm : 0.3;
string templateName = item.StringParams.TryGetValue("TemplateName", out var tn)
&& !string.IsNullOrEmpty(tn) ? tn : "GrayMatch_Template";
string posVarName = item.StringParams.TryGetValue("GrayTemplateMatch_PosVar", out var pn)
&& !string.IsNullOrEmpty(pn) ? pn : "灰度模板匹配_Pos";
// ===== 资源 =====
Mat graySrc = null;
Mat grayTemplate = null;
Mat templateRoi = null;
Mat bestResult = null;
int totalTemplates = 0;
try
{
// ===== 2. 加载模板 =====
var tmpl = func.LocalImageDatas.FirstOrDefault(m => m.Name == templateName);
if (tmpl?.Mat == null || tmpl.Mat.Empty())
throw new Exception("模板提取失败,请先画选区截取模板!");
templateRoi = tmpl.Mat.Clone();
// ===== 3. 灰度化 =====
graySrc = ToGray(src);
grayTemplate = ToGray(templateRoi);
if (grayTemplate.Width < 16 || grayTemplate.Height < 16)
throw new Exception($"模板太小({grayTemplate.Width}x{grayTemplate.Height}),请画大一些的选区!");
// ===== 4. 搜索区域 =====
double range = Math.Max(templateW, templateH) * 2.0;
int rgnX = Math.Max(0, (int)(centerX - range / 2));
int rgnY = Math.Max(0, (int)(centerY - range / 2));
int rgnW = Math.Min((int)range, graySrc.Width - rgnX);
int rgnH = Math.Min((int)range, graySrc.Height - rgnY);
using Mat searchRegion = graySrc[new OpenCvSharp.Rect(rgnX, rgnY, rgnW, rgnH)].Clone();
int offX = rgnX, offY = rgnY;
// ===== 5-6. 角度搜索(粗搜 + 可选精搜) =====
double bestScore, bestAngle;
int bestX, bestY, etW, etH;
MatchAngle(grayTemplate, searchRegion, offX, offY,
minAngle, maxAngle, angleStep, scoreMin,
out bestScore, out bestAngle, out bestX, out bestY, out etW, out etH, out bestResult, ref totalTemplates);
if (bestScore < scoreMin)
throw new Exception($"未找到可靠匹配(最佳分数 {bestScore:F3} < 阈值 {scoreMin})!");
// GetRotationMatrix2D 正角度 = OpenCV 顺时针 → 取反统一为视觉方向
bestAngle = -bestAngle;
// ===== 7. ECC 精调(亚像素位置 + 亚角度) =====
double matchX = bestX + etW / 2.0;
double matchY = bestY + etH / 2.0;
// ECC 需要原始灰度模板(不旋转),searchRegion 已在灰度的灰度源图上
double tplCX = grayTemplate.Width / 2.0, tplCY = grayTemplate.Height / 2.0;
double eccCos = Math.Cos(bestAngle * Math.PI / 180.0);
double eccSin = Math.Sin(bestAngle * Math.PI / 180.0);
// 匹配中心在 searchRegion 中的坐标
double matchXroi = matchX - offX;
double matchYroi = matchY - offY;
using Mat eccWarp = new Mat(2, 3, MatType.CV_32FC1);
eccWarp.Set<float>(0, 0, (float)eccCos);
eccWarp.Set<float>(0, 1, (float)-eccSin);
eccWarp.Set<float>(0, 2, (float)(matchXroi - eccCos * tplCX + eccSin * tplCY));
eccWarp.Set<float>(1, 0, (float)eccSin);
eccWarp.Set<float>(1, 1, (float)eccCos);
eccWarp.Set<float>(1, 2, (float)(matchYroi - eccSin * tplCX - eccCos * tplCY));
try
{
var io = InputOutputArray.Create(eccWarp);
Cv2.FindTransformECC(grayTemplate, searchRegion, io, MotionTypes.Euclidean,
new TermCriteria(CriteriaTypes.Eps | CriteriaTypes.Count, 200, 1e-3));
eccCos = eccWarp.At<float>(0, 0); eccSin = eccWarp.At<float>(1, 0);
double eccTx = eccWarp.At<float>(0, 2), eccTy = eccWarp.At<float>(1, 2);
matchX = eccCos * tplCX - eccSin * tplCY + eccTx + offX;
matchY = eccSin * tplCX + eccCos * tplCY + eccTy + offY;
bestAngle = Math.Atan2(eccSin, eccCos) * 180.0 / Math.PI;
etW = grayTemplate.Width; etH = grayTemplate.Height;
}
catch
{
// ECC 失败,保留粗搜结果
}
// ===== 9. 边界检查 =====
double hw = etW / 2.0, hh = etH / 2.0;
double ow = Math.Min(matchX + hw, graySrc.Width) - Math.Max(matchX - hw, 0);
double oh = Math.Min(matchY + hh, graySrc.Height) - Math.Max(matchY - hh, 0);
if (ow < hw || oh < hh)
throw new Exception($"匹配结果超出图像边界!");
// ===== 9. 偏移量 =====
double offsetX = matchX - centerX;
double offsetY = matchY - centerY;
// ===== 10. 存储结果 =====
func.Params.ResultDoubles["GrayMatch_MatchX"] = Math.Round(matchX, 2);
func.Params.ResultDoubles["GrayMatch_MatchY"] = Math.Round(matchY, 2);
func.Params.ResultDoubles["GrayMatch_Angle"] = Math.Round(bestAngle, 1);
func.Params.ResultDoubles["GrayMatch_Score"] = Math.Round(bestScore, 4);
func.Params.ResultDoubles["GrayMatch_Count"] = totalTemplates;
func.Params.ResultDoubles["GrayMatch_OffsetX"] = Math.Round(offsetX, 2);
func.Params.ResultDoubles["GrayMatch_OffsetY"] = Math.Round(offsetY, 2);
// ===== 11. 局部变量(位置 + 偏移) =====
var pv = func.Params.Variables.FirstOrDefault(v => v.Name == posVarName);
if (pv == null)
{
pv = new LocalVariableItem(posVarName, "Pos", new Pos());
System.Windows.Application.Current.Dispatcher.Invoke(() => func.Params.Variables.Add(pv));
}
pv.RawValue = new Pos(Math.Round(matchX, 2), Math.Round(matchY, 2), 0, Math.Round(bestAngle, 2));
string offVarName = posVarName + "_Offset";
var ov = func.Params.Variables.FirstOrDefault(v => v.Name == offVarName);
if (ov == null)
{
ov = new LocalVariableItem(offVarName, "Pos", new Pos());
System.Windows.Application.Current.Dispatcher.Invoke(() => func.Params.Variables.Add(ov));
}
ov.RawValue = new Pos(Math.Round(offsetX, 2), Math.Round(offsetY, 2), 0, 0);
// ===== 12. 可视化 =====
var magenta = Colors.Magenta;
var lime = Colors.Lime;
double rad = bestAngle * 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, magenta, 3));
func.DrawCommands.Add(DrawCommand.Line(matchX - 15, matchY, matchX + 15, matchY, magenta, 2));
func.DrawCommands.Add(DrawCommand.Line(matchX, matchY - 15, matchX, matchY + 15, magenta, 2));
func.DrawCommands.Add(DrawCommand.TextBlock(10, 60,
$"x:{matchX:F1} y:{matchY:F1} a:{bestAngle:F1}° s:{bestScore:F4}", lime, 18));
func.DrawCommands.Add(DrawCommand.TextBlock(10, 84,
$"offset: ({offsetX:+0.0;-0.0}, {offsetY:+0.0;-0.0})", lime, 14));
func.DrawCommands.Add(DrawCommand.TextBlock(10, 104,
$"[灰度模板匹配] {totalTemplates} templates", lime, 14));
_ = func.RenderDrawAsync();
item.Flow.Done = true;
return true;
}
finally
{
graySrc?.Dispose();
grayTemplate?.Dispose();
templateRoi?.Dispose();
bestResult?.Dispose();
}
}
private static void MatchAngle(Mat grayTemplate, Mat searchRegion, int offX, int offY,
double minAngle, double maxAngle, double step, double scoreMin,
out double bestScore, out double bestAngle, out int bestX, out int bestY,
out int etW, out int etH, out Mat bestResult, ref int totalCount)
{
bestScore = double.MinValue; bestAngle = 0; bestX = 0; bestY = 0;
etW = 0; etH = 0; bestResult = null;
int numAngles = Math.Max(1, (int)((maxAngle - minAngle) / step) + 1);
Point2f tmc = new(grayTemplate.Width / 2f, grayTemplate.Height / 2f);
for (int i = 0; i < numAngles; i++)
{
double ang = minAngle + i * step;
using var rm = Cv2.GetRotationMatrix2D(tmc, ang, 1.0);
double ca = Math.Abs(rm.At<double>(0, 0));
double sa = Math.Abs(rm.At<double>(0, 1));
int nw = (int)(grayTemplate.Height * sa + grayTemplate.Width * ca);
int nh = (int)(grayTemplate.Height * ca + grayTemplate.Width * sa);
rm.Set(0, 2, rm.At<double>(0, 2) + nw / 2.0 - tmc.X);
rm.Set(1, 2, rm.At<double>(1, 2) + nh / 2.0 - tmc.Y);
using Mat rot = new Mat();
Cv2.WarpAffine(grayTemplate, rot, rm, new Size(nw, nh),
InterpolationFlags.Linear, BorderTypes.Constant, Scalar.Black);
using Mat maskB = new Mat();
Cv2.Threshold(rot, maskB, 1, 255, ThresholdTypes.Binary);
OpenCvSharp.Rect bbox = Cv2.BoundingRect(maskB);
if (bbox.Width < 16 || bbox.Height < 16) continue;
using Mat tpl = rot[bbox].Clone();
totalCount++;
int rw = searchRegion.Width - tpl.Width + 1;
int rh = searchRegion.Height - tpl.Height + 1;
using Mat res = new Mat(rh, rw, MatType.CV_32FC1);
Cv2.MatchTemplate(searchRegion, tpl, res, TemplateMatchModes.CCorrNormed);
Cv2.MinMaxLoc(res, out _, out double mv, out _, out Point ml);
if (mv > bestScore)
{
bestScore = mv;
bestAngle = ang;
bestX = ml.X + offX;
bestY = ml.Y + offY;
etW = tpl.Width; etH = tpl.Height;
bestResult?.Dispose();
bestResult = res.Clone();
}
}
if (bestResult == null)
throw new Exception("所有角度的模板生成均失败!请检查模板图像。");
}
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;
}
}
}

View File

@ -84,7 +84,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
{
// ---------- 1. 提取或缓存模板 ----------
template = Mat.Zeros((int)height, (int)width, MatType.CV_8UC3);
var existing = func.Params.ImageDatas.FirstOrDefault(m => m.Name == templateName);
var existing = func.LocalImageDatas.FirstOrDefault(m => m.Name == templateName);
if (existing?.Mat != null && !existing.Mat.Empty())
{
if (roiShape == "旋转矩形")

View File

@ -22,7 +22,7 @@
</Grid.ColumnDefinitions>
<TextBlock Text="角度" VerticalAlignment="Center" ToolTip="旋转角度(度),正数逆时针,负数顺时针" />
<TextBox Grid.Column="1" Text="{Binding SelectVisionFlow.DoubleParams[RotateAngle], TargetNullValue=0, UpdateSourceTrigger=PropertyChanged}" />
<TextBox Grid.Column="1" Text="{Binding SelectVisionFlow.DoubleParams[RotateAngle], TargetNullValue=0, UpdateSourceTrigger=LostFocus}" />
<TextBlock Grid.Row="1" Text="尺寸模式" VerticalAlignment="Center" />
<ComboBox Grid.Row="1" Grid.Column="1" SelectedIndex="{Binding SelectVisionFlow.IntParams[ResizeMode], Mode=TwoWay}">

View File

@ -159,12 +159,21 @@ namespace PLCSharp.VVMs.Vision
_Src = value;
old?.Dispose(); // 释放旧 Mat 的非托管资源
}
}
}
private ObservableCollection<LocalImageData> _LocalImageDatas = [];
/// <summary>
/// 图像集合
/// </summary>
[NotMapped]
public ObservableCollection<LocalImageData> LocalImageDatas
{
get { return _LocalImageDatas; }
set { SetProperty(ref _LocalImageDatas, value); }
}
private VisionParams _Params = new();
// VisionFunction 中添加辅助方法
@ -328,6 +337,7 @@ namespace PLCSharp.VVMs.Vision
[VisionFlowType.拍照] = new GetFromCameraHandler(),
[VisionFlowType.卡尺寻边] = new CaliperFindEdgeHandler(),
[VisionFlowType.ORB匹配] = new ORBMatchHandler(),
[VisionFlowType.灰度模板匹配] = new GrayTemplateMatchHandler(),
[VisionFlowType.卡尺找圆] = new CaliperFindCircleHandler(),
[VisionFlowType.卡尺找旋转矩形] = new CaliperFindRectHandler(),
[VisionFlowType.清除绘制] = new ClearDrawHandler(),
@ -519,17 +529,7 @@ namespace PLCSharp.VVMs.Vision
/// </summary>
public class VisionParams : BindableBase
{
private ObservableCollection<ImageData> _Mats = [];
/// <summary>
/// 图像集合
/// </summary>
public ObservableCollection<ImageData> ImageDatas
{
get { return _Mats; }
set { SetProperty(ref _Mats, value); }
}
private ObservableDictionary<string, double> _ResultDoubles = [];
/// <summary>
/// 通用数值结果(如 ORB 匹配输出的 X/Y/角度偏移)

View File

@ -78,6 +78,9 @@
灰度面积 = 38,
[FlowCategory("算法")]
微信解码 = 39,
[FlowCategory("算法")]
灰度模板匹配 = 40,
}

View File

@ -93,6 +93,13 @@ namespace PLCSharp.VVMs.Vision
itemcopy.VisionsModel = this;
itemcopy.ImageDatas = ImageDatas;
itemcopy.GlobalModel = GlobalModel;
var localImageDatas = _DatasContext.LocalImageDatas.Where(c => c.FuncID == item.ID);
foreach (var l in localImageDatas)
{
itemcopy.LocalImageDatas.Add(l);
}
VisionFunctions.Add(itemcopy);
}