In this article, I will explain how to search for icons in a screenshot using template matching. The system loads the screenshot and the icon image, then locate similar objects using template matching technique. A box will be drawn around these objects and the screenshot image is displayed on the screen.
Download the full source code, search_icons.c. In the next section I will explain the code and show the result I've got.
Writing the code, step by step
First, load the reference and template image.
Listing 1: Load the images
Note that I stripped out the error checking lines from the code above to make it simple. Remember that you should always have some error checking in your programs.
The next step is perform template matching operation. But before that, we need to create a new image for the template matching result. If img is WxH and tpl is wxh, then the template matching result must be W-w+1xH-h+1.
Listing 2: Perform template matching
Now res contains the comparison result from template matching operation. From this result, we find each element which value is lower than a predefined threshold.
Listing 3: Find objects
We've marked similar objects by drawing a box around it. Now display the screenshot and free the memory.
Listing 4: Display image and free memory
Result
Figure 1 shows the result for searching PDF icons using the template shown in Figure 2.


As you can see, the program successfully found the objects that similar with the given template. However, the result vary depends on the threshold given. Generally, with higher threshold the program will be able to find all similar objects, but it also increase positive false. You may want to try different threshold values to get the best result.
Aurelien on Jan 17, 2010:
edmundo on Jan 26, 2010:
sping on Mar 8, 2010:
hieuiph on Jun 14, 2010:
| Tel. | +62 31 8662872 +62 856 338 6017 |
| ICQ | 489571630 |
| Skype | dede_bl4ckheart |
| Yahoo | dede_bl4ckheart |
| nashruddin.amin |
Victor on Nov 10, 2008:
That hardcoded threshold of 0.12 doesn't work in my case ( where's that value from, anyway ?).
I just searched for the minimum SvScalar value in the result array and draw rectangle there.