用OpenCVSharp 4.5跑一遍 OpenCV 官方教程
原官方教程链接:OpenCV: Template Matching
核心函数:matchTemplate(), minMaxLoc()
using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class tutorial22 : ITutorial
{
static Mat img = new Mat();
static Mat templ = new Mat();
static Mat result = new Mat();
static Mat mask = new Mat();
const string image_window = "Source Image";
const string result_window = "Result window";
static int match_method;
static bool use_mask;
static int max_Trackbar = 5;
public void Run()
{
img = Cv2.ImRead("I:\\csharp\\images\\lena.png",ImreadModes.Color);
templ = Cv2.ImRead("I:\\csharp\\images\\template_lena.png",ImreadModes.Color);
mask = Cv2.ImRead("I:\\csharp\\images\\mask_lena.png",ImreadModes.Grayscale);
if (img.Empty() || templ.Empty())
return;
if(!mask.Empty())
{
use_mask = true;
mask.ConvertTo(mask, MatType.CV_8UC1);
}
Cv2.NamedWindow(image_window, WindowFlags.AutoSize);
Cv2.NamedWindow(result_window, WindowFlags.AutoSize);
Cv2.NamedWindow("Template", WindowFlags.AutoSize);
Cv2.NamedWindow("Mask", WindowFlags.AutoSize);
const string trackbar_label = "Method: \r\n 0: SQDIFF \r\n 1: SQDIFF NORMED \r\n 2: TM CCORR \r\n 3: TM CCORR NORMED \r\n 4: TM COEFF \r\n 5: TM COEFF NORMED";
Cv2.CreateTrackbar(trackbar_label, image_window, ref match_method, max_Trackbar, MatchingMethod);
MatchingMethod(0, IntPtr.Zero);
Cv2.WaitKey(0);
}
static void MatchingMethod(int pos, IntPtr userData)
{
Mat img_display = new Mat();
img.CopyTo(img_display);
int result_cols = img.Cols - templ.Cols + 1;
int result_rows = img.Rows - templ.Rows + 1;
result.Create(result_rows, result_cols, MatType.CV_32FC1);
bool method_accepts_mask = ( TemplateMatchModes.SqDiff == (TemplateMatchModes)match_method || (TemplateMatchModes)match_method == TemplateMatchModes.CCorrNormed);
if (use_mask && method_accepts_mask)
{
Cv2.MatchTemplate(img, templ, result, (TemplateMatchModes)match_method, mask);
}
else
{
Cv2.MatchTemplate(img, templ, result, (TemplateMatchModes)match_method);
}
Cv2.Normalize(result, result, 0, 1, NormTypes.MinMax, -1, null);
double minVal; double maxVal; Point minLoc; Point maxLoc;
Point matchLoc;
Cv2.MinMaxLoc(result, out minVal, out maxVal, out minLoc, out maxLoc, null);
if ((TemplateMatchModes)match_method == TemplateMatchModes.SqDiff || (TemplateMatchModes)match_method == TemplateMatchModes.SqDiffNormed)
{ matchLoc = minLoc; }
else
{ matchLoc = maxLoc; }
Scalar color = new Scalar(0, 0, 0);
Cv2.Rectangle(img_display, matchLoc, new Point(matchLoc.X + templ.Cols, matchLoc.Y + templ.Rows), new Scalar(0, 0, 0), 2, LineTypes.Link8, 0);
Cv2.Rectangle(result, matchLoc, new Point(matchLoc.X + templ.Cols, matchLoc.Y + templ.Rows), new Scalar(0, 0, 0), 2, LineTypes.Link8, 0);
Cv2.ImShow(image_window, img_display);
Cv2.ImShow(result_window, result);
Cv2.ImShow("Template", templ);
Cv2.ImShow("Mask", mask);
}
}
}