Skip to content

Instantly share code, notes, and snippets.

@yoggy
Created December 9, 2011 10:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save yoggy/1451097 to your computer and use it in GitHub Desktop.
Save yoggy/1451097 to your computer and use it in GitHub Desktop.
OpenCV cv::matchTemplate() sample
#include <SDKDDKVer.h>
#include <Windows.h>
#pragma warning(disable:4819)
#pragma warning(disable:4996)
// for OpenCV2
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/gpu/gpu.hpp"
#include "opencv2/highgui/highgui.hpp"
#ifdef _DEBUG
#pragma comment(lib, "opencv_core231d.lib")
#pragma comment(lib, "opencv_imgproc231d.lib")
#pragma comment(lib, "opencv_objdetect231d.lib")
#pragma comment(lib, "opencv_gpu231d.lib")
#pragma comment(lib, "opencv_highgui231d.lib")
#else
#pragma comment(lib, "opencv_core231.lib")
#pragma comment(lib, "opencv_imgproc231.lib")
#pragma comment(lib, "opencv_objdetect231.lib")
#pragma comment(lib, "opencv_gpu231.lib")
#pragma comment(lib, "opencv_highgui231.lib")
#endif
int main(int argc, char* argv[])
{
cv::Mat src_img, template_img;
cv::Mat result_mat;
cv::Mat debug_img;
template_img = cv::imread("..\\img\\lena_eye.jpg", CV_LOAD_IMAGE_GRAYSCALE);
if (template_img.data == NULL) {
printf("cv::imread() failed...\n");
return -1;
}
src_img = cv::imread("..\\img\\lena.jpg", CV_LOAD_IMAGE_GRAYSCALE);
if (src_img.data == NULL) {
printf("cv::imread() failed...\n");
return -1;
}
cv::cvtColor(src_img, debug_img, CV_GRAY2BGR);
while(true) {
// method: CV_TM_SQDIFF, CV_TM_SQDIFF_NORMED, CV_TM _CCORR, CV_TM_CCORR_NORMED, CV_TM_CCOEFF, CV_TM_CCOEFF_NORMED
int match_method = CV_TM_CCORR_NORMED;
cv::matchTemplate(src_img, template_img, result_mat, match_method);
cv::normalize(result_mat, result_mat, 0, 1, cv::NORM_MINMAX, -1, cv::Mat());
double minVal; double maxVal;
cv::Point minLoc, maxLoc, matchLoc;
cv::minMaxLoc(result_mat, &minVal, &maxVal, &minLoc, &maxLoc, cv::Mat() );
if( match_method == CV_TM_SQDIFF || match_method == CV_TM_SQDIFF_NORMED ) matchLoc = minLoc;
else matchLoc = maxLoc;
cv::rectangle(
debug_img,
matchLoc,
cv::Point(matchLoc.x + template_img.cols , matchLoc.y + template_img.rows),
CV_RGB(255,0,0),
3);
cv::imshow("debug_img", debug_img);
int c = cv::waitKey(1);
if (c == 27) break;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment