模板匹配是一项在一幅图像中寻找与另一幅模板图像最匹配(相似)部分的技术。在OpenCV中,模板匹配由MatchTemplate()函数完成。模板匹配不是基于直方图的 (关于图像直方图,如果有时间会进行专门的介绍) ,而是通过在输入图像上滑动图像块,对实际的图像块和输入图像进行匹配的一种匹配方法。
MatchTemplate()函数用于匹配出和模板重叠的图像区域。
void matchTemplate(InputArray image,
InputArray temp1,
OutputArray result,
int method )
下面编写程序,使用不同的模板匹配方法对猪猪侠的眼睛进行检测。
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
using namespace cv;
using namespace std;
#define WINDOW_NAME1 "【原始图片】"
#define WINDOW_NAME2 "【匹配窗口】"
Mat g_srcImage; Mat g_templateImage; Mat g_resultImage;
int g_nMatchMethod;
int g_nMaxTrackbarNum = 5;
void on_Matching(int, void*);
static void ShowHelpText();
int main()
{
system("color 1F");
ShowHelpText();
g_srcImage = imread("pig.jpg", 1);
g_templateImage = imread("pigeye.jpg", 1);
namedWindow(WINDOW_NAME1, CV_WINDOW_AUTOSIZE);
namedWindow(WINDOW_NAME2, CV_WINDOW_AUTOSIZE);
createTrackbar("方法", WINDOW_NAME1, &g_nMatchMethod, g_nMaxTrackbarNum, on_Matching);
on_Matching(0, 0);
waitKey(0);
return 0;
}
void on_Matching(int, void*)
{
Mat srcImage;
g_srcImage.copyTo(srcImage);
//初始化用于结果输出的矩阵
int resultImage_cols = g_srcImage.cols - g_templateImage.cols + 1;
int resultImage_rows = g_srcImage.rows - g_templateImage.rows + 1;
g_resultImage.create(resultImage_cols, resultImage_rows, CV_32FC1);
//进行匹配和标准化
matchTemplate(g_srcImage, g_templateImage, g_resultImage, g_nMatchMethod);
normalize(g_resultImage, g_resultImage, 0, 1, NORM_MINMAX, -1, Mat());
//定位最匹配的位置
double minValue; double maxValue; Point minLocation; Point maxLocation;
Point matchLocation;
minMaxLoc(g_resultImage, &minValue, &maxValue, &minLocation, &maxLocation, Mat());
//对于方法 SQDIFF 和 SQDIFF_NORMED, 越小的数值有着更高的匹配结果. 而其余的方法, 数值越大匹配效果越好
if (g_nMatchMethod == CV_TM_SQDIFF || g_nMatchMethod == CV_TM_SQDIFF_NORMED)
{
matchLocation = minLocation;
}
else
{
matchLocation = maxLocation;
}
//绘制出矩形,显示最终结果
rectangle(srcImage, matchLocation, Point(matchLocation.x + g_templateImage.cols, matchLocation.y + g_templateImage.rows), Scalar(0, 0, 255), 2, 8, 0);
rectangle(g_resultImage, matchLocation, Point(matchLocation.x + g_templateImage.cols, matchLocation.y + g_templateImage.rows), Scalar(0, 0, 255), 2, 8, 0);
imshow(WINDOW_NAME1, srcImage);
imshow(WINDOW_NAME2, g_resultImage);
}
static void ShowHelpText()
{
printf("\n\n ----------------------------------------------------------------------------\n");
printf("\n\t滑动条对应的方法数值说明: \n\n"
"\t\t方法【0】- 平方差匹配法(SQDIFF)\n"
"\t\t方法【1】- 归一化平方差匹配法(SQDIFF NORMED)\n"
"\t\t方法【2】- 相关匹配法(TM CCORR)\n"
"\t\t方法【3】- 归一化相关匹配法(TM CCORR NORMED)\n"
"\t\t方法【4】- 相关系数匹配法(TM COEFF)\n"
"\t\t方法【5】- 归一化相关系数匹配法(TM COEFF NORMED)\n");
}