You can use connectedcomponent to fix thresh and find a possible location. A weighted surface with correlation should be tested :
#include "opencv2/opencv.hpp"
#include <iostream>
using namespace cv;
using namespace std;
static void AddSlider(String sliderName, String windowName, int minSlider, int maxSlider, int valDefault, int *valSlider, void(*f)(int, void *), void *r)
{
createTrackbar(sliderName, windowName, valSlider, 1, f, r);
setTrackbarMin(sliderName, windowName, minSlider);
setTrackbarMax(sliderName, windowName, maxSlider);
setTrackbarPos(sliderName, windowName, valDefault);
}
struct SliderData {
Mat img;
int thresh;
};
static void UpdateThreshImage(int, void *r)
{
SliderData *p = (SliderData*)r;
Mat dst, labels, stats, centroids;
threshold(p->img, dst, p->thresh, 255, THRESH_BINARY);
connectedComponentsWithStats(dst, labels, stats, centroids, 8);
if (centroids.rows < 10)
{
cout << "**********************************************************************************\n";
cout << " thresh = " << p->thresh / 255.0 << "\n";
for (int i = 0; i < centroids.rows; i++)
{
int x = (int)centroids.at<double>(i, 0);
int y = (int)centroids.at<double>(i, 1);
if (dst.at<uchar>(Point(x,y)) == 255)
{
cout << "(x, y) = ("<<centroids.at<double>(i, 0) << ",";
cout << centroids.at<double>(i, 1) << ") surface = ";
cout << stats.at<int>(i, 4) << "\n";
}
}
cout << "----------------------------------------------------------------------------------\n";
}
imshow("Max corr", dst);
}
void main(void)
{
Mat imgSrc = imread("source.jpg",IMREAD_GRAYSCALE);
Mat imgTmp = imread("template.jpg", IMREAD_GRAYSCALE);
Mat result;
imshow("Original", imgSrc);
imshow("Template", imgTmp);
Scalar m1 = mean(imgSrc);
Scalar m2 = mean(imgTmp);
Mat imgSrcF;
Mat imgTmpF;
Mat rNorm;
SliderData ps;
ps.thresh = 0;
cv::matchTemplate(imgSrc, imgTmp, result, TM_CCOEFF_NORMED);
normalize(result, rNorm, 1, 0, NORM_MINMAX);
rNorm.convertTo(ps.img, CV_8U, 255);
imshow("matchTemplate", ps.img);
AddSlider("Level", "matchTemplate", 200, 255, ps.thresh, &ps.thresh, UpdateThreshImage, &ps);
int code = 0;
while (code != 27)
{
code = waitKey(50);
}
waitKey(0);
}