Finding all matches with matchtemplate opencv opencvsharp

Casper Thule Hansen picture Casper Thule Hansen · Feb 3, 2012 · Viewed 8.5k times · Source

I am using opencv with opencvsharp.

When doing a matchtemplate and afterwards minmaxloc I only get the first match. How do I get all matches?

            Cv.MatchTemplate(tempImg, templateSymbol.Img, resImg, MatchTemplateMethod.CCorrNormed);
            double min_val, max_val;
            Cv.MinMaxLoc(resImg, out min_val, out max_val);
            if (max_val > 0.5)
            {

                symbolsFound.Add(templateSymbol.Description);
                Console.WriteLine(templateSymbol.Description);
            }

I only find the first match and I know there are more matches.

Answer

Mayank Kumawat picture Mayank Kumawat · Jan 12, 2015
try
        {

            IplImage tpl = Cv.LoadImage("template path", LoadMode.Color);
            IplImage img = Cv.LoadImage("main image path", LoadMode.Color);

            IplImage res = Cv.CreateImage(Cv.Size(img.Width - tpl.Width + 1, img.Height - tpl.Height + 1), BitDepth.F32, 1);
            Cv.MatchTemplate(img, tpl, res, MatchTemplateMethod.CCoeffNormed);

            Cv.Threshold(res, res, 0.9, 255, ThresholdType.ToZero);

            while (true)
            {
                CvPoint minloc, maxloc;
                double minval, maxval, threshold = 0.95;

                Cv.MinMaxLoc(res, out minval, out maxval, out minloc, out maxloc, null);
                if (maxval > threshold)
                {
                    Console.WriteLine("Matched " + maxloc.X + "," + maxloc.Y);
                    Cv.FloodFill(res, maxloc, new CvScalar());
                }
                else
                {
                    Console.WriteLine("No More Matches");
                    break;
                }
            }

            Cv.ReleaseImage(res);
            Cv.ReleaseImage(img);


        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }