54 lines
2.8 KiB
C#
54 lines
2.8 KiB
C#
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);
|
|
|
|
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(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,
|
|
$"{dist:F3}", Colors.Lime, 16));
|
|
|
|
item.Flow.Done = true;
|
|
return true;
|
|
}
|
|
}
|
|
}
|