我正试图使用OpenCVSharp中的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
出了什么问题?错误在哪里?结果数组的大小,位深度和通道号看起来是正确的,但该方法仍然会出现异常。
答案 0 :(得分:1)
不确定原始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);
答案 1 :(得分:1)
应该有
的异常行 *image.MatchTemplate(*template*, result, MatchTemplateMethod.CCoeffNormed);*