版权声明:共享知识,欢迎转载 https://blog.csdn.net/kakiebu/article/details/79535304
介绍两个函数
void cvMinMaxLoc(//取出矩阵中最大最小值
const CvArr* arr,//目标矩阵
double* min_val,//最小值
double* max_val,//最大值
CvPoint* min_loc = NULL,//最小值位置
CvPoint* max_loc = NULL,//最大值位置
const CvArr* mask = NULL//矩阵“开关”
);
void matchTemplate(
InputArray image, //输入图像
InputArray templ, //输入模板
OutputArray result, //输出结果,类型CV_32FC1
int method //模板匹配方法
);
#include <opencv2/opencv.hpp>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace cv;
using namespace std;
char file[] = "10.jpg";
char file2[] = "11.jpg";
string convertToString(double d);
int main(int argc, char** argv)
{
Mat img = imread(file, -1);
pyrDown(img, img, Size(img.cols/2, img.rows/2));
pyrDown(img, img, Size(img.cols/2, img.rows/2));
pyrDown(img, img, Size(img.cols/2, img.rows/2));
imshow("1",img);imwrite("img.jpg", img);
//////////模版匹配
Mat temp(img, Rect(90,130,130,250));
imshow("temp",temp);imwrite("temp.jpg", temp);
/*
这里为什么是原图尺寸-木板尺寸+1呢?
理解整个模板匹配的过程就是从匹配图像中依次找到与模板相同大小的矩形图像
然后按照给定的方法计算相关系数,并把这个值输出到结果矩阵中与原图模板矩形左上角相同位置坐标的地方
其实得到的矩阵就是一个相关性表。
*/
int width = img.cols - temp.cols +1;
int hight = img.rows - temp.rows +1;
Mat result(width, hight, CV_32FC1);
int match_method = CV_TM_SQDIFF;
matchTemplate(img, temp, result, match_method);
normalize(result, result, 0, 1, NORM_MINMAX, -1, Mat());
imshow("result", result);imwrite("result.jpg", result);
Point minLoc, maxLoc, temLoc;
double min, max;
minMaxLoc(result, &min, &max, &minLoc, &maxLoc, Mat());
if ( match_method == CV_TM_SQDIFF || match_method == CV_TM_SQDIFF_NORMED )
{
temLoc = minLoc;
}
else
{
temLoc = maxLoc;
}
rectangle(img, Rect(temLoc.x, temLoc.y, temp.cols, temp.rows), Scalar(0,0,255), 1, 8, 0);
imshow("find_result", img);imwrite("find_result.jpg", img);
waitKey();
return 1;
}
img.jpg
temp.jpg
result.jpg
find_result.jpg