我在尝试使用EmguCV MatchTemplate
函数返回所有匹配项时遇到麻烦。另一个要求是,我需要对颜色敏感(红色正方形不是蓝色正方形)。 编辑:如果我的测试不正确,我认为它实际上已经对颜色敏感。
这是我想出的代码,但是我不确定如何修改它以满足我的需求:
Image<Bgr, byte> template = new Image<Bgr, byte>(pathNeedle);
Image<Bgr, byte> source = new Image<Bgr, byte>(pathHaystack);
Image<Bgr, byte> imageToShow = source.Copy();
Stopwatch watch = Stopwatch.StartNew();
using (Image<Gray, float> result = source.MatchTemplate(template, TemplateMatchingType.CcoeffNormed))
{
double[] minValues, maxValues;
Point[] minLocations, maxLocations;
result.MinMax(out minValues, out maxValues, out minLocations, out maxLocations);
watch.Stop();
if (maxValues[0] > threshold)
{
// Match success
Rectangle match = new Rectangle(maxLocations[0], template.Size);
imageToShow.Draw(match, new Bgr(Color.Red), 3);
// do stuff with match
// etc..
}
}
答案 0 :(得分:0)
您需要获取本地最大值
private static List<Point> GetLocalMaxs(Image<Bgr, byte> image, Image<Bgr, byte> template)
{
Image<Gray, float> result = image.MatchTemplate(template, TemplateMatchingType.CcoeffNormed);
var listOfMaxs = new List<Point>();
var resultWithPadding = new Image<Gray, float>(image.Size);
var heightOfPadding = (image.Height - result.Height) / 2;
var widthOfPadding = (image.Width - result.Width) / 2;
resultWithPadding.ROI = new Rectangle() { X = heightOfPadding, Y = widthOfPadding, Width = result.Width, Height = result.Height };
result.CopyTo(resultWithPadding);
resultWithPadding.ROI = Rectangle.Empty;
for (int i = 0; i < resultWithPadding.Width; i++)
{
for (int j = 0; j < resultWithPadding.Height; j++)
{
var centerOfRoi = new Point() { X = i + template.Width / 2, Y = j + template.Height / 2 };
var roi = new Rectangle() { X = i, Y = j, Width = template.Width, Height = template.Height };
resultWithPadding.ROI = roi;
double[] minValues, maxValues;
Point[] minLocations, maxLocations;
resultWithPadding.MinMax(out minValues, out maxValues, out minLocations, out maxLocations);
resultWithPadding.ROI = Rectangle.Empty;
var maxLocation = maxLocations.First();
if (maxLocation.X == roi.Width / 2 && maxLocation.Y == roi.Height / 2)
{
var point = new Point() { X = centerOfRoi.X, Y = centerOfRoi.Y };
listOfMaxs.Add(point);
}
}
}
return listOfMaxs;
}