Skip to content

Instantly share code, notes, and snippets.

@BinRoot
Created February 7, 2015 01:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BinRoot/5c2ac12ee5271cc778f6 to your computer and use it in GitHub Desktop.
Save BinRoot/5c2ac12ee5271cc778f6 to your computer and use it in GitHub Desktop.
// Declare your template and image
Mat* templ = ...;
Mat* img = new Mat(iplImg, true);
/// Source image to display
Mat img_display;
img -> copyTo( img_display );
/// Create the result matrix
int result_cols = img -> cols - templ -> cols + 1;
int result_rows = img -> rows - templ -> rows + 1;
Mat result;
result.create( result_cols, result_rows, CV_32FC1 );
int match_method = CV_TM_SQDIFF;
/// Do the Matching and Normalize
matchTemplate( *img, *templ, result, match_method );
normalize( result, result, 0, 1, NORM_MINMAX, -1, Mat() );
/// Localizing the best match with minMaxLoc
double minVal; double maxVal; Point minLoc; Point maxLoc;
Point matchLoc;
minMaxLoc( result, &minVal, &maxVal, &minLoc, &maxLoc, Mat() );
/// For SQDIFF and SQDIFF_NORMED, the best matches are lower values. For all the other methods, the higher the better
if( match_method == CV_TM_SQDIFF || match_method == CV_TM_SQDIFF_NORMED ) {
matchLoc = minLoc;
} else {
matchLoc = maxLoc;
}
// matchLoc is the top-left point of the bounding box
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment