using OpenCvSharp;
using OpenCvSharp.Extensions;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using static System.Net.Mime.MediaTypeNames;
namespace OpenCvSharp_Demo
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
// 读取输入图像和模板图像
Mat srcImage = new Mat("1.jpg");
Mat tempImage = new Mat("2.jpg");
Cv2.ImShow("srcImage", srcImage);
Cv2.ImShow("tempImage", tempImage);
// 创建用于存储模板和匹配结果的图像
Mat result = new Mat();
// 使用模板匹配方法进行匹配,这里使用归一化相关系数匹配法
Cv2.MatchTemplate(srcImage, tempImage, result, TemplateMatchModes.CCoeffNormed);
// 获取匹配结果中的最小值、最大值以及对应的位置
double minVal, maxVal;
OpenCvSharp.Point minLoc, maxLoc;
Cv2.MinMaxLoc(result, out minVal, out maxVal, out minLoc, out maxLoc);
// 获取最佳匹配的位置
OpenCvSharp.Point matchLoc = maxLoc;
// 在输入图像上用红色矩形框标记匹配的位置
Cv2.Rectangle(srcImage, matchLoc, new OpenCvSharp.Point(matchLoc.X + tempImage.Cols, matchLoc.Y + tempImage.Rows), Scalar.Red, 2);
pictureBox1.Image = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(srcImage);
}
}
}