I am trying to use OpenCV (java) to do template matching and use the max min values to determine whether the object found or not.
I am using the following java/opencv code but the problem is it returns 0.0 for min values for both best match as well as for the scenarios where no match found.
So this template matching seems unreliable to determine whether the object found or not. Am I doing anything wrong in this code or I need to go for any other techniques?
Thanks in advance.
int templateMatchMethod = Imgproc.TM_SQDIFF_NORMED;
Mat largeImage = Highgui.imread(largeUrl);
Mat smallImage = Highgui.imread(smallUrl);
boolean isMaxTypleMethod = true;
double TEMPLATE_MATCH_THRESHOLD = 0.8;
int result_cols = largeImage.cols() - smallImage.cols() + 1;
int result_rows = largeImage.rows() - smallImage.rows() + 1;
Mat result = new Mat(result_rows, result_cols, CvType.CV_8U);
Imgproc.matchTemplate(largeImage, smallImage, result, templateMatchMethod);
Core.normalize(result, result, 0, 1, Core.NORM_MINMAX, -1, new Mat());
MinMaxLocResult mmr = Core.minMaxLoc(result);
Point matchLoc;
double minMaxValue = 1;
if (templateMatchMethod == Imgproc.TM_SQDIFF || templateMatchMethod == Imgproc.TM_SQDIFF_NORMED)
{
matchLoc = mmr.minLoc;
isMaxTypleMethod = false;
TEMPLATE_MATCH_THRESHOLD = 0.4;
minMaxValue = mmr.minVal;
}
else
{
matchLoc = mmr.maxLoc;
minMaxValue = mmr.maxVal;
}
Core.rectangle(largeImage, matchLoc, new Point(matchLoc.x + smallImage.cols(),
matchLoc.y + smallImage.rows()), new Scalar(0, 255, 0));
System.out.println("minMaxValue : "+minMaxValue);
if(isMaxTypleMethod && TEMPLATE_MATCH_THRESHOLD < minMaxValue)
{
System.out.println("Match found");
}
else if (!isMaxTypleMethod && TEMPLATE_MATCH_THRESHOLD > minMaxValue)
{
System.out.println("Match found");
}