Mzk
Mzk

Reputation: 1120

Understanding Template Matching in openCV

Just want to clear out my confusion. I've tested openCV template matching method to match some numbers. First I have this sequence of number 0 1 2 3 4 5 1 2 3 4 5 (after binarization probably the character width is different). How does template matching works to match number '1'? Does it;

  1. slides through all the window until it found 2 matches (2 output), or
  2. stop after it match the first '1', or
  3. find the highest correlation between the two number '1' and choose either one.

Matching Number '1'

Edited: As attached is the output. It only match one number '1' and not two '1'.

[Q] How can I detect two numbers '1' simultaneously?

Upvotes: 3

Views: 5470

Answers (1)

I know it's an old question but here is an answer.

When you do MatchTemplate, it will output an grayscale image. After that, you will need to do a MinMax on it. Then, you can check if there is a result in the range you are looking for. In the example below, using EmguCV (a wrapper of OpenCV in C#), I draw a rectangle around the best find (index 0 of the minValues array) only if it's below 0.75 (you can adjust this threshold for your needs).

Here is the code:

Image<Gray, float> result = new Image<Gray, float>(new System.Drawing.Size(nWidth, nHeight));
result = image.CurrentImage.MatchTemplate(_imageTemplate.CurrentImage, Emgu.CV.CvEnum.TM_TYPE.CV_TM_SQDIFF_NORMED);


double[] minValues;
double[] maxValues;
System.Drawing.Point[] minLocations;
System.Drawing.Point[] maxLocations;

result.MinMax(out minValues, out maxValues, out minLocations, out maxLocations);
if (minValues[0] < 0.75)
{
    Rectangle rect = new Rectangle(new Point(minLocations[0].X, minLocations[0].Y), 
        new Size(_imageTemplate.CurrentImage.Width, _imageTemplate.CurrentImage.Height));
    image.CurrentImage.Draw(rect, new Bgr(0,0,255), 1);
}
else
{
    //Nothing has been found
}

EDIT

Here is an example of the output:

Example of output

Upvotes: 5

Related Questions