模板匹配

来源:互联网 发布:dede分类目录源码 编辑:程序博客网 时间:2024/06/06 23:56
#include <iostream>
#include "opencv2/core/core.hpp"
#include "highgui.h"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/features2d/features2d.hpp"
#include "opencv2/imgproc/imgproc.hpp"  
#include "opencv2/highgui/highgui.hpp"  
using namespace cv;
using namespace std;
int main()
{
/*
Mat img = imread("目标1.jpg",0);
resize(img,img,Size(img.cols/5,img.rows/5));
equalizeHist(img,img); //直方图均衡化
GaussianBlur(img, img, Size(3, 3), 0, 0); //高斯模糊(Gaussian Blur)


threshold(img,img,100,255,CV_THRESH_BINARY);
imshow("show",img);
*/
Mat g_findImage = imread("目标1.jpg",0);
Mat modeImage = imread("模板1.png",0);
equalizeHist(g_findImage, g_findImage); //直方图均衡化
GaussianBlur(g_findImage, g_findImage, Size(3, 3), 0, 0); //高斯模糊(Gaussian Blur)
equalizeHist(modeImage, modeImage); //直方图均衡化
GaussianBlur(modeImage, modeImage, Size(3, 3), 0, 0); //高斯模糊(Gaussian Blur)
threshold(g_findImage, g_findImage, 100, 255, CV_THRESH_BINARY);
threshold(modeImage, modeImage, 100, 255, CV_THRESH_BINARY);
g_findImage = ~g_findImage;
namedWindow("【被查找的图像】", CV_WINDOW_NORMAL);
namedWindow("【模版图像】", CV_WINDOW_NORMAL);
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);


//模版匹配函数 一共6种匹配方法
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);
namedWindow("【匹配后的图像】", CV_WINDOW_NORMAL);
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);
namedWindow("【匹配后的计算过程图像】", CV_WINDOW_NORMAL);
imshow("【匹配后的计算过程图像】", dstImage);
waitKey();
return 0;
}
原创粉丝点击