OpenCVSharp3 MatchTemplate中有多个结果 [英] Multiple results in OpenCVSharp3 MatchTemplate

查看:674
本文介绍了OpenCVSharp3 MatchTemplate中有多个结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试查找图像中的图像出现.我已经编写了以下代码,以使用OpenCVSharp3进行单个匹配:

I am trying to find image occurences inside an image. I have written the following code to get a single match using OpenCVSharp3:

Mat src = OpenCvSharp.Extensions.BitmapConverter.ToMat(Resources.all);
Mat template = OpenCvSharp.Extensions.BitmapConverter.ToMat(Resources.img);
Mat result = src.MatchTemplate(template, TemplateMatchModes.CCoeffNormed);

double minVal, maxVal;
OpenCvSharp.Point minLoc, maxLoc;
result.MinMaxLoc(out minVal, out maxVal, out minLoc, out maxLoc);
Console.WriteLine("maxLoc: {0}, maxVal: {1}", maxLoc, maxVal);

如何根据阈值获得更多匹配?

How can I get more matches based on a threshold value?

谢谢!

推荐答案

这是C ++代码的端口.祝你好运!

Here's a port of the C++ code. Good luck!

using OpenCvSharp;
using OpenCvSharp.Util;
static void RunTemplateMatch(string reference, string template)
{
    using (Mat refMat = new Mat(reference))
    using (Mat tplMat = new Mat(template))
    using (Mat res = new Mat(refMat.Rows - tplMat.Rows + 1, refMat.Cols - tplMat.Cols + 1, MatType.CV_32FC1))
    {
        //Convert input images to gray
        Mat gref = refMat.CvtColor(ColorConversionCodes.BGR2GRAY);
        Mat gtpl = tplMat.CvtColor(ColorConversionCodes.BGR2GRAY);

        Cv2.MatchTemplate(gref, gtpl, res, TemplateMatchModes.CCoeffNormed);
        Cv2.Threshold(res, res, 0.8, 1.0, ThresholdTypes.Tozero);

        while (true)
        {
            double minval, maxval, threshold = 0.8;
            Point minloc, maxloc;
            Cv2.MinMaxLoc(res, out minval, out maxval, out minloc, out maxloc);

            if (maxval >= threshold)
            {
                //Setup the rectangle to draw
                Rect r = new Rect(new Point(maxloc.X, maxloc.Y), new Size(tplMat.Width, tplMat.Height));

                //Draw a rectangle of the matching area
                Cv2.Rectangle(refMat, r, Scalar.LimeGreen, 2);

                //Fill in the res Mat so you don't find the same area again in the MinMaxLoc
                Rect outRect;
                Cv2.FloodFill(res, maxloc, new Scalar(0), out outRect, new Scalar(0.1), new Scalar(1.0));
            }
            else
                break;
        }

        Cv2.ImShow("Matches", refMat);
        Cv2.WaitKey();
    }
}

这篇关于OpenCVSharp3 MatchTemplate中有多个结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆