图像校正

This commit is contained in:
tfarcraw 2026-07-23 02:28:19 +08:00
parent 97d75b9139
commit 27e3ee67df
22 changed files with 318 additions and 56 deletions

View File

@ -43,7 +43,7 @@
/// <summary>
/// 失败原因(非空表示异常结束)
/// </summary>
public string? ErrorState { get; set; }
public string? FailMessage { get; set; }
/// <summary>
/// 单个步骤超时时间(秒),默认 5 秒
/// </summary>
@ -64,7 +64,7 @@
{
Done = false;
IsSuccess = false;
ErrorState = null;
FailMessage = null;
Step = 0;
StepTime = DateTime.Now;
FlowStarTime = DateTime.Now;

View File

@ -10,4 +10,4 @@ using System.Diagnostics.CodeAnalysis;
[assembly: SuppressMessage("Style", "IDE0305:简化集合初始化")]
[assembly: SuppressMessage("Usage", "VSTHRD003:Avoid awaiting foreign Tasks")]
[assembly: SuppressMessage("Usage", "VSTHRD001:Avoid legacy thread switching APIs")]
[assembly: SuppressMessage("Usage", "VSTHRD002:Avoid problematic synchronous waits")]

View File

@ -50,6 +50,9 @@ public partial class VisionConfigViewModel
case VisionFlowType.图像相减:
ContentRegion = new ImageFromLocal();
break;
case VisionFlowType.图像校正:
ContentRegion = new ImageWarp();
break;
case VisionFlowType.从局部图像获取图片:
case VisionFlowType.存到局部图像:
ContentRegion = new ImageFromLocal();
@ -133,6 +136,9 @@ public partial class VisionConfigViewModel
case VisionFlowType.XFeat匹配:
ContentRegion = new XFeatMatch();
break;
case VisionFlowType.矩阵生成:
ContentRegion = new MatrixGen();
break;
case VisionFlowType.点到点距离:
ContentRegion = new PointToPointDistance();
break;
@ -416,7 +422,10 @@ public partial class VisionConfigViewModel
newFlow.IntParams["TileSize"] = 8;
break;
case VisionFlowType.图像相减:
break;
case VisionFlowType.图像校正:
newFlow.StringParams["MatrixVar"] = "SIFT匹配_矩阵";
break;
case VisionFlowType.ROI解码:
newFlow.IntParams["DecodeType"] = 0;
@ -476,6 +485,12 @@ public partial class VisionConfigViewModel
newFlow.StringParams["XFeatMatch_PosVar"] = "XFeat匹配_Pos";
newFlow.StringParams["XFeatMatch_OffsetVar"] = "XFeat匹配_Offset";
break;
case VisionFlowType.矩阵生成:
newFlow.DoubleParams["MoveX"] = 0;
newFlow.DoubleParams["MoveY"] = 0;
newFlow.DoubleParams["Angle"] = 0;
newFlow.StringParams["MatrixVar"] = "生成矩阵";
break;
case VisionFlowType.点到点距离:
newFlow.StringParams["ResultVar"] = "点到点距离";
break;

View File

@ -11,6 +11,6 @@
<StackPanel>
<TextBlock Text="{Binding Path=SelectVisionFlow.StringParams[Path]}" TextWrapping="Wrap" />
<Button Command="{Binding ImageFile}" CommandParameter="Save" Content="选择文件夹" />
<CheckBox Content="以日期为文件夹" IsChecked="{Binding Path=SelectVisionFlow.StringParams[DateTimePath]}" />
<CheckBox Content="以日期为文件夹" IsChecked="{Binding Path=SelectVisionFlow.BoolParams[DateTimePath]}" />
</StackPanel>
</UserControl>

View File

@ -1,4 +1,6 @@
using OpenCvSharp;
using Microsoft.VisualBasic;
using OpenCvSharp;
using System.IO;
namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Access
{
@ -23,9 +25,27 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Access
{
try
{
Cv2.ImWrite(filePath, func.Src);
item.Flow.Done = true;
return true;
if (item.BoolParams.TryGetValue("DateTimePath", out bool useDateTime)) {
if (useDateTime) {
filePath += DateTime.Now.ToString("yyyy_MM_dd");
filePath += "\\";
}
}
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
var fileName = filePath + DateTime.Now.ToString("yyyy_MM_dd HH_mm_ss_ff") + ".png";
if (Cv2.ImWrite(fileName, func.Src))
{
return true;
}
else {
throw new Exception($"保存图像失败");
}
}
catch (Exception ex)
{

View File

@ -23,7 +23,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
if (!item.DoubleParams.TryGetValue("CircleCenterX", out double cx) ||
!item.DoubleParams.TryGetValue("CircleCenterY", out double cy) ||
!item.DoubleParams.TryGetValue("CircleRadius", out double radius))
{ item.Flow.ErrorState = "圆形ROI未配置,请先画圆!"; return false; }
{ item.Flow.FailMessage = "圆形ROI未配置,请先画圆!"; return false; }
// 读取卡尺参数
var threshold = item.IntParams.TryGetValue("Threshold", out int t) ? Math.Max(t, 1) : 30;
@ -181,7 +181,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
_ = func.RenderDrawAsync();
if (edgePoints.Count < 3)
{
item.Flow.ErrorState = $"仅找到 {edgePoints.Count} 个边缘点,至少需要3个!";
item.Flow.FailMessage = $"仅找到 {edgePoints.Count} 个边缘点,至少需要3个!";
return false;
}
@ -197,7 +197,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
if (ransacInliers < minInliers)
{
item.Flow.ErrorState = $"内点数不足 ({ransacInliers} < {minInliers}),请调整 RANSAC 阈值!";
item.Flow.FailMessage = $"内点数不足 ({ransacInliers} < {minInliers}),请调整 RANSAC 阈值!";
return false;
};

View File

@ -14,7 +14,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
!item.DoubleParams.TryGetValue("LineStartY", out double sy) ||
!item.DoubleParams.TryGetValue("LineEndX", out double ex) ||
!item.DoubleParams.TryGetValue("LineEndY", out double ey))
{ item.Flow.ErrorState = "卡尺线未配置,请先画线!"; return false; }
{ item.Flow.FailMessage = "卡尺线未配置,请先画线!"; return false; }
var threshold = item.IntParams.TryGetValue("Threshold", out int t) ? Math.Max(t, 1) : 30;
var numCalipers = item.IntParams.TryGetValue("NumCalipers", out int nc) ? Math.Max(nc, 1) : 50;
@ -31,7 +31,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
double lineDx = ex - sx, lineDy = ey - sy;
double lineLen = Math.Sqrt(lineDx * lineDx + lineDy * lineDy);
if (lineLen < 1) { item.Flow.ErrorState = "直线太短!"; return false; }
if (lineLen < 1) { item.Flow.FailMessage = "直线太短!"; return false; }
double ux = lineDx / lineLen, uy = lineDy / lineLen;
double pdx = -uy, pdy = ux;
double halfLen = caliperLength / 2.0;
@ -88,7 +88,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
if (edgePoints.Count < 2)
{
item.Flow.ErrorState = $"仅找到 {edgePoints.Count} 个边缘点,至少需要2个!";
item.Flow.FailMessage = $"仅找到 {edgePoints.Count} 个边缘点,至少需要2个!";
return false;
}

View File

@ -73,7 +73,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
var tmpl = func.LocalImageDatas.FirstOrDefault(m => m.Name == templateName);
if (tmpl?.Mat == null || tmpl.Mat.Empty())
{
item.Flow.ErrorState = "模板提取失败,请先画选区截取模板!";
item.Flow.FailMessage = "模板提取失败,请先画选区截取模板!";
return false;
}
templateRoi = tmpl.Mat.Clone();
@ -102,7 +102,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
if (bestScore < scoreMin)
{
item.Flow.ErrorState = $"未找到可靠匹配(最佳分数 {bestScore:F3} < 阈值 {scoreMin})";
item.Flow.FailMessage = $"未找到可靠匹配(最佳分数 {bestScore:F3} < 阈值 {scoreMin})";
return false;
}

View File

@ -0,0 +1,45 @@
<UserControl x:Class="PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm.MatrixGen"
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="200" d:DesignWidth="300">
<ScrollViewer VerticalScrollBarVisibility="Auto">
<StackPanel>
<GroupBox Header="变换参数">
<Grid Margin="5">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="60" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<TextBlock Text="X 平移" VerticalAlignment="Center" />
<TextBox Grid.Column="1" Text="{Binding SelectVisionFlow.DoubleParams[MoveX], Mode=TwoWay, TargetNullValue=0, UpdateSourceTrigger=LostFocus}" />
<TextBlock Grid.Row="1" Text="Y 平移" VerticalAlignment="Center" />
<TextBox Grid.Row="1" Grid.Column="1" Text="{Binding SelectVisionFlow.DoubleParams[MoveY], Mode=TwoWay, TargetNullValue=0, UpdateSourceTrigger=LostFocus}" />
<TextBlock Grid.Row="2" Text="角度" VerticalAlignment="Center" ToolTip="旋转角度(度)" />
<TextBox Grid.Row="2" Grid.Column="1" Text="{Binding SelectVisionFlow.DoubleParams[Angle], Mode=TwoWay, TargetNullValue=0, UpdateSourceTrigger=LostFocus}" />
</Grid>
</GroupBox>
<GroupBox Header="输出变量">
<Grid Margin="5">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="80" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<TextBlock Text="矩阵变量名" VerticalAlignment="Center" ToolTip="写入局部变量表的 String 变量名" />
<TextBox Grid.Column="1" Text="{Binding SelectVisionFlow.StringParams[MatrixVar], Mode=TwoWay, TargetNullValue=生成矩阵, UpdateSourceTrigger=LostFocus}" />
</Grid>
</GroupBox>
</StackPanel>
</ScrollViewer>
</UserControl>

View File

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

View File

@ -0,0 +1,43 @@
using OpenCvSharp;
namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
{
/// <summary>
/// 矩阵生成 — 根据输入位移和角度生成 2x3 仿射变换矩阵,写入局部变量表。
/// </summary>
public class MatrixGenHandler : IVisionFlowHandler
{
public VisionFlowType Type => VisionFlowType.矩阵生成;
public bool Execute(VisionFunction func, VisionFlow item)
{
double x = item.DoubleParams.TryGetValue("MoveX", out double mx) ? mx : 0;
double y = item.DoubleParams.TryGetValue("MoveY", out double my) ? my : 0;
double angle = item.DoubleParams.TryGetValue("Angle", out double a) ? a : 0;
string varName = item.StringParams.TryGetValue("MatrixVar", out var mn) && !string.IsNullOrEmpty(mn)
? mn : "生成矩阵";
var center = new Point2f(0, 0);
using Mat M = Cv2.GetRotationMatrix2D(center, angle, 1.0);
M.Set(0, 2, x);
M.Set(1, 2, y);
string json = MatExtension.SerializeAffineMat(M);
var v = func.Params.Variables.FirstOrDefault(v => v.Name == varName);
if (v == null)
{
v = new LocalVariableItem(varName, "String", json);
System.Windows.Application.Current.Dispatcher.Invoke(() => func.Params.Variables.Add(v));
}
else
{
v.RawValue = json;
}
item.Flow.Done = true;
return true;
}
}
}

View File

@ -51,7 +51,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
case "旋转矩形":
if (!item.DoubleParams.TryGetValue("TemplateWidth", out templateW) ||
!item.DoubleParams.TryGetValue("TemplateHeight", out templateH))
{ item.Flow.ErrorState = "旋转矩形模板参数缺失!"; return false; }
{ item.Flow.FailMessage = "旋转矩形模板参数缺失!"; return false; }
break;
case "圆形":
if (!item.DoubleParams.TryGetValue("TemplateRadius", out double radius))

View File

@ -1,4 +1,4 @@
<UserControl x:Class="PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm.SiftMatch"
<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"
@ -18,9 +18,7 @@
<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">
<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="圆形" />
@ -41,12 +39,18 @@
</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" />
<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" />
<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" />
@ -91,15 +95,24 @@
</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}" />
<CheckBox Grid.Row="0" Grid.Column="2" Margin="5,0" VerticalAlignment="Center" IsChecked="{Binding SelectVisionFlow.BoolParams[SiftMatch_OutPos]}" />
<CheckBox Grid.Row="0" Grid.Column="2"
Margin="5,0"
VerticalAlignment="Center"
IsChecked="{Binding SelectVisionFlow.BoolParams[SiftMatch_OutPos]}" />
<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}" />
<CheckBox Grid.Row="1" Grid.Column="2" Margin="5,0" VerticalAlignment="Center" IsChecked="{Binding SelectVisionFlow.BoolParams[SiftMatch_OutOffset]}" />
<CheckBox Grid.Row="1" Grid.Column="2"
Margin="5,0"
VerticalAlignment="Center"
IsChecked="{Binding SelectVisionFlow.BoolParams[SiftMatch_OutOffset]}" />
<TextBlock Grid.Row="2" Text="变换矩阵变量" VerticalAlignment="Center" ToolTip="变换矩阵写入此 String 变量" />
<TextBox Grid.Row="2" Grid.Column="1" Text="{Binding SelectVisionFlow.StringParams[SiftMatch_MatVar], Mode=TwoWay, TargetNullValue=SIFT匹配_矩阵}" />
<CheckBox Grid.Row="2" Grid.Column="2" Margin="5,0" VerticalAlignment="Center" IsChecked="{Binding SelectVisionFlow.BoolParams[SiftMatch_OutMat]}" />
<CheckBox Grid.Row="2" Grid.Column="2"
Margin="5,0"
VerticalAlignment="Center"
IsChecked="{Binding SelectVisionFlow.BoolParams[SiftMatch_OutMat]}" />
</Grid>
</GroupBox>
@ -127,7 +140,10 @@
<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" />
<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" />
@ -137,13 +153,19 @@
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="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" />
<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" />
@ -153,8 +175,13 @@
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"
<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>

View File

@ -1,4 +1,4 @@
using OpenCvSharp;
using OpenCvSharp;
namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
{
@ -77,7 +77,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
var existing = func.LocalImageDatas.FirstOrDefault(m => m.Name == templateName);
if (existing?.Mat == null || existing.Mat.Empty())
{
item.Flow.ErrorState = "模板提取失败,请先画选区截取模板!";
item.Flow.FailMessage = "模板提取失败,请先画选区截取模板!";
return false;
}

View File

@ -38,7 +38,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
public bool Execute(VisionFunction func, VisionFlow item)
{
var src = func.Src;
if (src == null || src.Empty()) { item.Flow.ErrorState = "请先获取图片!"; return false; }
if (src == null || src.Empty()) { item.Flow.FailMessage = "请先获取图片!"; return false; }
// ===== 1. 参数 =====
string roiShape = item.StringParams.TryGetValue("ROIShape", out var rs)
@ -48,7 +48,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
!item.DoubleParams.TryGetValue("TemplateCenterY", out double centerY) ||
!item.DoubleParams.TryGetValue("Width", out double imgW) ||
!item.DoubleParams.TryGetValue("Height", out double imgH))
{ item.Flow.ErrorState = "模板未配置,请先画选区截取模板!"; return false; }
{ item.Flow.FailMessage = "模板未配置,请先画选区截取模板!"; return false; }
double templateW, templateH;
switch (roiShape)
@ -58,22 +58,22 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
!item.DoubleParams.TryGetValue("TemplateTop", out double tTop) ||
!item.DoubleParams.TryGetValue("TemplateWidth", out templateW) ||
!item.DoubleParams.TryGetValue("TemplateHeight", out templateH))
{ item.Flow.ErrorState = "矩形模板参数缺失!"; return false; }
{ 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.ErrorState = "旋转矩形模板参数缺失!"; return false; }
{ item.Flow.FailMessage = "旋转矩形模板参数缺失!"; return false; }
break;
case "圆形":
if (!item.DoubleParams.TryGetValue("TemplateRadius", out double radius))
{ item.Flow.ErrorState = "圆形模板参数缺失!"; return false; }
{ item.Flow.FailMessage = "圆形模板参数缺失!"; return false; }
templateW = radius * 2; templateH = radius * 2;
break;
default:
item.Flow.ErrorState = $"不支持的 ROI 形状:{roiShape}"; return false;
item.Flow.FailMessage = $"不支持的 ROI 形状:{roiShape}"; return false;
}
float matchThresh = (float)(item.DoubleParams.TryGetValue("MatchThresh", out double mt) ? mt : 0.6);
@ -98,7 +98,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
var existing = func.LocalImageDatas.FirstOrDefault(m => m.Name == templateName);
if (existing?.Mat == null || existing.Mat.Empty())
{
item.Flow.ErrorState = "模板提取失败,请先画选区截取模板!";
item.Flow.FailMessage = "模板提取失败,请先画选区截取模板!";
return false;
}
@ -108,7 +108,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
!item.DoubleParams.TryGetValue("TemplateBBoxTop", out double bby) ||
!item.DoubleParams.TryGetValue("TemplateBBoxWidth", out double bbw) ||
!item.DoubleParams.TryGetValue("TemplateBBoxHeight", out double bbh))
{ item.Flow.ErrorState = "旋转矩形模板参数缺失!"; return false; }
{ item.Flow.FailMessage = "旋转矩形模板参数缺失!"; return false; }
using var cloneMat = existing.Mat.Clone();
template[new OpenCvSharp.Rect((int)bbx, (int)bby, (int)bbw, (int)bbh)] = cloneMat;
}
@ -127,18 +127,18 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
// ===== 4. 特征提取 =====
var tplFeats = ExtractFeatures(session, template, maxDim, detThresh, topK);
if (tplFeats.Length < 4)
{ item.Flow.ErrorState = $"模板特征点不足({tplFeats.Length} < 4)"; return false; }
{ item.Flow.FailMessage = $"模板特征点不足({tplFeats.Length} < 4)"; return false; }
var srcFeats = ExtractFeatures(session, src, maxDim, detThresh, topK);
if (srcFeats.Length < 4)
{ item.Flow.ErrorState = $"搜索图特征点不足({srcFeats.Length} < 4)"; return false; }
{ 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.ErrorState = "匹配点不足,定位失败!"; return false; }
{ item.Flow.FailMessage = "匹配点不足,定位失败!"; return false; }
// ===== 6. 结果 =====
double matchX = result.Value.X;

View File

@ -1,4 +1,4 @@
using OpenCvSharp;
using OpenCvSharp;
namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Processing
{
@ -12,7 +12,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Processing
public bool Execute(VisionFunction func, VisionFlow item)
{
var src = func.Src;
if (src == null || src.Empty()) { item.Flow.ErrorState = "请先获取图片!"; return false; }
if (src == null || src.Empty()) { item.Flow.FailMessage = "请先获取图片!"; return false; }
// 确保参数存在,避免 XAML 绑定报红框
if (!item.IntParams.ContainsKey("Method")) item.IntParams["Method"] = 0;

View File

@ -15,19 +15,19 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Processing
var src = func.Src;
if (src == null || src.Empty())
{
item.Flow.ErrorState = "请先获取图片!"; return false;
item.Flow.FailMessage = "请先获取图片!"; return false;
}
if (!item.StringParams.TryGetValue("Image", out var imageName) || string.IsNullOrEmpty(imageName))
{
item.Flow.ErrorState = "请选择要相减的局部图像!";
item.Flow.FailMessage = "请选择要相减的局部图像!";
return false;
}
var imageData = func.LocalImageDatas.FirstOrDefault(i => i.Name == imageName);
if (imageData?.Mat == null || imageData.Mat.Empty())
{
item.Flow.ErrorState = $"局部图像池中未找到图片:{imageName}";
item.Flow.FailMessage = $"局部图像池中未找到图片:{imageName}";
return false;
}
@ -66,7 +66,7 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Processing
// 写回 func.Src
func.Src.Dispose();
func.Src = grayOther;
func.Src = graySrc;
return true;
}
}

View File

@ -0,0 +1,24 @@
<UserControl x:Class="PLCSharp.VVMs.Vision.VisionFlowHandler.Processing.ImageWarp"
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="120" d:DesignWidth="300">
<ScrollViewer VerticalScrollBarVisibility="Auto">
<StackPanel>
<GroupBox Header="变换矩阵">
<Grid Margin="5">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="80" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<TextBlock Text="矩阵变量名" VerticalAlignment="Center" ToolTip="从局部变量表中读取 String 类型的矩阵变量" />
<TextBox Grid.Column="1" Text="{Binding SelectVisionFlow.StringParams[MatrixVar], Mode=TwoWay, TargetNullValue=SIFT匹配_矩阵, UpdateSourceTrigger=LostFocus}" />
</Grid>
</GroupBox>
</StackPanel>
</ScrollViewer>
</UserControl>

View File

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

View File

@ -0,0 +1,59 @@
using OpenCvSharp;
namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Processing
{
/// <summary>
/// 图像校正 — 用局部变量表中的变换矩阵对 func.Src 做透视变换。
/// 配合 SIFT 匹配输出的矩阵变量使用。
/// </summary>
public class ImageWarpHandler : IVisionFlowHandler
{
public VisionFlowType Type => VisionFlowType.图像校正;
public bool Execute(VisionFunction func, VisionFlow item)
{
var src = func.Src;
if (src == null || src.Empty()) { item.Flow.FailMessage = "请先获取图片!"; return false; }
if (!item.StringParams.TryGetValue("MatrixVar", out var matVarName) || string.IsNullOrEmpty(matVarName))
{ item.Flow.FailMessage = "请指定变换矩阵变量名!"; return false; }
var matVar = func.Params.Variables.FirstOrDefault(v => v.Name == matVarName);
if (matVar?.RawValue == null)
{ item.Flow.FailMessage = $"局部变量表中未找到矩阵变量:{matVarName}"; return false; }
string json = matVar.RawValue.ToString() ?? "";
if (string.IsNullOrEmpty(json))
{ item.Flow.FailMessage = $"矩阵变量为空:{matVarName}"; return false; }
Mat H;
try
{
H = MatExtension.DeserializeAffineMat(json);
}
catch
{
item.Flow.FailMessage = $"矩阵反序列化失败:{matVarName}";
return false;
}
if (H.Rows < 2 || H.Cols < 3)
{ item.Flow.FailMessage = $"矩阵格式错误({H.Rows}x{H.Cols},应为 2x3)"; return false; }
using Mat warped = new();
using Mat invH = new();
Cv2.InvertAffineTransform(H, invH);
Cv2.WarpAffine(src, warped, invH, src.Size(), InterpolationFlags.Linear,
BorderTypes.Constant, Scalar.Black);
H.Dispose();
var oldSrc = func.Src;
func.Src = warped.Clone();
oldSrc.Dispose();
item.Flow.Done = true;
return true;
}
}
}

View File

@ -268,14 +268,11 @@ namespace PLCSharp.VVMs.Vision
}
else
{
var customControl = GlobalModel.GetCustomControl(ControlName);
if (customControl != null && Src != null)
{
customControl.ShowMat(Src);
}
flow.Done = true;
flow.IsSuccess = true;
@ -303,14 +300,14 @@ namespace PLCSharp.VVMs.Vision
}
else
{
item.Flow.ErrorState ??= "未知错误";
item.Flow.FailMessage ??= "未知错误";
flow.IsSuccess = false;
flow.Done = true;
}
}
else if (item.Flow.CheckStepTime(flow.TimeoutSeconds))
{
item.Flow.ErrorState = $"执行超时(>{flow.TimeoutSeconds:F0}秒)";
item.Flow.FailMessage = $"执行超时(>{flow.TimeoutSeconds:F0}秒)";
flow.IsSuccess = false;
flow.Done = true;
}
@ -369,6 +366,7 @@ namespace PLCSharp.VVMs.Vision
[VisionFlowType.灰度模板匹配] = new GrayTemplateMatchHandler(),
[VisionFlowType.SIFT匹配] = new SiftMatchHandler(),
[VisionFlowType.XFeat匹配] = new XFeatMatchHandler(),
[VisionFlowType.矩阵生成] = new MatrixGenHandler(),
[VisionFlowType.点到点距离] = new PointToPointDistanceHandler(),
[VisionFlowType.卡尺找圆] = new CaliperFindCircleHandler(),
[VisionFlowType.卡尺找旋转矩形] = new CaliperFindRectHandler(),
@ -384,6 +382,7 @@ namespace PLCSharp.VVMs.Vision
[VisionFlowType.ROI剪切] = new ROICropHandler(),
[VisionFlowType.直方图均衡化] = new HistogramEqualizeHandler(),
[VisionFlowType.图像相减] = new ImageSubtractHandler(),
[VisionFlowType.图像校正] = new ImageWarpHandler(),
};
[NotMapped]

View File

@ -59,6 +59,12 @@
[FlowCategory("图像处理")]
图像相减 = 23,
[FlowCategory("图像处理")]
图像校正 = 24,
[FlowCategory("算法")]
矩阵生成 = 44,
[FlowCategory("图像处理")]
坐标转换 = 18,