模板匹配的概念与原理
模板匹配是在一幅图像中寻找与另一幅模板图像最匹配(相似)部分的技术,在OpenCV中,模板匹配由函数MatchTemplate()函数实现。需要注意的是,模板匹配不是基于直方图的,而是通过在输入图像上滑动图像块,对实际的图像块和输入图像进行匹配的一种方法。
如图,通过一个人脸图像模板,在整个输入图像上移动这张脸,寻找和这张脸相似的最优匹配。
MatchTemplate()函数
MatchTemplate()用于匹配出和模板重叠的图像区域,函数原型:
void MatchTemplate(InputArray image, InputArray telp1, outputArray result, int method)
- 第一个参数:待搜索的图像,需要是8位或32位浮点型图像。
- 第二个参数:搜索模板,需要和源图像有一样的数据类型,且尺寸不能大于源图像。
- 第三个参数:比较结果的映射图像,必须是单通道32位浮点型图像。如果图像尺寸是W*H,temp1是w*h,则此参数一定是(W-w+1)*(H-h+1).
- 第四个参数:int类型的method,指定的匹配方法,有6种方法可以使用:
1、平方差匹配法method=TM_SQDIFF
这类方法是用平方差来匹配,最好匹配为0,匹配越差,则匹配值越大。
2、归一化平方差匹配法method=TM_SQDIFF_NORMED
3、相关匹配法method=TM_CCORR
这类方法采用模板和图像件的乘法操作,所以较大的数表示匹配程度较高,0表示最坏的匹配结果。
4、归一化相关匹配法method=TM_CCORR_NORMED
5、系数匹配法method=RM_CCOEFF
这类方法将模板对其均值的相对值与图像对其均值的相关值进行匹配,1表示完美匹配,-1表示较差的匹配。0表示没有任何相关性。
其中:
6、归一化系数匹配法method=RM_CCOEFF_NORMED
通常,从简单的测量(平方差)到更复杂的测量(相关系数),我们可获得越来越准确的匹配,但同时也会以越来越大的计算量为代价。
代码示例:
#include <iostream>
#include <opencv2/opencv.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
using namespace std;
using namespace cv;
int main() {
Mat g_srcImage, g_templateImage, g_resultImage;
int g_nMatchMethod = 1;
g_srcImage = imread("/Users/dwz/Desktop/cpp/person.jpg", 1);
g_templateImage = imread("/Users/dwz/Desktop/cpp/face.jpg", 1);
Mat srcImage;
g_srcImage.copyTo(srcImage);
int resultImage_cols, resultImage_rows;
resultImage_cols = g_srcImage.cols - g_templateImage.cols +1;
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());
matchLocation = minLocation;
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);
imwrite("result.jpg", g_resultImage*255);
imwrite("result_src.jpg", srcImage);
return 0;
}
输入:
输出: