Template matching

Template matching is a technique in digital image processing for finding small parts of an image which match a template image. It can be used in manufacturing as a part of quality control, a way to navigate a mobile robot, or as a way to detect edges in images.

Example

In the following image water is running from tap and we need to find out portion in image which is highlighted in red. So the base image is full tap image and we need to find that the portion highlighted in red exists in image exists in full tap image or not.

Full Image (linux2.jpg) Sample image to be find out (linux2temp.jpg)

Code

#include "cv.h"
#include "highgui.h"
int main()
{
	IplImage* imgOriginal = cvLoadImage("linux2.jpg", 0);
	IplImage* imgTemplate = cvLoadImage("linux2temp.jpg", 0);


	IplImage* imgResult = cvCreateImage(cvSize(imgOriginal->width-imgTemplate->width+1, 
		imgOriginal->height-imgTemplate->height+1), IPL_DEPTH_32F, 1);

	cvZero(imgResult);

	cvMatchTemplate(imgOriginal, imgTemplate, imgResult, CV_TM_CCORR_NORMED);
	double min_val=0, max_val=0;
	CvPoint min_loc, max_loc;
	cvMinMaxLoc(imgResult, &min_val, &max_val, &min_loc, &max_loc);

	cvRectangle(imgOriginal, max_loc, cvPoint(max_loc.x+imgTemplate->width, max_loc.y+imgTemplate->height), cvScalar(1), 1);

	printf("%f", max_val);
	cvNamedWindow("result");
	cvShowImage("result", imgOriginal);
	cvWaitKey(0);
	return 0;
}

Output :