How to call OpenCV's MatchTemplate method from C#

5.7k views Asked by At

I'm trying to get the template's position on the image using OpenCVSharp library from NuGet. Here is the code I've wrote:

var image = Cv.LoadImage("Image.png");
var template = Cv.LoadImage("Template.png");
var w = (image.Width - template.Width) + 1;
var h = (image.Height - template.Height) + 1;
IplImage result = new IplImage(w, h, BitDepth.F32, 1);

Console.WriteLine("Image: {0} {1}", image.GetSize(), image.ElemType);
Console.WriteLine("Template: {0} {1}", template.GetSize(), template.ElemType);
Console.WriteLine("Result: {0} {1}", result.GetSize(), result.ElemType);

image.MatchTemplate(image, result, MatchTemplateMethod.CCoeffNormed); // throws exception

double minVal, maxVal;
CvPoint minLoc, maxLoc;
result.MinMaxLoc(out minVal, out maxVal, out minLoc, out maxLoc);
Console.WriteLine(maxLoc);

Output:

Image: CvSize (Width:2048 Height:1536) U8C3
Template: CvSize (Width:169 Height:128) U8C3
Result: CvSize (Width:1880 Height:1409) F32C1

Exception:

OpenCvSharp.OpenCVException : result.size() == cv::Size(std::abs(img.cols - templ.cols) + 1, std::abs(img.rows - templ.rows) + 1) && result.type() == CV_32F

What's wrong? Where is the error? The size, bit depth and channel number of the result array look correct, but the method still rises the exception.

2

There are 2 answers

0
Liqiang He On BEST ANSWER

exception line there should be

*image.MatchTemplate(*template*, result, MatchTemplateMethod.CCoeffNormed);*

0
al0 On

Not sure what's wrong with the original C-like code, but I'm managed to get it working with C++ like code:

 using OpenCvSharp;
 using OpenCvSharp.CPlusPlus;
 // ...

 var image = new Mat("Image.png");
 var template = new Mat("Template.png");

 double minVal, maxVal;
 Point minLoc, maxLoc;
 var result = image.MatchTemplate(template, MatchTemplateMethod.CCoeffNormed);
 result.MinMaxLoc(out minVal, out maxVal, out minLoc, out maxLoc);
 Console.WriteLine("maxLoc: {0}, maxVal: {1}", maxLoc, maxVal);