258 lines
12 KiB
C#
258 lines
12 KiB
C#
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));
|
||
}
|
||
}
|
||
}
|
||
}
|