Template Matching - Implementation

Implementation

In this simple implementation, it is assumed that the above described method is applied on grey images: This is why Grey is used as pixel intensity. The final position in this implementation gives the top left location for where the template image best matches the search image.

minSAD = VALUE_MAX; // loop through the search image for ( int x = 0; x <= S_rows - T_rows; x++ ) { for ( int y = 0; y <= S_cols - T_cols; y++ ) { SAD = 0.0; // loop through the template image for ( int j = 0; j < T_cols; j++ ) for ( int i = 0; i < T_rows; i++ ) { pixel p_SearchIMG = S; pixel p_TemplateIMG = T; SAD += abs( p_SearchIMG.Grey - p_TemplateIMG.Grey ); } // save the best found position if ( minSAD < SAD ) { minSAD = SAD; // give me min SAD position.bestRow = x; position.bestCol = y; position.bestSAD = SAD; } } }

One way to perform template matching on color images is to decompose the pixels into their color components and measure the quality of match between the color template and search image using the sum of the SAD computed for each color separately.

Read more about this topic:  Template Matching