#include#include #include #include using namespace cv; int main() { Mat srcImage = imread("XXX.jpg"); //原图 Mat tempImage = imread("xxx.jpg"); //模板图像 Mat resultImage; //结果图像 int resultImage_rows = srcImage.rows - tempImage.rows + 1; //结果图像的行数:W-w+1,W:原图像的行数,w:模板图像的行数 int resultImage_cols = srcImage.cols - tempImage.cols + 1; //结果图像的列数:H-h+1,H:原图像的列数,h:模板图像的列数 resultImage.create(resultImage_rows, resultImage_cols, CV_32FC1); //结果图像必须为单通道32位浮点型 //TM_SQDIFF:平方差匹配法 TM_SQDIFF_NORMED:归一化平方差匹配法 //TM_CCORR:相关匹配法 M_CCORR_NORMED:归一化相关匹配法 TM_CCOEFF:系数匹配法 TM_CCOEFF_NORMED:化相关系数匹配法 int method = TM_CCOEFF_NORMED; matchTemplate(srcImage, tempImage, resultImage, method); //模板匹配 normalize(resultImage, resultImage, 0, 1, NORM_MINMAX, -1, Mat()); //归一化处理 double minValue, maxValue; Point minLocation, maxLocation, matchLocation; minMaxLoc(resultImage, &minValue, &maxValue, &minLocation, &maxLocation, Mat()); //在resultImage中矩阵的每一个点的亮度表示与模板T的匹配程度 if (method == TM_SQDIFF || method == TM_SQDIFF_NORMED) //越小越匹配 { matchLocation = minLocation; //匹配图像的左上角 } else //越大越匹配 { matchLocation = maxLocation; } //在原图上匹配区域画矩形 rectangle(srcImage, matchLocation, Point(matchLocation.x + tempImage.cols, matchLocation.y + tempImage.rows), Scalar(0, 0, 255), 2, 8, 0); std::cout << "左上角坐标:"<



