基于VS 2015 opencv
#include<opencv2/opencv.hpp>
#include<iostream>
using namespace std;
using namespace cv;
int main()
{
Mat airport, plane;
airport = imread("airport.bmp",0);
plane = imread("template.bmp", 0);
Mat Correlation(airport.rows,airport.cols, CV_64FC1, Scalar(0));
Mat NormCorrelation;
imshow("原始图", airport);
imshow("飞机", plane);
int N = plane.cols*plane.rows;
double Sgf = 0, Sgg = 0, Sff = 0,Sg = 0,Sf = 0;
double Ss;
//模板
for (int a = 0; a < plane.rows; ++a)
{
for (int b = 0; b < plane.cols; ++b)
{
Sg+= plane.at<uchar>(a,b);
Sgg += plane.at<uchar>(a, b)*plane.at<uchar>(a, b);
}
}
double Cgg = Sgg - Sg*Sg / N;
//再原始影像上进行窗口滑动
for (int i = plane.rows / 2; i < airport.rows-plane.rows/2 - 1; i++)
{
for (int j = plane.rows / 2; j < airport.cols - plane.rows / 2 - 1; j++)
{
for (int c = 0; c < plane.rows; ++c)
{
for (int f = 0; f < plane.cols; ++f)
{
Sf += airport.at<uchar>(i + c - plane.rows / 2, j + f - plane.cols / 2);
Sff += (airport.at<uchar>(i + c - plane.cols / 2, +f - plane.cols / 2)*airport.at<uchar>(i + c - plane.cols / 2, +f - plane.cols / 2));
Sgf += (plane.at<uchar>(c, f)*airport.at<uchar>(i + c - plane.rows / 2, j + f - plane.rows, j + f - plane.cols / 2));
}
}
double Cff = Sff - Sf*Sf / N;
Ss = sqrt(Cff*Cgg);
Correlation.at<double>(i,j) - (Sgf - Sg*Sg / N) / Ss;
Sf = 0;
Sgf = 0;
Sff = 0;
}
}
imshow("相关系数图像", Correlation);
double minVal;
double maxVal;
Point minLoc;
Point maxLoc;
minMaxLoc(Correlation, &minVal, &maxVal, &minLoc, &maxLoc);
cout << maxVal << endl << maxLoc.x << endl << maxLoc.y << endl;
rectangle(airport,Point(maxLoc.x - 16, maxLoc.y - 16), Point(maxLoc.x + 16, maxLoc.y + 16), Scalar(0, 0, 255), 2, 8);
cout << "over" << endl;
waitKey(0);
}