shimat / opencvsharp

OpenCV wrapper for .NET
Apache License 2.0
5.22k stars 1.13k forks source link

MatchTemplate results are inconsistent or incorrect #1632

Open Nadafy opened 6 months ago

Nadafy commented 6 months ago

I am experiencing an inconsistency in the results of the MatchTemplate method between OpenCVSharp and EmguCV. When using the same template image and search image, the EmguCV version of the code consistently finds a best match with a similarity score of approximately 0.99, while the OpenCVSharp version of same code does not find any matches at all. Also if you save the match result as an image for debugging, it looks completely irrelevant!

Steps to reproduce:

I am on windows, Visual Studio 2022, OpenCvSharp4.Windows 4.8.0.20230708 from NuGet

Sample Code:

Mat sourceMat= new Mat(path1, ImreadModes.Grayscale);
Mat templateMat= new Mat(path2, ImreadModes.Grayscale);

Mat matchResult = new Mat();
Cv2.MatchTemplate(sourceMat, templateMat, matchResult, TemplateMatchModes.CCoeffNormed);
//For debugging purpose
Cv2.Normalize(matchResult, matchResult, 0, 255, NormTypes.MinMax);
matchResult.SaveImage("MatchMapForDebugging.png");

//double minval, maxval, threshold = 0.8;
//Point minloc, maxloc;
//Cv2.MinMaxLoc(res, out minval, out maxval, out minloc, out maxloc);
HeikoBoettger commented 4 months ago

Hi, was just about to create the a duplicate when I found your report. I have similar code also based on OpenCvSharp4 and the latest nuget available and observed the same. In my result I have a lot of matches on a diagonal line, my guess is that something is wrong when passing the value to the underlying opencv library. To confirm that it wasn't some issue with the input images and the configuration of the parameter valuem I rewrote the code in python3 and it worked.