plcsharp/PLCSharpWpf/VVMs/Vision/VisionFlowHandler/Algorithm/XFeatMatchHandler.cs
2026-07-23 03:32:21 +08:00

407 lines
19 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using OpenCvSharp;
using Microsoft.ML.OnnxRuntime;
using Microsoft.ML.OnnxRuntime.Tensors;
namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
{
public class XFeatMatchHandler : IVisionFlowHandler
{
public VisionFlowType Type => VisionFlowType.XFeat匹配;
// 全局共享 session(只加载一次)
private static InferenceSession? _session;
private static readonly object _lock = new();
private static readonly string ModelPath = "Models/xfeat.onnx";
private static InferenceSession GetSession()
{
if (_session == null)
{
lock (_lock)
{
_session ??= new InferenceSession(ModelPath);
}
}
return _session;
}
// 特征点结构
private struct XFeatPoint(int x, int y, float score, float theta, float[] desc)
{
public int X = x;
public int Y = y;
public float Score = score;
public float Theta = theta;
public float[] Desc = desc;
}
public bool Execute(VisionFunction func, VisionFlow item)
{
var src = func.Src;
if (src == null || src.Empty()) { item.Flow.FailMessage = "请先获取图片!"; return false; }
// ===== 1. 参数 =====
string roiShape = item.StringParams.TryGetValue("ROIShape", out var rs)
&& !string.IsNullOrEmpty(rs) ? rs : "矩形";
if (!item.DoubleParams.TryGetValue("TemplateCenterX", out double centerX) ||
!item.DoubleParams.TryGetValue("TemplateCenterY", out double centerY) ||
!item.DoubleParams.TryGetValue("Width", out double imgW) ||
!item.DoubleParams.TryGetValue("Height", out double imgH))
{ item.Flow.FailMessage = "模板未配置,请先画选区截取模板!"; return false; }
double templateW, templateH;
switch (roiShape)
{
case "矩形":
if (!item.DoubleParams.TryGetValue("TemplateLeft", out double tLeft) ||
!item.DoubleParams.TryGetValue("TemplateTop", out double tTop) ||
!item.DoubleParams.TryGetValue("TemplateWidth", out templateW) ||
!item.DoubleParams.TryGetValue("TemplateHeight", out templateH))
{ 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.FailMessage = "旋转矩形模板参数缺失!"; return false; }
break;
case "圆形":
if (!item.DoubleParams.TryGetValue("TemplateRadius", out double radius))
{ item.Flow.FailMessage = "圆形模板参数缺失!"; return false; }
templateW = radius * 2; templateH = radius * 2;
break;
default:
item.Flow.FailMessage = $"不支持的 ROI 形状:{roiShape}"; return false;
}
float matchThresh = (float)(item.DoubleParams.TryGetValue("MatchThresh", out double mt) ? mt : 0.6);
float detThresh = (float)(item.DoubleParams.TryGetValue("DetectThresh", out double dt) ? dt : 0.01);
int topK = item.IntParams.TryGetValue("TopK", out int tk) ? Math.Clamp(tk, 64, 8192) : 4096;
int maxDim = item.IntParams.TryGetValue("MaxDim", out int md) ? Math.Clamp(md, 240, 1200) : 640;
string templateName = item.StringParams.TryGetValue("TemplateName", out var tn)
&& !string.IsNullOrEmpty(tn) ? tn : "XFeat_Template";
string posVarName = item.StringParams.TryGetValue("XFeatMatch_PosVar", out var pn)
&& !string.IsNullOrEmpty(pn) ? pn : "XFeat匹配_Pos";
string offsetVarName = item.StringParams.TryGetValue("XFeatMatch_OffsetVar", out var ov)
&& !string.IsNullOrEmpty(ov) ? ov : "XFeat匹配_Offset";
// ===== 资源 =====
Mat template = null;
try
{
// ===== 2. 加载模板(黑背景原图大小) =====
template = Mat.Zeros((int)imgH, (int)imgW, MatType.CV_8UC3);
var existing = func.LocalImageDatas.FirstOrDefault(m => m.Name == templateName);
if (existing?.Mat == null || existing.Mat.Empty())
{
item.Flow.FailMessage = "模板提取失败,请先画选区截取模板!";
return false;
}
if (roiShape == "旋转矩形")
{
if (!item.DoubleParams.TryGetValue("TemplateBBoxLeft", out double bbx) ||
!item.DoubleParams.TryGetValue("TemplateBBoxTop", out double bby) ||
!item.DoubleParams.TryGetValue("TemplateBBoxWidth", out double bbw) ||
!item.DoubleParams.TryGetValue("TemplateBBoxHeight", out double bbh))
{ item.Flow.FailMessage = "旋转矩形模板参数缺失!"; return false; }
using var cloneMat = existing.Mat.Clone();
template[new OpenCvSharp.Rect((int)bbx, (int)bby, (int)bbw, (int)bbh)] = cloneMat;
}
else
{
double left = centerX - templateW / 2.0;
double top = centerY - templateH / 2.0;
OpenCvSharp.Rect roi = new((int)left, (int)top, (int)templateW, (int)templateH);
using var cloneMat = existing.Mat.Clone();
template[roi] = cloneMat;
}
// ===== 3. 加载 ONNX 模型 =====
var session = GetSession();
// ===== 4. 特征提取 =====
var tplFeats = ExtractFeatures(session, template, maxDim, detThresh, topK);
if (tplFeats.Length < 4)
{ item.Flow.FailMessage = $"模板特征点不足({tplFeats.Length} < 4)"; return false; }
var srcFeats = ExtractFeatures(session, src, maxDim, detThresh, topK);
if (srcFeats.Length < 4)
{ 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.FailMessage = "匹配点不足,定位失败!"; return false; }
// ===== 6. 结果 =====
double matchX = result.Value.X;
double matchY = result.Value.Y;
double deltaAngle = result.Value.Angle;
double offsetX = matchX - centerX;
double offsetY = matchY - centerY;
func.Params.ResultDoubles["MatchPosX"] = Math.Round(matchX, 2);
func.Params.ResultDoubles["MatchPosY"] = Math.Round(matchY, 2);
func.Params.ResultDoubles["MatchAngle"] = Math.Round(deltaAngle, 2);
func.Params.ResultDoubles["XFeatMatch_OffsetX"] = Math.Round(offsetX, 2);
func.Params.ResultDoubles["XFeatMatch_OffsetY"] = Math.Round(offsetY, 2);
func.Params.ResultDoubles["XFeatMatch_Angle"] = Math.Round(deltaAngle, 2);
func.Params.ResultDoubles["XFeatMatch_MatchCount"] = result.Value.Matches;
func.Params.ResultDoubles["XFeatMatch_Inliers"] = result.Value.Inliers;
func.Params.ResultDoubles["XFeatMatch_Score"] = Math.Round((double)result.Value.Inliers / Math.Max(1, result.Value.Matches) * 100, 1);
// ===== 7. 局部变量 =====
var posVar = func.Params.Variables.FirstOrDefault(v => v.Name == posVarName);
if (posVar == null)
{
posVar = new LocalVariableItem(posVarName, "Pos", new Pos());
System.Windows.Application.Current.Dispatcher.Invoke(() => func.Params.Variables.Add(posVar));
}
posVar.RawValue = new Pos(Math.Round(matchX, 2), Math.Round(matchY, 2), 0, Math.Round(deltaAngle, 2));
var offVar = func.Params.Variables.FirstOrDefault(v => v.Name == offsetVarName);
if (offVar == null)
{
offVar = new LocalVariableItem(offsetVarName, "Pos", new Pos());
System.Windows.Application.Current.Dispatcher.Invoke(() => func.Params.Variables.Add(offVar));
}
offVar.RawValue = new Pos(Math.Round(offsetX, 2), Math.Round(offsetY, 2), 0, Math.Round(deltaAngle, 2));
// ===== 8. 可视化 =====
var cyan = System.Windows.Media.Colors.Cyan;
var lime = System.Windows.Media.Colors.Lime;
var yellow = System.Windows.Media.Color.FromArgb(180, 255, 255, 0);
// WPF Y轴向下,绘制时角度取反使视觉方向一致
double rad = -deltaAngle * Math.PI / 180.0;
double cosA = Math.Cos(rad), sinA = Math.Sin(rad);
double hw0 = templateW / 2.0, hh0 = templateH / 2.0;
var corners = new (double x, double y)[]
{
(-hw0, -hh0), (hw0, -hh0), (hw0, hh0), (-hw0, hh0)
};
var polyPts = corners.Select(c => new System.Windows.Point(
matchX + c.x * cosA - c.y * sinA,
matchY + c.x * sinA + c.y * cosA)).ToArray();
func.DrawCommands.Add(DrawCommand.Polygon(polyPts, cyan, 3));
func.DrawCommands.Add(DrawCommand.FilledCircle(matchX, matchY, 4, cyan));
// 绘制匹配上的特征点(内点)
if (result.Value.InlierPts.Length > 0)
{
foreach (var pt in result.Value.InlierPts)
{
func.DrawCommands.Add(DrawCommand.FilledCircle(pt.X, pt.Y, 3, yellow));
}
}
func.DrawCommands.Add(DrawCommand.TextBlock(10, 60,
$"x:{matchX:F1} y:{matchY:F1} a:{deltaAngle:F1} deg", lime, 18));
func.DrawCommands.Add(DrawCommand.TextBlock(10, 84,
$"offset: ({offsetX:+0.0;-0.0}, {offsetY:+0.0;-0.0}) inliers:{result.Value.Inliers}/{result.Value.Matches}", lime, 14));
_ = func.RenderDrawAsync();
item.Flow.Done = true;
return true;
}
finally
{
template?.Dispose();
}
}
// ===== ONNX 特征提取 =====
private static XFeatPoint[] ExtractFeatures(InferenceSession session, Mat img,
int maxDim, float detThresh, int topK)
{
float scale = Math.Min((float)maxDim / img.Width, (float)maxDim / img.Height);
int newW = (int)(img.Width * scale / 32) * 32;
int newH = (int)(img.Height * scale / 32) * 32;
float scaleW = (float)newW / img.Width;
float scaleH = (float)newH / img.Height;
using Mat resized = new();
Cv2.Resize(img, resized, new Size(newW, newH), 0, 0, InterpolationFlags.Linear);
// XFeat 模型要求 3 通道输入
if (resized.Channels() == 1)
Cv2.CvtColor(resized, resized, ColorConversionCodes.GRAY2BGR);
// 预计算梯度方向(用于特征点方向)
MatExtension.BGR2GRAY(resized, out Mat grayRs);
using Mat dx = new(), dy = new();
Cv2.Sobel(grayRs, dx, MatType.CV_32F, 1, 0, 3, 1, 0, BorderTypes.Replicate);
Cv2.Sobel(grayRs, dy, MatType.CV_32F, 0, 1, 3, 1, 0, BorderTypes.Replicate);
var input = new DenseTensor<float>([1, 3, newH, newW]);
unsafe
{
byte* pSrc = (byte*)resized.Data;
int step = (int)resized.Step();
for (int y = 0; y < newH; y++)
for (int x = 0; x < newW; x++)
{
int idx = y * step + x * 3;
input[0, 0, y, x] = pSrc[idx + 2] / 255f;
input[0, 1, y, x] = pSrc[idx + 1] / 255f;
input[0, 2, y, x] = pSrc[idx + 0] / 255f;
}
}
using var outputs = session.Run([NamedOnnxValue.CreateFromTensor("input", input)]);
var descTensor = outputs[0].AsTensor<float>(); // [1, 64, H/8, W/8] descriptors
var kptLogits = outputs[1].AsTensor<float>(); // [1, 65, H/8, W/8] keypoint logits
// output[2] = reliability, not used here
int Hc = kptLogits.Dimensions[2]; // coarse grid (H/8)
int Wc = kptLogits.Dimensions[3];
int Hf = Hc * 8, Wf = Wc * 8;
// 手动实现 get_kpts_heatmap: softmax 65ch → 取前64ch → 重排为 [H*8, W*8]
var heatmap = new float[Hf * Wf];
for (int h = 0; h < Hc; h++)
{
for (int w = 0; w < Wc; w++)
{
// softmax
float maxVal = float.MinValue;
for (int c = 0; c < 65; c++)
maxVal = Math.Max(maxVal, kptLogits[0, c, h, w]);
double sum = 0;
for (int c = 0; c < 65; c++)
sum += Math.Exp(kptLogits[0, c, h, w] - maxVal);
// 前 64 通道 → 8x8 子块
for (int sy = 0; sy < 8; sy++)
for (int sx = 0; sx < 8; sx++)
{
int c = sy * 8 + sx;
float prob = (float)(Math.Exp(kptLogits[0, c, h, w] - maxVal) / sum);
heatmap[(h * 8 + sy) * Wf + (w * 8 + sx)] = prob;
}
}
}
// 在全分辨率热力图上做 NMS 提取特征点
int halfNms = 4;
var pts = new List<XFeatPoint>();
for (int y = halfNms; y < Hf - halfNms; y++)
{
for (int x = halfNms; x < Wf - halfNms; x++)
{
float score = heatmap[y * Wf + x];
if (score < detThresh) continue;
bool isMax = true;
for (int yy = -halfNms; yy <= halfNms && isMax; yy++)
for (int xx = -halfNms; xx <= halfNms; xx++)
if ((xx != 0 || yy != 0) && score < heatmap[(y + yy) * Wf + (x + xx)])
{ isMax = false; break; }
if (!isMax) continue;
// 描述子坐标 (对应到网格)
int dgy = y / 8, dgx = x / 8;
var desc = new float[64];
for (int c = 0; c < 64; c++)
desc[c] = descTensor[0, c, dgy, dgx];
// 计算梯度方向(在缩放后的图像坐标上)
float gxVal = 0, gyVal = 0;
if (x < newW && y < newH)
{
unsafe
{
float* pDx = (float*)dx.Data;
float* pDy = (float*)dy.Data;
int step = (int)(dx.Step() / sizeof(float));
gxVal = pDx[y * step + x];
gyVal = pDy[y * step + x];
}
}
float theta = (float)(Math.Atan2(gyVal, gxVal) * 180.0 / Math.PI);
pts.Add(new XFeatPoint(
(int)(x / scaleW), (int)(y / scaleH), score, theta, desc));
}
}
pts.Sort((a, b) => b.Score.CompareTo(a.Score));
return pts.Take(Math.Min(topK, pts.Count)).ToArray();
}
// ===== 匹配 + 定位 =====
private record struct LocateResult(double X, double Y, double Angle, int Matches, int Inliers, Point2f[] InlierPts);
private static LocateResult? MatchAndLocate(XFeatPoint[] tpl, XFeatPoint[] src,
double cx, double cy, double tw, double th, float matchThresh)
{
if (tpl.Length < 4 || src.Length < 4) return null;
var matches = new List<(int ti, int si)>();
for (int ti = 0; ti < tpl.Length; ti++)
{
float best = float.MaxValue;
int bestSi = -1;
for (int si = 0; si < src.Length; si++)
{
float dot = 0, nt = 0, ns = 0;
for (int ch = 0; ch < 64; ch++)
{
dot += tpl[ti].Desc[ch] * src[si].Desc[ch];
nt += tpl[ti].Desc[ch] * tpl[ti].Desc[ch];
ns += src[si].Desc[ch] * src[si].Desc[ch];
}
float dist = 1 - dot / (float)(Math.Sqrt(nt) * Math.Sqrt(ns) + 1e-10f);
if (dist < best) { best = dist; bestSi = si; }
}
if (bestSi >= 0 && best < matchThresh)
matches.Add((ti, bestSi));
}
if (matches.Count < 4) return null;
var srcPts = matches.Select(m => new Point2f(tpl[m.ti].X, tpl[m.ti].Y)).ToArray();
var dstPts = matches.Select(m => new Point2f(src[m.si].X, src[m.si].Y)).ToArray();
using Mat mask = new();
using Mat H = Cv2.FindHomography(
InputArray.Create(srcPts), InputArray.Create(dstPts),
HomographyMethods.Ransac, 3.0, mask);
if (H == null || H.Empty()) return null;
int inliers = Cv2.CountNonZero(mask);
if (inliers < 4) return null;
// 收集内点(搜索图中匹配上的特征点)
var inlierPts = new List<Point2f>();
for (int i = 0; i < mask.Rows; i++)
if (mask.At<byte>(i, 0) != 0)
inlierPts.Add(dstPts[i]);
double[] c = { cx, cy, 1.0 };
double tx = H.At<double>(0, 0) * c[0] + H.At<double>(0, 1) * c[1] + H.At<double>(0, 2);
double ty = H.At<double>(1, 0) * c[0] + H.At<double>(1, 1) * c[1] + H.At<double>(1, 2);
double tz = H.At<double>(2, 0) * c[0] + H.At<double>(2, 1) * c[1] + H.At<double>(2, 2);
if (Math.Abs(tz) > 1e-10) { tx /= tz; ty /= tz; }
double angle = Math.Atan2(H.At<double>(1, 0), H.At<double>(0, 0)) * 180.0 / Math.PI;
angle = -angle; // OpenCV 坐标系 Y 向下,取反使逆时针旋转为正角度
return new LocateResult(tx, ty, angle, matches.Count, inliers, [.. inlierPts]);
}
}
}