用?OpenCVSharp 4.5?跑一遍?OpenCV官方教程
原OpenCV官方教程链接:OpenCV: AKAZE local features matching
using System;
using System.Collections.Generic;
using OpenCvSharp;
using OpenCvSharp.XFeatures2D;
namespace ConsoleApp1
{
class tutorial50:ITutorial
{
public void Run()
{
float inlier_threshold = 2.5f;
float nn_match_ratio = 0.8f;
Mat img1 = Cv2.ImRead(@"I:\csharp\images\graf1.png", ImreadModes.Grayscale);
Mat img2 = Cv2.ImRead(@"I:\csharp\images\graf3.png",ImreadModes.Grayscale);
//以下为 homography(文件H1to3p.xml)数据
double[,] data = {{7.6285898e-01,-2.9922929e-01,2.2567123e+02 },
{ 3.3443473e-01, 1.0143901e+00, -7.6999973e+01 },
{ 3.4663091e-04, -1.4364524e-05, 1.0000000e+00 }};
Mat homography = new Mat(3,3,MatType.CV_64F,data);
KeyPoint[] kpts1, kpts2;
Mat desc1 = new Mat(), desc2 = new Mat();
AKAZE akaz = AKAZE.Create();
akaz.DetectAndCompute(img1, null, out kpts1, desc1);
akaz.DetectAndCompute(img2, null, out kpts2, desc2);
BFMatcher matcher = new BFMatcher(NormTypes.Hamming);
DMatch[][] nn_matches = matcher.KnnMatch(desc1, desc2, 2);
List<KeyPoint> matched1 = new List<KeyPoint>(), matched2 = new List<KeyPoint>();
for (int i = 0; i < nn_matches.Length; i++)
{
DMatch first = nn_matches[i][0];
float dist1 = nn_matches[i][0].Distance;
float dist2 = nn_matches[i][1].Distance;
if (dist1 < nn_match_ratio * dist2)
{
matched1.Add( kpts1[first.QueryIdx]);
matched2.Add(kpts2[first.TrainIdx]);
}
}
List<DMatch> good_matches = new List<DMatch>();
List<KeyPoint> inliers1=new List<KeyPoint>(),
inliers2 = new List<KeyPoint>();
for (int i = 0; i < matched1.Count; i++)
{
Mat col = Mat.Ones(new Size(1, 3), MatType.CV_64F);
col.At<double>(0) = matched1[i].Pt.X;
col.At<double>(1) = matched1[i].Pt.Y;
col = homography * col;
col /= col.At<double>(2);
double dist = Math.Sqrt(Math.Pow(col.At<double>(0) - matched2[i].Pt.X, 2) +
Math.Pow(col.At<double>(1) - matched2[i].Pt.Y, 2));
if (dist < inlier_threshold)
{
int new_i = (int)inliers1.Count;
inliers1.Add(matched1[i]);
inliers2.Add(matched2[i]);
good_matches.Add(new DMatch(new_i, new_i, 0));
}
}
Mat res= new Mat();
Cv2.DrawMatches(img1, inliers1, img2, inliers2, good_matches, res);
Cv2.ImWrite("akaze_result.png", res);
double inlier_ratio = inliers1.Count / (double)matched1.Count;
Console.WriteLine( "A-KAZE Matching Results");
Console.WriteLine("*******************************" );
Console.WriteLine("# Keypoints 1:\t{0}" , kpts1.Length);
Console.WriteLine("# Keypoints 2:\t{0}", kpts2.Length);
Console.WriteLine("# Matches:\t{0}", matched1.Count);
Console.WriteLine("# Inliers:\t{0}", inliers1.Count);
Console.WriteLine("# Inliers Ratio:\t{0}" ,inlier_ratio );
Cv2.ImShow("result", res);
Cv2.WaitKey();
}
}
}
?
?
|