using OpenCvSharp;
namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
{
///
/// SIFT + FLANN + Homography 特征匹配定位。
/// 对纹理丰富的物体鲁棒,天然支持旋转和尺度变化。
///
public class SiftMatchHandler : IVisionFlowHandler
{
public VisionFlowType Type => VisionFlowType.SIFT匹配;
public bool Execute(VisionFunction func, VisionFlow item)
{
var src = func.Src;
if (src == null || src.Empty()) throw new Exception("请先获取图片!");
// ===== 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))
throw new Exception("模板未配置,请先画选区截取模板!");
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))
throw new Exception("矩形模板参数缺失!");
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))
throw new Exception("旋转矩形模板参数缺失!");
break;
case "圆形":
if (!item.DoubleParams.TryGetValue("TemplateRadius", out double radius))
throw new Exception("圆形模板参数缺失!");
templateW = radius * 2; templateH = radius * 2;
break;
default:
throw new Exception($"不支持的 ROI 形状:{roiShape}");
}
int nFeatures = item.IntParams.TryGetValue("NFeatures", out int nf) ? Math.Max(nf, 500) : 1000;
double minGoodRatio = item.DoubleParams.TryGetValue("MinGoodRatio", out double mgr)
? Math.Clamp(mgr, 0.01, 1.0) : 0.3;
int minMatches = item.IntParams.TryGetValue("MinMatches", out int mm) ? Math.Max(mm, 8) : 8;
string templateName = item.StringParams.TryGetValue("TemplateName", out var tn)
&& !string.IsNullOrEmpty(tn) ? tn : "SIFT_Template";
string posVarName = item.StringParams.TryGetValue("SiftMatch_PosVar", out var pn)
&& !string.IsNullOrEmpty(pn) ? pn : "SIFT匹配_Pos";
string offsetVarName = item.StringParams.TryGetValue("SiftMatch_OffsetVar", out var ov)
&& !string.IsNullOrEmpty(ov) ? ov : "SIFT匹配_Offset";
// ===== 资源 =====
Mat graySrc = null, grayTemplate = null;
Mat tplDesc = null, srcDesc = null;
Mat mask = null, H = null;
Mat template = null;
try
{
// ===== 2. 加载模板(黑背景原图大小,ROI 位置放模板内容) =====
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.ErrorState = "模板提取失败,请先画选区截取模板!";
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))
throw new Exception("旋转矩形模板参数缺失!");
OpenCvSharp.Rect bboxRoi = new((int)bbx, (int)bby, (int)bbw, (int)bbh);
using var cloneMat = existing.Mat.Clone();
template[bboxRoi] = 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. 灰度化 =====
graySrc = ToGray(src);
grayTemplate = ToGray(template);
// ===== 4. SIFT 特征检测 =====
var sift = SIFT.Create(nFeatures);
tplDesc = new Mat();
using Mat noMask = new();
sift.DetectAndCompute(grayTemplate, noMask, out KeyPoint[] tplKps, tplDesc);
srcDesc = new Mat();
sift.DetectAndCompute(graySrc, noMask, out KeyPoint[] srcKps, srcDesc);
if (tplKps.Length < 2 || srcKps.Length < 2)
throw new Exception($"特征点不足:模板 {tplKps.Length} 个,搜索图 {srcKps.Length} 个!");
// ===== 5. FLANN 匹配 + Lowe's ratio test =====
var matcher = new FlannBasedMatcher();
DMatch[][] knnMatches = matcher.KnnMatch(tplDesc, srcDesc, 2);
var goodMatches = knnMatches
.Where(m => m.Length >= 2 && m[0].Distance < minGoodRatio * m[1].Distance)
.Select(m => m[0])
.ToArray();
if (goodMatches.Length < minMatches)
{
goodMatches = knnMatches
.Where(m => m.Length >= 2 && m[0].Distance < 0.85 * m[1].Distance)
.Select(m => m[0])
.ToArray();
}
if (goodMatches.Length < 4)
throw new Exception($"优质匹配点不足({goodMatches.Length} < 4),请确认物体纹理充足!");
// ===== 6. RANSAC 单应性 =====
Point2f[] srcPts = goodMatches.Select(m => tplKps[m.QueryIdx].Pt).ToArray();
Point2f[] dstPts = goodMatches.Select(m => srcKps[m.TrainIdx].Pt).ToArray();
mask = new Mat();
H = Cv2.FindHomography(
InputArray.Create(srcPts), InputArray.Create(dstPts),
HomographyMethods.Ransac, 3.0, mask);
if (H == null || H.Empty())
throw new Exception("计算单应性矩阵失败!");
// ===== 7. 计算偏移和角度 =====
double h00 = H.At(0, 0), h01 = H.At(0, 1), h02 = H.At(0, 2);
double h10 = H.At(1, 0), h11 = H.At(1, 1), h12 = H.At(1, 2);
double h20 = H.At(2, 0), h21 = H.At(2, 1), h22 = H.At(2, 2);
double[] c = { centerX, centerY, 1.0 };
double tx = h00 * c[0] + h01 * c[1] + h02;
double ty = h10 * c[0] + h11 * c[1] + h12;
double tz = h20 * c[0] + h21 * c[1] + h22;
if (Math.Abs(tz) > 1e-10) { tx /= tz; ty /= tz; }
double deltaAngle = Math.Atan2(h10, h00) * 180.0 / Math.PI;
double offsetX = tx - centerX;
double offsetY = ty - centerY;
int inlierCount = Cv2.CountNonZero(mask);
double inlierRatio = (double)inlierCount / goodMatches.Length;
// ===== 8. 存储结果 =====
func.Params.ResultDoubles["MatchPosX"] = Math.Round(tx, 3);
func.Params.ResultDoubles["MatchPosY"] = Math.Round(ty, 3);
func.Params.ResultDoubles["MatchAngle"] = Math.Round(deltaAngle, 3);
func.Params.ResultDoubles["SiftMatch_OffsetX"] = Math.Round(offsetX, 3);
func.Params.ResultDoubles["SiftMatch_OffsetY"] = Math.Round(offsetY, 3);
func.Params.ResultDoubles["SiftMatch_Angle"] = Math.Round(deltaAngle, 3);
func.Params.ResultDoubles["SiftMatch_MatchCount"] = goodMatches.Length;
func.Params.ResultDoubles["SiftMatch_InlierRatio"] = Math.Round(inlierRatio, 3);
func.Params.ResultDoubles["SiftMatch_Score"] = Math.Round(inlierRatio * 100, 1);
// ===== 9. 局部变量 =====
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(tx, 3), Math.Round(ty, 3), 0, Math.Round(deltaAngle, 3));
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, 3), Math.Round(offsetY, 3), 0, Math.Round(deltaAngle, 3));
// ===== 10. 可视化 =====
Mat colorSrc = null;
if (func.Src.Channels() == 1)
{
colorSrc = new Mat();
Cv2.CvtColor(func.Src, colorSrc, ColorConversionCodes.GRAY2BGR);
func.Src = colorSrc;
}
// 画矩形边框
var corners = new Point2f[]
{
new((float)(centerX - templateW / 2.0), (float)(centerY - templateH / 2.0)),
new((float)(centerX + templateW / 2.0), (float)(centerY - templateH / 2.0)),
new((float)(centerX + templateW / 2.0), (float)(centerY + templateH / 2.0)),
new((float)(centerX - templateW / 2.0), (float)(centerY + templateH / 2.0))
};
var dstCorners = Cv2.PerspectiveTransform(corners, H);
Cv2.Polylines(func.Src,
[[.. dstCorners.Select(p => new Point((int)p.X, (int)p.Y))]],
true, Scalar.Magenta, 2);
Cv2.Circle(func.Src, (int)Math.Round(tx), (int)Math.Round(ty), 8, Scalar.Magenta, 2);
Cv2.Circle(func.Src, (int)Math.Round(tx), (int)Math.Round(ty), 3, Scalar.Magenta, -1);
string info = $"pos: ({tx:F1}, {ty:F1}) angle={deltaAngle:F1} | offs ({offsetX:F1}, {offsetY:F1})";
Cv2.PutText(func.Src, info, new Point(10, 100), HersheyFonts.HersheySimplex, 1.8, Scalar.Lime, 2);
Mat reMat = new();
Cv2.DrawMatches(template, tplKps, func.Src, srcKps, goodMatches, reMat);
func.Src = reMat;
colorSrc?.Dispose();
item.Flow.Done = true;
return true;
}
finally
{
graySrc?.Dispose();
grayTemplate?.Dispose();
tplDesc?.Dispose();
srcDesc?.Dispose();
mask?.Dispose();
H?.Dispose();
template?.Dispose();
}
}
private static Mat ToGray(Mat src)
{
if (src.Channels() == 1) return src.Clone();
var g = new Mat();
Cv2.CvtColor(src, g, ColorConversionCodes.BGR2GRAY);
return g;
}
}
}