如何从 C# 调用 OpenCV 的 MatchTemplate 方法

How to call OpenCV's MatchTemplate method from C#

我正在尝试使用 OpenCVSharp library from NuGet 获取模板在图像上的位置。这是我写的代码:

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);

输出:

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

异常:

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

怎么了?错误在哪里?结果数组的大小、位深和通道数看起来是正确的,但该方法仍然引发异常。

不确定原始的类 C 代码有什么问题,但我设法让它与 C++ 类代码一起工作:

 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);

例外行应该有

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