【效果展示】
原图
模板图
匹配结果:
【实现部分代码】
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using OpenCvSharp;
namespace FIRC
{
public partial class Form1 : Form
{
public Dictionary<string, TemplateMatchModes> tmm_dict = new Dictionary<string, TemplateMatchModes>();
public Mat src = null;//存储原图
public Mat template = Cv2.ImRead(Application.StartupPath+"\\images\\template.jpg");
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "(图片文件)*.*|*.bmp;*.jpg;*.jpeg;*.tiff;*.tiff;*.png"; ;
if (ofd.ShowDialog() == DialogResult.OK)
{
src= Cv2.ImRead(ofd.FileName);
var points = FIRCMatchTemplate.MatchTemplate(src,template,tmm_dict[comboBox1.Text],0.8f);
var resultMat = FIRCMatchTemplate.DrawImage(points,src.Clone(),template.Size());
pictureBox1.Image = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(resultMat);
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if(src!=null)
{
var points = FIRCMatchTemplate.MatchTemplate(src, template, tmm_dict[comboBox1.Text], 0.8f);
var resultMat = FIRCMatchTemplate.DrawImage(points, src.Clone(), template.Size());
pictureBox1.Image = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(resultMat);
}
}
private void Form1_Load(object sender, EventArgs e)
{
tmm_dict.Add("CCoeffNormed",TemplateMatchModes.CCoeffNormed);
tmm_dict.Add("CCoeff", TemplateMatchModes.CCoeff);
tmm_dict.Add("SqDiffNormed", TemplateMatchModes.SqDiffNormed);
tmm_dict.Add("SqDiff", TemplateMatchModes.SqDiff);
tmm_dict.Add("CCorrNormed", TemplateMatchModes.CCorrNormed);
tmm_dict.Add("CCorr", TemplateMatchModes.CCorr);
comboBox1.SelectedIndex = 0;
}
}
}
【测试环境】
vs2019,netframework4.7.2,opencvsharp4.8.0
【视频演示】
【演示源码下载地址】