c++ opencv 模板匹配matchTemplate

#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 << "左上角坐标:"<<matchLocation << std::endl;
	std::cout << "右下角坐标:" << Point(matchLocation.x + tempImage.cols, matchLocation.y + tempImage.rows) << std::endl;
	// 创建一个名为 "图片"窗口    
	namedWindow("图片", CV_WINDOW_NORMAL);
	//显示图像
	imshow("图片", srcImage); 
	waitKey(0);
	return 0;
}

你可能感兴趣的:(opencv,c++,计算机视觉)