天天看点

opencv3 实现模版匹配-matchTemplate函数

#include<opencv2/opencv.hpp>
#include<iostream>
#include<vector>

using namespace cv;
using namespace std;

int main()
{
	Mat g_findImage = imread("利利.jpg");
	Mat modeImage = imread("利利头像.jpg");
	imshow("【被查找的图像】", g_findImage);
	imshow("【模版图像】", modeImage);

	Mat findImage;
	g_findImage.copyTo(findImage);

	//创建输出图像,输出图像的宽度 = 被查找到额图像的宽度 - 模版图像的宽度 + 1, 高度同样符合
	Mat dstImage;
	dstImage.create(findImage.rows - modeImage.rows + 1, findImage.cols - modeImage.cols + 1, CV_32FC1);

	//进行模版匹配,首先是方式0(平方差匹配法)
	matchTemplate(findImage, modeImage, dstImage, 0);
	normalize(dstImage, dstImage, 0, 1, 32);

	//绘制矩形方便显示
	//首先是从得到的 输出矩阵中得到 最大或最小值(平方差匹配方式是越小越好,所以在这种方式下,找到最小位置)
	//找矩阵的最小位置的函数是 minMaxLoc函数
	Point minPoint;
	minMaxLoc(dstImage, 0, 0, &minPoint, 0);

	//开始正式绘制
	rectangle(findImage, minPoint, Point(minPoint.x + modeImage.cols, minPoint.y + modeImage.rows)
		, Scalar(theRNG().uniform(0, 255), theRNG().uniform(0, 255), theRNG().uniform(0, 255)), 3, 8);
	imshow("【匹配后的图像】", findImage);

	rectangle(dstImage, minPoint, Point(minPoint.x + modeImage.cols, minPoint.y + modeImage.rows)
		, Scalar(theRNG().uniform(0, 255), theRNG().uniform(0, 255), theRNG().uniform(0, 255)), 3, 8);
	imshow("【匹配后的计算过程图像】", dstImage);

	waitKey(0);

	return 0;
}
           
opencv3 实现模版匹配-matchTemplate函数