This commit is contained in:
tfarcraw 2026-08-04 11:52:30 +08:00
parent deb1be9026
commit d98e2480d5
13 changed files with 334 additions and 379 deletions

View File

@ -1,6 +1,7 @@
#nullable enable
using System.Text.Json;
using System.Text.Json.Serialization;
namespace PLCSharp.Core.Tools
{
@ -10,11 +11,13 @@ namespace PLCSharp.Core.Tools
public static class JsonOptions
{
/// <summary>
/// 默认选项:属性名大小写不敏感(用于 EF Core 列序列化 / 反序列化)。
/// 默认选项:属性名大小写不敏感(用于 EF Core 列序列化 / 反序列化);
/// 允许 NaN / Infinity 等命名浮点字面量,避免局部变量表中的非法值导致序列化崩溃。
/// </summary>
public static JsonSerializerOptions Default { get; } = new()
{
PropertyNameCaseInsensitive = true,
NumberHandling = JsonNumberHandling.AllowNamedFloatingPointLiterals,
};
/// <summary>
@ -24,6 +27,7 @@ namespace PLCSharp.Core.Tools
{
PropertyNameCaseInsensitive = true,
WriteIndented = true,
NumberHandling = JsonNumberHandling.AllowNamedFloatingPointLiterals,
};
}
}

View File

@ -21,7 +21,7 @@
<PackageReference Include="Libdmtx.Net" Version="0.7.9-dev.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="9.0.17" />
<PackageReference Include="MiniExcel" Version="1.45.0" />
<PackageReference Include="OpenCvSharp5.Windows" Version="5.0.0.20260726" />
<PackageReference Include="OpenCvSharp5.Windows" Version="5.0.0.20260730" />
<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" />-->

View File

@ -166,12 +166,8 @@ public partial class VisionConfigViewModel
ContentRegion = new MatrixGen();
break;
case VisionFlowType.点到点距离:
ContentRegion = new PointToPointDistance();
break;
case VisionFlowType.点到线距离:
ContentRegion = new PointToLineDistance();
case VisionFlowType.距离:
ContentRegion = new Distance();
break;
case VisionFlowType.画廊分类:
@ -392,7 +388,7 @@ public partial class VisionConfigViewModel
newFlow.DoubleParams["RansacTh"] = 5;
newFlow.IntParams["CaliperLength"] = 100;
newFlow.IntParams["NumCalipers"] = 50;
newFlow.BoolParams["Caliper_OutOffset"] = true;
newFlow.BoolParams["Caliper_OutOffset"] = false;
newFlow.StringParams["EdgeName"] = "卡尺寻边_Edge";
newFlow.StringParams["LineOffsetVar"] = "找线_Offset";
newFlow.StringParams["Caliper_TransformOutVar"] = "找线_转换";
@ -551,14 +547,9 @@ public partial class VisionConfigViewModel
newFlow.StringParams["MatrixVar"] = "生成矩阵";
break;
case VisionFlowType.点到点距离:
newFlow.StringParams["ResultVar"] = "点到点距离";
newFlow.StringParams["PtPt_TransOutVar"] = "点到点距离_转换";
break;
case VisionFlowType.点到线距离:
newFlow.StringParams["ResultVar"] = "点到线距离";
newFlow.StringParams["PtLine_TransOutVar"] = "点到线距离_转换";
case VisionFlowType.距离:
newFlow.StringParams["ResultVar"] = "距离";
newFlow.StringParams["Dist_TransOutVar"] = "距离_转换";
break;
case VisionFlowType.两线交点:

View File

@ -1,4 +1,4 @@
<UserControl x:Class="PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm.PointToPointDistance"
<UserControl x:Class="PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm.Distance"
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"
@ -7,7 +7,7 @@
xmlns:vision="clr-namespace:PLCSharp.VVMs.Vision"
mc:Ignorable="d"
d:DataContext="{d:DesignInstance Type=vision:VisionConfigViewModel}"
d:DesignHeight="200" d:DesignWidth="300">
d:DesignHeight="280" d:DesignWidth="300">
<ScrollViewer VerticalScrollBarVisibility="Auto">
<StackPanel>
<GroupBox Header="参数">
@ -21,55 +21,74 @@
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="80" />
<ColumnDefinition />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0" Text="点1变量" VerticalAlignment="Center" />
<TextBlock Grid.Row="0" Text="变量1" VerticalAlignment="Center" />
<ComboBox Grid.Row="0" Grid.Column="1"
Grid.ColumnSpan="2"
ItemsSource="{Binding AllVariables}"
SelectedValue="{Binding SelectVisionFlow.StringParams[Point1Var], Mode=TwoWay}"
SelectedValue="{Binding SelectVisionFlow.StringParams[Var1], Mode=TwoWay}"
SelectedValuePath="Name" DisplayMemberPath="Name" />
<TextBlock Grid.Row="1" Text="点2变量" VerticalAlignment="Center" />
<TextBlock Grid.Row="1" Text="变量2" VerticalAlignment="Center" />
<ComboBox Grid.Row="1" Grid.Column="1"
Grid.ColumnSpan="2"
ItemsSource="{Binding AllVariables}"
SelectedValue="{Binding SelectVisionFlow.StringParams[Point2Var], Mode=TwoWay}"
SelectedValue="{Binding SelectVisionFlow.StringParams[Var2], Mode=TwoWay}"
SelectedValuePath="Name" DisplayMemberPath="Name" />
<TextBlock Grid.Row="2" Text="结果变量" VerticalAlignment="Center" />
<TextBox Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="2" Text="{Binding SelectVisionFlow.StringParams[ResultVar], Mode=TwoWay}" />
<TextBlock Grid.Row="3" Text="距离" VerticalAlignment="Center" />
<TextBox Grid.Row="3" Grid.Column="1"
Grid.ColumnSpan="2"
Text="{Binding SelectedVisionFunction.Params.ResultDoubles[PointDist_Distance], Mode=OneWay}"
Text="{Binding SelectedVisionFunction.Params.ResultDoubles[Dist_Distance], Mode=OneWay}"
IsReadOnly="True" Background="#FFF0F0F0" />
<TextBlock Grid.Row="4" Text="ΔX" VerticalAlignment="Center" />
<TextBox Grid.Row="4" Grid.Column="1"
Grid.ColumnSpan="2"
Text="{Binding SelectedVisionFunction.Params.ResultDoubles[PointDist_DeltaX], Mode=OneWay}"
Text="{Binding SelectedVisionFunction.Params.ResultDoubles[Dist_DeltaX], Mode=OneWay}"
IsReadOnly="True" Background="#FFF0F0F0" />
<TextBlock Grid.Row="5" Text="ΔY" VerticalAlignment="Center" />
<TextBox Grid.Row="5" Grid.Column="1"
Grid.ColumnSpan="2"
Text="{Binding SelectedVisionFunction.Params.ResultDoubles[PointDist_DeltaY], Mode=OneWay}"
Text="{Binding SelectedVisionFunction.Params.ResultDoubles[Dist_DeltaY], Mode=OneWay}"
IsReadOnly="True" Background="#FFF0F0F0" />
<TextBlock Grid.Row="6" Text="坐标转换" VerticalAlignment="Center" />
<ComboBox Grid.Row="6" Grid.Column="1"
<TextBlock Grid.Row="6" Text="垂足X" VerticalAlignment="Center" />
<TextBox Grid.Row="6" Grid.Column="1"
Grid.ColumnSpan="2"
Text="{Binding SelectedVisionFunction.Params.ResultDoubles[Dist_FootX], Mode=OneWay}"
IsReadOnly="True" Background="#FFF0F0F0" />
<TextBlock Grid.Row="7" Text="垂足Y" VerticalAlignment="Center" />
<TextBox Grid.Row="7" Grid.Column="1"
Grid.ColumnSpan="2"
Text="{Binding SelectedVisionFunction.Params.ResultDoubles[Dist_FootY], Mode=OneWay}"
IsReadOnly="True" Background="#FFF0F0F0" />
<TextBlock Grid.Row="8" Text="坐标转换" VerticalAlignment="Center" />
<ComboBox Grid.Row="8" Grid.Column="1"
Margin="5,0"
ItemsSource="{Binding SystemVariables}"
SelectedValue="{Binding SelectVisionFlow.StringParams[PtPt_TransMat], Mode=TwoWay}"
SelectedValue="{Binding SelectVisionFlow.StringParams[Dist_TransMat], Mode=TwoWay}"
SelectedValuePath="Name" DisplayMemberPath="Name" />
<CheckBox Grid.Row="6" Grid.Column="2"
<CheckBox Grid.Row="8" Grid.Column="2"
VerticalAlignment="Center"
Content="启用"
IsChecked="{Binding SelectVisionFlow.BoolParams[PtPt_EnableTrans], Mode=TwoWay}" />
<TextBlock Grid.Row="7" Text="转换变量" VerticalAlignment="Center" />
<TextBox Grid.Row="7" Grid.Column="1" Grid.ColumnSpan="2" Text="{Binding SelectVisionFlow.StringParams[PtPt_TransOutVar], Mode=TwoWay}" />
IsChecked="{Binding SelectVisionFlow.BoolParams[Dist_EnableTrans], Mode=TwoWay}" />
<TextBlock Grid.Row="9" Text="转换变量" VerticalAlignment="Center" />
<TextBox Grid.Row="9" Grid.Column="1" Grid.ColumnSpan="2" Text="{Binding SelectVisionFlow.StringParams[Dist_TransOutVar], Mode=TwoWay}" />
<TextBlock Grid.Row="10" Grid.ColumnSpan="3"
Margin="0,4,0,0"
TextWrapping="Wrap"
Foreground="#FF888888"
FontSize="11"
Text="规则:Pos+Pos 点距 / Pos+Line 点线距 / Line+Line 线中点到线 / Line+Circle 圆心到线 / Circle+Circle 圆心距 / Pos+Circle 点到圆心" />
</Grid>
</GroupBox>
</StackPanel>
</ScrollViewer>
</UserControl>
</UserControl>

View File

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

View File

@ -0,0 +1,257 @@
using OpenCvSharp;
using System.Windows.Media;
namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
{
/// <summary>
/// 距离工具 —— 根据两个变量的类型自动计算:
/// Pos+Pos 点到点 / Pos+Line 点到线 / Line+Line 第一条线的中点到第二条线 / Line+Circle 圆心到线 / Circle+Circle 圆心距 / Pos+Circle 点到圆心
/// </summary>
public class DistanceHandler : IVisionFlowHandler
{
public VisionFlowType Type => VisionFlowType.距离;
public bool Execute(VisionFunction func, VisionFlow item)
{
var var1Name = item.StringParams.TryGetValue("Var1", out var v1) && !string.IsNullOrEmpty(v1) ? v1 : "None";
var var2Name = item.StringParams.TryGetValue("Var2", out var v2) && !string.IsNullOrEmpty(v2) ? v2 : "None";
var var1 = func.Params.Variables.FirstOrDefault(v => v.Name == var1Name);
var var2 = func.Params.Variables.FirstOrDefault(v => v.Name == var2Name);
if (var1 == null) throw new Exception($"变量 '{var1Name}' 不存在!");
if (var2 == null) throw new Exception($"变量 '{var2Name}' 不存在!");
var raw1 = var1.RawValue;
var raw2 = var2.RawValue;
// 点实体:Pos 直接取坐标,Circle 取圆心
Point2d? GetPoint(object raw) => raw switch
{
Pos p => new Point2d(p.X, p.Y),
Circle c => new Point2d(c.Center.X, c.Center.Y),
_ => null
};
double dist = 0, dx = 0, dy = 0, footX = 0, footY = 0;
bool isPointToPoint = false;
Point2d pa = default, pb = default; // 点对点场景的两个点
Point2d pt = default; Line line = default; // 点对线场景的点与线
var a = GetPoint(raw1);
var b = GetPoint(raw2);
if (a.HasValue && b.HasValue)
{
// 规则1/5/6:Pos+Pos、Circle+Circle、Pos+Circle(或反过来),圆取圆心参与点距
pa = a.Value; pb = b.Value;
isPointToPoint = true;
}
else if (a.HasValue && raw2 is Line)
{
// 规则2/4:Pos+Line、Circle+Line(圆取圆心)
pt = a.Value; line = (Line)raw2;
}
else if (raw1 is Line && b.HasValue)
{
// 规则2/4:Line+Pos、Line+Circle(圆取圆心)
pt = b.Value; line = (Line)raw1;
}
else if (raw1 is Line && raw2 is Line)
{
// 规则3:第一条线的中点到第二条线的距离
var ln1 = (Line)raw1;
var ln2 = (Line)raw2;
pt = new Point2d((ln1.From.X + ln1.To.X) / 2, (ln1.From.Y + ln1.To.Y) / 2);
line = ln2;
}
else
{
throw new Exception($"变量 '{var1Name}'({Describe(raw1)}) 与 '{var2Name}'({Describe(raw2)}) 类型组合不支持!仅支持 Pos / Line / Circle 的组合。");
}
double? tDist = null; // 坐标转换后的距离
if (isPointToPoint)
{
(dist, dx, dy) = PointToPoint(pa, pb);
func.Params.ResultDoubles["Dist_Distance"] = dist;
func.Params.ResultDoubles["Dist_DeltaX"] = dx;
func.Params.ResultDoubles["Dist_DeltaY"] = dy;
if (TryGetTransform(item, func, out var mat) && mat != null)
{
using (mat)
{
var tp1 = TransformPoint(mat, pa.X, pa.Y);
var tp2 = TransformPoint(mat, pb.X, pb.Y);
double tDist_ = Math.Sqrt((tp2.X - tp1.X) * (tp2.X - tp1.X) + (tp2.Y - tp1.Y) * (tp2.Y - tp1.Y));
// UI 显示转换后值
func.Params.ResultDoubles["Dist_Distance"] = Math.Round(tDist_, 3);
func.Params.ResultDoubles["Dist_DeltaX"] = Math.Round(tp2.X - tp1.X, 3);
func.Params.ResultDoubles["Dist_DeltaY"] = Math.Round(tp2.Y - tp1.Y, 3);
tDist = Math.Round(tDist_, 3);
}
}
}
else
{
(dist, footX, footY) = PointToLine(pt, line);
func.Params.ResultDoubles["Dist_Distance"] = dist;
func.Params.ResultDoubles["Dist_FootX"] = footX;
func.Params.ResultDoubles["Dist_FootY"] = footY;
if (TryGetTransform(item, func, out var mat) && mat != null)
{
using (mat)
{
var tf = TransformPoint(mat, line.From.X, line.From.Y);
var tt = TransformPoint(mat, line.To.X, line.To.Y);
var tp = TransformPoint(mat, pt.X, pt.Y);
var tLine = new Line(new Pos(tf.X, tf.Y, 0, 0), new Pos(tt.X, tt.Y, 0, 0));
var tPoint = new Point2d(tp.X, tp.Y);
var (tDist_, tFootX, tFootY) = PointToLine(tPoint, tLine);
// UI 显示转换后值
func.Params.ResultDoubles["Dist_Distance"] = tDist_;
func.Params.ResultDoubles["Dist_FootX"] = tFootX;
func.Params.ResultDoubles["Dist_FootY"] = tFootY;
tDist = tDist_;
}
}
}
// 主结果:未启用转换写像素距离,启用转换写转换后距离
func.ResultDouble = tDist.HasValue ? Math.Round(tDist.Value, 3) : dist;
// 结果写入局部变量(未转换的距离)
var resultVarName = item.StringParams.TryGetValue("ResultVar", out var rv) && !string.IsNullOrEmpty(rv) ? rv : "距离";
var resultVar = func.Params.Variables.FirstOrDefault(v => v.Name == resultVarName);
if (resultVar == null)
{
resultVar = new LocalVariableItem(resultVarName, "Double", 0.0);
System.Windows.Application.Current.Dispatcher.Invoke(() => func.Params.Variables.Add(resultVar));
}
resultVar.RawValue = dist;
// 转换后距离写入转换输出变量(仅当坐标转换实际执行成功时)
if (tDist.HasValue)
{
var xfOutVar = item.StringParams.TryGetValue("Dist_TransOutVar", out var xov) && !string.IsNullOrEmpty(xov) ? xov : null;
if (xfOutVar != null)
{
var xfVar = func.Params.Variables.FirstOrDefault(v => v.Name == xfOutVar);
if (xfVar == null)
{
xfVar = new LocalVariableItem(xfOutVar, "Double", 0.0);
System.Windows.Application.Current.Dispatcher.Invoke(() => func.Params.Variables.Add(xfVar));
}
xfVar.RawValue = Math.Round(tDist.Value, 3);
}
}
// 可视化
DrawVisualization(func, raw1, raw2, isPointToPoint, pa, pb, pt, line, footX, footY, dist);
_ = func.RenderDrawAsync();
item.Flow.Completed = true;
return true;
}
/// <summary>
/// 读取并反序列化坐标转换矩阵(Dist_EnableTrans / Dist_TransMat)
/// </summary>
private static bool TryGetTransform(VisionFlow item, VisionFunction func, out Mat mat)
{
mat = null;
if (!item.BoolParams.TryGetValue("Dist_EnableTrans", out bool doXf) || !doXf) return false;
if (!item.StringParams.TryGetValue("Dist_TransMat", out var xfName) || string.IsNullOrEmpty(xfName)) return false;
var sysVar = func.GlobalModel.VariablesModel.SystemVariables.FirstOrDefault(v => v.Name == xfName);
if (sysVar?.Value == null) return false;
mat = MatExtension.DeserializeAffineMat((string)sysVar.Value);
return true;
}
/// <summary>
/// 仿射/透视矩阵变换点
/// </summary>
private static Point2f TransformPoint(Mat mat, double px, double py)
{
if (mat.Rows == 2)
return new Point2f(
(float)(px * mat.At<double>(0, 0) + py * mat.At<double>(0, 1) + mat.At<double>(0, 2)),
(float)(px * mat.At<double>(1, 0) + py * mat.At<double>(1, 1) + mat.At<double>(1, 2)));
double w = px * mat.At<double>(2, 0) + py * mat.At<double>(2, 1) + mat.At<double>(2, 2);
if (Math.Abs(w) < 1e-10) return new Point2f(0, 0);
return new Point2f(
(float)((px * mat.At<double>(0, 0) + py * mat.At<double>(0, 1) + mat.At<double>(0, 2)) / w),
(float)((px * mat.At<double>(1, 0) + py * mat.At<double>(1, 1) + mat.At<double>(1, 2)) / w));
}
/// <summary>
/// 点到点距离
/// </summary>
private static (double dist, double dx, double dy) PointToPoint(Point2d a, Point2d b)
{
double dx = b.X - a.X, dy = b.Y - a.Y;
return (Math.Round(Math.Sqrt(dx * dx + dy * dy), 3), Math.Round(dx, 3), Math.Round(dy, 3));
}
/// <summary>
/// 点到直线距离 + 垂足
/// </summary>
private static (double dist, double footX, double footY) PointToLine(Point2d p, Line l)
{
double x1 = l.From.X, y1 = l.From.Y, x2 = l.To.X, y2 = l.To.Y;
double A = y2 - y1, B = x1 - x2, C = x2 * y1 - x1 * y2;
double denom = Math.Sqrt(A * A + B * B);
if (denom < 1e-10) throw new Exception("直线长度为零!");
double dist = Math.Abs(A * p.X + B * p.Y + C) / denom;
double dot = (p.X - x1) * (x2 - x1) + (p.Y - y1) * (y2 - y1);
double t = dot / (denom * denom);
return (Math.Round(dist, 3), Math.Round(x1 + t * (x2 - x1), 3), Math.Round(y1 + t * (y2 - y1), 3));
}
private static string Describe(object raw) => raw switch
{
Pos => "Pos",
Line => "Line",
Circle => "Circle",
Rect => "Rect",
Barcode => "Barcode",
_ => raw.GetType().Name
};
private static void DrawVisualization(VisionFunction func, object raw1, object raw2, bool isPointToPoint,
Point2d pa, Point2d pb, Point2d pt, Line line, double footX, double footY, double dist)
{
// 画输入的几何实体(线/圆)
void DrawEntity(object raw)
{
switch (raw)
{
case Line l:
func.DrawCommands.Add(DrawCommand.Line(l.From.X, l.From.Y, l.To.X, l.To.Y, Colors.Lime, 2));
break;
case Circle c:
func.DrawCommands.Add(DrawCommand.Circle(c.Center.X, c.Center.Y, c.Radius, Colors.Lime, 2));
break;
}
}
DrawEntity(raw1);
DrawEntity(raw2);
if (isPointToPoint)
{
func.DrawCommands.Add(DrawCommand.Line(pa.X, pa.Y, pb.X, pb.Y, Colors.Cyan, 1));
func.DrawCommands.Add(DrawCommand.FilledCircle(pa.X, pa.Y, 4, Colors.Yellow));
func.DrawCommands.Add(DrawCommand.FilledCircle(pb.X, pb.Y, 4, Colors.Yellow));
func.DrawCommands.Add(DrawCommand.TextBlock((pa.X + pb.X) / 2 + 5, (pa.Y + pb.Y) / 2 - 5, $"{dist:F3}", Colors.Lime, 48));
}
else
{
func.DrawCommands.Add(DrawCommand.Line(pt.X, pt.Y, footX, footY, Colors.Cyan, 1));
func.DrawCommands.Add(DrawCommand.FilledCircle(pt.X, pt.Y, 4, Colors.Yellow));
func.DrawCommands.Add(DrawCommand.FilledCircle(footX, footY, 3, Colors.Cyan));
func.DrawCommands.Add(DrawCommand.TextBlock((pt.X + footX) / 2, (pt.Y + footY) / 2 - 10, $"{dist:F3}", Colors.Lime, 48));
}
}
}
}

View File

@ -1,69 +0,0 @@
<UserControl x:Class="PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm.PointToLineDistance"
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="200" d:DesignWidth="300">
<ScrollViewer VerticalScrollBarVisibility="Auto">
<StackPanel>
<GroupBox Header="参数">
<Grid Margin="5">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="80" />
<ColumnDefinition />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0" Text="点变量" VerticalAlignment="Center" />
<ComboBox Grid.Row="0" Grid.Column="1"
ItemsSource="{Binding AllVariables}"
SelectedValue="{Binding SelectVisionFlow.StringParams[PointVar], Mode=TwoWay}"
SelectedValuePath="Name" DisplayMemberPath="Name" />
<TextBlock Grid.Row="1" Text="线变量" VerticalAlignment="Center" />
<ComboBox Grid.Row="1" Grid.Column="1"
ItemsSource="{Binding AllVariables}"
SelectedValue="{Binding SelectVisionFlow.StringParams[LineVar], Mode=TwoWay}"
SelectedValuePath="Name" DisplayMemberPath="Name" />
<TextBlock Grid.Row="2" Text="结果变量" VerticalAlignment="Center" />
<TextBox Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="2" Text="{Binding SelectVisionFlow.StringParams[ResultVar], Mode=TwoWay}" />
<TextBlock Grid.Row="3" Text="距离" VerticalAlignment="Center" />
<TextBox Grid.Row="3" Grid.Column="1"
Grid.ColumnSpan="2"
Text="{Binding SelectedVisionFunction.Params.ResultDoubles[PointLineDist_Distance], Mode=OneWay}"
IsReadOnly="True" Background="#FFF0F0F0" />
<TextBlock Grid.Row="4" Text="垂足X,Y" VerticalAlignment="Center" />
<TextBox Grid.Row="4" Grid.Column="1"
Grid.ColumnSpan="2"
Text="{Binding SelectedVisionFunction.Params.ResultDoubles[PointLineDist_FootX], Mode=OneWay}"
IsReadOnly="True" Background="#FFF0F0F0" />
<TextBlock Grid.Row="5" Text="坐标转换" VerticalAlignment="Center" />
<ComboBox Grid.Row="5" Grid.Column="1"
Margin="5,0"
ItemsSource="{Binding SystemVariables}"
SelectedValue="{Binding SelectVisionFlow.StringParams[PtLine_TransMat], Mode=TwoWay}"
SelectedValuePath="Name" DisplayMemberPath="Name" />
<CheckBox Grid.Row="5" Grid.Column="2"
VerticalAlignment="Center"
Content="启用"
IsChecked="{Binding SelectVisionFlow.BoolParams[PtLine_EnableTrans], Mode=TwoWay}" />
<TextBlock Grid.Row="7" Text="转换变量" VerticalAlignment="Center" />
<TextBox Grid.Row="7" Grid.Column="1" Grid.ColumnSpan="2" Text="{Binding SelectVisionFlow.StringParams[PtLine_TransOutVar], Mode=TwoWay}" />
</Grid>
</GroupBox>
</StackPanel>
</ScrollViewer>
</UserControl>

View File

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

View File

@ -1,143 +0,0 @@
using OpenCvSharp;
using System.Windows.Media;
namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
{
/// <summary>
/// 点到线距离工具 —— 读取一个 Pos 变量和一个 Line 变量,计算点到直线的垂直距离。
/// </summary>
public class PointToLineDistanceHandler : IVisionFlowHandler
{
public VisionFlowType Type => VisionFlowType.点到线距离;
public bool Execute(VisionFunction func, VisionFlow item)
{
var pointVarName = item.StringParams.TryGetValue("PointVar", out var pv) && !string.IsNullOrEmpty(pv) ? pv : "None";
var lineVarName = item.StringParams.TryGetValue("LineVar", out var lv) && !string.IsNullOrEmpty(lv) ? lv : "None";
var pointVar = func.Params.Variables.FirstOrDefault(v => v.Name == pointVarName);
var lineVar = func.Params.Variables.FirstOrDefault(v => v.Name == lineVarName);
if (pointVar == null) { item.Flow.FailMessage = $"变量 '{pointVarName}' 不存在!"; return false; }
if (lineVar == null) { item.Flow.FailMessage = $"变量 '{lineVarName}' 不存在!"; return false; }
if (pointVar.RawValue is not Pos point) { item.Flow.FailMessage = $"变量 '{pointVarName}' 不是 Pos 类型!"; return false; }
if (lineVar.RawValue is not Line line) { item.Flow.FailMessage = $"变量 '{lineVarName}' 不是 Line 类型!"; return false; }
// 点到直线垂直距离公式
double x1 = line.From.X, y1 = line.From.Y;
double x2 = line.To.X, y2 = line.To.Y;
double x0 = point.X, y0 = point.Y;
double A = y2 - y1;
double B = x1 - x2;
double C = x2 * y1 - x1 * y2;
double denom = Math.Sqrt(A * A + B * B);
if (denom < 1e-10) { item.Flow.FailMessage = "直线长度为零!"; return false; }
double dist = Math.Abs(A * x0 + B * y0 + C) / denom;
dist = Math.Round(dist, 3);
// 垂足坐标
double dot = (x0 - x1) * (x2 - x1) + (y0 - y1) * (y2 - y1);
double t = dot / (denom * denom);
double footX = Math.Round(x1 + t * (x2 - x1), 3);
double footY = Math.Round(y1 + t * (y2 - y1), 3);
func.Params.ResultDoubles["PointLineDist_Distance"] = dist;
func.Params.ResultDoubles["PointLineDist_FootX"] = footX;
func.Params.ResultDoubles["PointLineDist_FootY"] = footY;
// 坐标转换
bool transformApplied = false;
double tDist = 0;
if (item.BoolParams.TryGetValue("PtLine_EnableTrans", out bool doXf) && doXf)
{
if (item.StringParams.TryGetValue("PtLine_TransMat", out var xfName) && !string.IsNullOrEmpty(xfName))
{
var sysVar = func.GlobalModel.VariablesModel.SystemVariables.FirstOrDefault(v => v.Name == xfName);
if (sysVar?.Value != null)
{
Mat transformMat = MatExtension.DeserializeAffineMat((string)sysVar.Value);
using (transformMat)
{
Point2f XfPt(double px, double py)
{
if (transformMat.Rows == 2)
return new Point2f(
(float)(px * transformMat.At<double>(0, 0) + py * transformMat.At<double>(0, 1) + transformMat.At<double>(0, 2)),
(float)(px * transformMat.At<double>(1, 0) + py * transformMat.At<double>(1, 1) + transformMat.At<double>(1, 2)));
double w = px * transformMat.At<double>(2, 0) + py * transformMat.At<double>(2, 1) + transformMat.At<double>(2, 2);
if (Math.Abs(w) < 1e-10) return new Point2f(0, 0);
return new Point2f(
(float)((px * transformMat.At<double>(0, 0) + py * transformMat.At<double>(0, 1) + transformMat.At<double>(0, 2)) / w),
(float)((px * transformMat.At<double>(1, 0) + py * transformMat.At<double>(1, 1) + transformMat.At<double>(1, 2)) / w));
}
var tf = XfPt(line.From.X, line.From.Y);
var tt = XfPt(line.To.X, line.To.Y);
var tp = XfPt(point.X, point.Y);
// 变换后重新计算距离
double nx1 = tf.X, ny1 = tf.Y, nx2 = tt.X, ny2 = tt.Y, nx0 = tp.X, ny0 = tp.Y;
double nA = ny2 - ny1, nB = nx1 - nx2, nC = nx2 * ny1 - nx1 * ny2;
double nDenom = Math.Sqrt(nA * nA + nB * nB);
if (nDenom >= 1e-10)
{
double _tDist = Math.Abs(nA * nx0 + nB * ny0 + nC) / nDenom;
double nDot = (nx0 - nx1) * (nx2 - nx1) + (ny0 - ny1) * (ny2 - ny1);
double nT = nDot / (nDenom * nDenom);
double nFootX = Math.Round(nx1 + nT * (nx2 - nx1), 3);
double nFootY = Math.Round(ny1 + nT * (ny2 - ny1), 3);
// UI 显示转换后值
func.Params.ResultDoubles["PointLineDist_Distance"] = Math.Round(_tDist, 3);
func.Params.ResultDoubles["PointLineDist_FootX"] = nFootX;
func.Params.ResultDoubles["PointLineDist_FootY"] = nFootY;
transformApplied = true;
tDist = Math.Round(_tDist, 3);
}
}
}
}
}
if (transformApplied)
{
// 转换后距离写入 TransOutVar
var xfVarName = item.StringParams.TryGetValue("PtLine_TransOutVar", out var xov) && !string.IsNullOrEmpty(xov) ? xov : null;
if (xfVarName != null)
{
var xfVar = func.Params.Variables.FirstOrDefault(v => v.Name == xfVarName);
if (xfVar == null)
{
xfVar = new LocalVariableItem(xfVarName, "Double", 0.0);
System.Windows.Application.Current.Dispatcher.Invoke(() => func.Params.Variables.Add(xfVar));
}
xfVar.RawValue = tDist;
}
}
var resultVarName = item.StringParams.TryGetValue("ResultVar", out var rv) && !string.IsNullOrEmpty(rv) ? rv : "点到线距离";
var resultVar = func.Params.Variables.FirstOrDefault(v => v.Name == resultVarName);
if (resultVar == null)
{
resultVar = new LocalVariableItem(resultVarName, "Double", 0.0);
System.Windows.Application.Current.Dispatcher.Invoke(() => func.Params.Variables.Add(resultVar));
}
resultVar.RawValue = dist;
// 可视化
func.DrawCommands.Add(DrawCommand.Line(line.From.X, line.From.Y, line.To.X, line.To.Y, Colors.Lime, 2));
func.DrawCommands.Add(DrawCommand.Line(point.X, point.Y, footX, footY, Colors.Cyan, 1));
func.DrawCommands.Add(DrawCommand.FilledCircle(point.X, point.Y, 4, Colors.Yellow));
func.DrawCommands.Add(DrawCommand.FilledCircle(footX, footY, 3, Colors.Cyan));
func.DrawCommands.Add(DrawCommand.TextBlock(
(point.X + footX) / 2, (point.Y + footY) / 2 - 10,
$"{func.Params.ResultDoubles["PointLineDist_Distance"]:F3}", Colors.Lime, 48));
_ = func.RenderDrawAsync();
item.Flow.Completed = true;
return true;
}
}
}

View File

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

View File

@ -1,103 +0,0 @@
using OpenCvSharp;
using System.Windows.Media;
namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
{
/// <summary>
/// 点到点距离工具 —— 读取两个 Pos 局部变量,计算欧几里德距离。
/// </summary>
public class PointToPointDistanceHandler : IVisionFlowHandler
{
public VisionFlowType Type => VisionFlowType.点到点距离;
public bool Execute(VisionFunction func, VisionFlow item)
{
var var1Name = item.StringParams.TryGetValue("Point1Var", out var p1) && !string.IsNullOrEmpty(p1) ? p1 : "None";
var var2Name = item.StringParams.TryGetValue("Point2Var", out var p2) && !string.IsNullOrEmpty(p2) ? p2 : "None";
var var1 = func.Params.Variables.FirstOrDefault(v => v.Name == var1Name);
var var2 = func.Params.Variables.FirstOrDefault(v => v.Name == var2Name);
if (var1 == null) throw new Exception($"变量 '{var1Name}' 不存在!");
if (var2 == null) throw new Exception($"变量 '{var2Name}' 不存在!");
if (var1.RawValue is not Pos pos1) throw new Exception($"变量 '{var1Name}' 不是 Pos 类型!");
if (var2.RawValue is not Pos pos2) throw new Exception($"变量 '{var2Name}' 不是 Pos 类型!");
double dist = Math.Sqrt((pos2.X - pos1.X) * (pos2.X - pos1.X) + (pos2.Y - pos1.Y) * (pos2.Y - pos1.Y));
dist = Math.Round(dist, 3);
func.Params.ResultDoubles["PointDist_Distance"] = dist;
func.Params.ResultDoubles["PointDist_DeltaX"] = Math.Round(pos2.X - pos1.X, 3);
func.Params.ResultDoubles["PointDist_DeltaY"] = Math.Round(pos2.Y - pos1.Y, 3);
// 坐标转换
double? tDist = null;
if (item.BoolParams.TryGetValue("PtPt_EnableTrans", out bool doXf) && doXf)
{
if (item.StringParams.TryGetValue("PtPt_TransMat", out var xfName) && !string.IsNullOrEmpty(xfName))
{
var sysVar = func.GlobalModel.VariablesModel.SystemVariables.FirstOrDefault(v => v.Name == xfName);
if (sysVar?.Value != null)
{
Mat transformMat = MatExtension.DeserializeAffineMat((string)sysVar.Value);
using (transformMat)
{
Point2f XfPt(double px, double py)
{
if (transformMat.Rows == 2)
return new Point2f(
(float)(px * transformMat.At<double>(0, 0) + py * transformMat.At<double>(0, 1) + transformMat.At<double>(0, 2)),
(float)(px * transformMat.At<double>(1, 0) + py * transformMat.At<double>(1, 1) + transformMat.At<double>(1, 2)));
double w = px * transformMat.At<double>(2, 0) + py * transformMat.At<double>(2, 1) + transformMat.At<double>(2, 2);
if (Math.Abs(w) < 1e-10) return new Point2f(0, 0);
return new Point2f(
(float)((px * transformMat.At<double>(0, 0) + py * transformMat.At<double>(0, 1) + transformMat.At<double>(0, 2)) / w),
(float)((px * transformMat.At<double>(1, 0) + py * transformMat.At<double>(1, 1) + transformMat.At<double>(1, 2)) / w));
}
var tp1 = XfPt(pos1.X, pos1.Y);
var tp2 = XfPt(pos2.X, pos2.Y);
double tDist_ = Math.Sqrt((tp2.X - tp1.X) * (tp2.X - tp1.X) + (tp2.Y - tp1.Y) * (tp2.Y - tp1.Y));
// UI 显示转换后值
func.Params.ResultDoubles["PointDist_Distance"] = Math.Round(tDist_, 3);
func.Params.ResultDoubles["PointDist_DeltaX"] = Math.Round(tp2.X - tp1.X, 3);
func.Params.ResultDoubles["PointDist_DeltaY"] = Math.Round(tp2.Y - tp1.Y, 3);
tDist = tDist_;
}
}
}
}
var resultVarName = item.StringParams.TryGetValue("ResultVar", out var rv) && !string.IsNullOrEmpty(rv) ? rv : "点到点距离";
var resultVar = func.Params.Variables.FirstOrDefault(v => v.Name == resultVarName);
if (resultVar == null)
{
resultVar = new LocalVariableItem(resultVarName, "Double", 0.0);
System.Windows.Application.Current.Dispatcher.Invoke(() => func.Params.Variables.Add(resultVar));
}
resultVar.RawValue = dist;
// 转换后距离写入 TransOutVar(如果启用)
if (!string.IsNullOrEmpty(item.StringParams.TryGetValue("PtPt_TransOutVar", out var xov) ? xov : null))
{
var xfVar = func.Params.Variables.FirstOrDefault(v => v.Name == xov);
if (xfVar == null)
{
xfVar = new LocalVariableItem(xov, "Double", 0.0);
System.Windows.Application.Current.Dispatcher.Invoke(() => func.Params.Variables.Add(xfVar));
}
xfVar.RawValue = tDist.HasValue ? Math.Round(tDist.Value, 3) : double.NaN;
}
// 可视化:画连接线和标注
func.DrawCommands.Add(DrawCommand.Line(pos1.X, pos1.Y, pos2.X, pos2.Y, Colors.Lime, 2));
func.DrawCommands.Add(DrawCommand.FilledCircle(pos1.X, pos1.Y, 4, Colors.Cyan));
func.DrawCommands.Add(DrawCommand.FilledCircle(pos2.X, pos2.Y, 4, Colors.Cyan));
func.DrawCommands.Add(DrawCommand.TextBlock(
(pos1.X + pos2.X) / 2 + 5, (pos1.Y + pos2.Y) / 2 - 5,
$"{func.Params.ResultDoubles["PointDist_Distance"]:F3}", Colors.Lime, 48));
_ = func.RenderDrawAsync();
item.Flow.Completed = true;
return true;
}
}
}

View File

@ -204,6 +204,7 @@ namespace PLCSharp.VVMs.Vision
try
{
Params = value != null ? JsonSerializer.Deserialize<VisionParams>(value, JsonOptions.Default) ?? new VisionParams() : new VisionParams(); // 自动反序列化
CleanInvalidVariableValues(); // 清洗历史残留的 NaN / ±Infinity,避免脏数据污染后续流程
}
catch (global::System.Exception)
{
@ -212,6 +213,20 @@ namespace PLCSharp.VVMs.Vision
}
}
/// <summary>
/// 清洗局部变量表中非有限的 double 值(NaN / ±Infinity),重置为 0。
/// </summary>
private void CleanInvalidVariableValues()
{
foreach (var v in Params.Variables)
{
if (v.VarType == "Double" && v.RawValue is double d && !double.IsFinite(d))
{
v.RawValue = 0.0;
}
}
}
private ObservableCollection<VisionFlow> _VisionFlows = [];
/// <summary>
@ -386,8 +401,7 @@ namespace PLCSharp.VVMs.Vision
[VisionFlowType.灰度模板匹配] = new GrayTemplateMatchHandler(),
[VisionFlowType.SIFT匹配] = new SiftMatchHandler(),
[VisionFlowType.矩阵生成] = new MatrixGenHandler(),
[VisionFlowType.点到点距离] = new PointToPointDistanceHandler(),
[VisionFlowType.点到线距离] = new PointToLineDistanceHandler(),
[VisionFlowType.距离] = new DistanceHandler(),
[VisionFlowType.卡尺找圆] = new CaliperFindCircleHandler(),
[VisionFlowType.卡尺找旋转矩形] = new CaliperFindRectHandler(),
[VisionFlowType.清除绘制] = new ClearDrawHandler(),

View File

@ -113,10 +113,7 @@
灰度模板匹配 = 40,
[FlowCategory("算法")]
点到点距离 = 41,
[FlowCategory("算法")]
点到线距离 = 45,
距离 = 41,
[FlowCategory("算法")]
SIFT匹配 = 42,