76 lines
3.3 KiB
C#
76 lines
3.3 KiB
C#
using OpenCvSharp;
|
|
|
|
namespace PLCSharp.VVMs.Vision.VisionFlowHandler
|
|
{
|
|
/// <summary>
|
|
/// 坐标转换公共辅助方法
|
|
/// </summary>
|
|
public static class TransformHelper
|
|
{
|
|
/// <summary>
|
|
/// 应用 2x3 或 3x3 仿射/透视矩阵变换一个点
|
|
/// </summary>
|
|
public static Point2f Apply(Mat m, double px, double py)
|
|
{
|
|
if (m.Rows == 2)
|
|
return new Point2f(
|
|
(float)(px * m.At<double>(0, 0) + py * m.At<double>(0, 1) + m.At<double>(0, 2)),
|
|
(float)(px * m.At<double>(1, 0) + py * m.At<double>(1, 1) + m.At<double>(1, 2)));
|
|
double w = px * m.At<double>(2, 0) + py * m.At<double>(2, 1) + m.At<double>(2, 2);
|
|
if (Math.Abs(w) < 1e-10) return new Point2f(0, 0);
|
|
return new Point2f(
|
|
(float)((px * m.At<double>(0, 0) + py * m.At<double>(0, 1) + m.At<double>(0, 2)) / w),
|
|
(float)((px * m.At<double>(1, 0) + py * m.At<double>(1, 1) + m.At<double>(1, 2)) / w));
|
|
}
|
|
|
|
/// <summary>
|
|
/// 从系统变量表中读取矩阵
|
|
/// </summary>
|
|
public static Mat? GetTransformMat(VisionFunction func, VisionFlow item, string paramKey)
|
|
{
|
|
if (!item.StringParams.TryGetValue(paramKey, out var name) || string.IsNullOrEmpty(name)) return null;
|
|
var sv = func.GlobalModel.VariablesModel.SystemVariables.FirstOrDefault(v => v.Name == name);
|
|
if (sv?.Value == null) return null;
|
|
return MatExtension.DeserializeAffineMat((string)sv.Value);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 写入转换后变量
|
|
/// </summary>
|
|
public static void WriteTransVar(VisionFunction func, VisionFlow item, string paramKey, string defaultName, string varType, object value)
|
|
{
|
|
var vn = item.StringParams.TryGetValue(paramKey, out var ov) && !string.IsNullOrEmpty(ov) ? ov : null;
|
|
if (vn == null) return;
|
|
var v = func.Params.Variables.FirstOrDefault(v => v.Name == vn);
|
|
if (v == null)
|
|
{
|
|
v = new LocalVariableItem(vn, varType, value);
|
|
System.Windows.Application.Current.Dispatcher.Invoke(() => func.Params.Variables.Add(v));
|
|
}
|
|
else
|
|
v.RawValue = value;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 标准坐标转换流程:读矩阵 → 变换点 → 覆盖 ResultDoubles → 写 TransOutVar
|
|
/// </summary>
|
|
public static Point2f ExecuteTransform(VisionFunction func, VisionFlow item,
|
|
string enableKey, string matKey, string outVarKey, string outVarDefault, string outVarType,
|
|
object outVarValue, Action<double, double> updateResultDoubles,
|
|
double x, double y)
|
|
{
|
|
if (!item.BoolParams.TryGetValue(enableKey, out bool enabled) || !enabled)
|
|
return new Point2f((float)x, (float)y);
|
|
|
|
using var m = GetTransformMat(func, item, matKey);
|
|
if (m == null) return new Point2f((float)x, (float)y);
|
|
|
|
var pt = Apply(m, x, y);
|
|
double xfX = Math.Round(pt.X, 3), xfY = Math.Round(pt.Y, 3);
|
|
updateResultDoubles(xfX, xfY);
|
|
WriteTransVar(func, item, outVarKey, outVarDefault, outVarType, outVarValue);
|
|
return new Point2f((float)xfX, (float)xfY);
|
|
}
|
|
}
|
|
}
|