#include <opencv2/opencv.hpp>
#include <time.h>
using namespace cv;
using namespace std;
int main()
{
clock_t start, end;
double minVal;
Point minLoc;
double threshold = 0.001;
int count = 0;
Mat FinalImage = imread("source.png", IMREAD_COLOR);
if (FinalImage.empty())
return -1;
// Grayscale source, target and mask for faster calculation.
Mat SourceImage;
cvtColor(FinalImage, SourceImage, CV_BGR2GRAY);
Mat TargetImage = imread("target.png", IMREAD_GRAYSCALE);
if (TargetImage.empty())
return -1;
Mat Mask = imread("mask.png", IMREAD_GRAYSCALE);
if (Mask.empty())
return -1;
Mat Result;
start = clock();
// Mask must have the same datatype and size with target image.
// It is not set by default. Currently, only the TM_SQDIFF and TM_CCORR_NORMED methods are supported.
matchTemplate(SourceImage, TargetImage, Result, TM_SQDIFF, Mask); // Type of the template matching operation: TM_SQDIFF
normalize(Result, Result, 0, 1, NORM_MINMAX, -1, Mat());
minMaxLoc(Result, &minVal, NULL, &minLoc, NULL);
for (int i = 0; i < Result.rows; i++)
for (int j = 0; j < Result.cols; j++)
if (Result.at<float>(i, j) < threshold)
{
rectangle(FinalImage, Point(j, i), Point(j + TargetImage.cols, i + TargetImage.rows), Scalar(0, 0, 255), 1);
count++;
}
end = clock();
cout << "Searching time: " << difftime(end, start) / CLOCKS_PER_SEC << endl;
cout << "Minimum Value: " << minVal << " " << minLoc << endl;
cout << "Threshold: " << threshold << endl;
cout << "Found: " << count << endl;
imshow("Mask", Mask);
imshow("TargetImage", TargetImage);
imshow("Result", Result);
imshow("FinalImage", FinalImage);
waitKey(0);
return 0;
}