• Open Source Computer Vision Library

灰度模板匹配

Wikipedia,自由的百科全书

代码对输入的两张图像直接进行灰度模板匹配,运行结果如下图:

Image:hptemplet.png

Image:hppart.png

Image:templetmatch.png

使用opencv1.0版本,具体代码:

// numRecog.cpp : Defines the entry point for the console application.
//
 
#include "stdafx.h"
#include <cv.h>
#include <highgui.h>
#include <stdio.h>
 
 
 
int main(int argc, char* argv[])
{
	int i,j,ii,jj,count,countmax,targeti,targetj;
	IplImage *src = 0;
	IplImage *bwdst = 0;
	IplImage *bwdst1 = 0;
	IplImage *cannydst = 0;
	IplImage *templet = 0;
	CvSize templetsize, srcsize;
	CvRect roiRegion;
 
	templet = cvLoadImage("templet.bmp", CV_LOAD_IMAGE_GRAYSCALE); 
	//cvNamedWindow( "templet", 0 );
    //cvShowImage( "templet", templet );
	templetsize = cvGetSize(templet);
 
	src = cvLoadImage("8.bmp", CV_LOAD_IMAGE_GRAYSCALE); 
	//cvNamedWindow( "src", 0 );
    //cvShowImage( "src", src );
	srcsize = cvGetSize(src);
 
	//binary51
	bwdst = cvCreateImage(cvGetSize(src), IPL_DEPTH_8U, 1);
	cvAdaptiveThreshold(src, bwdst, 255, CV_ADAPTIVE_THRESH_MEAN_C, CV_THRESH_BINARY, 51, 5 );
	//cvNamedWindow( "bwdst", 0 );
    //cvShowImage( "bwdst", bwdst );
	cvSaveImage("bwdst.bmp",bwdst );
 
	//binary11
	bwdst1 = cvCreateImage(cvGetSize(src), IPL_DEPTH_8U, 1);
	cvAdaptiveThreshold(src, bwdst1, 255, CV_ADAPTIVE_THRESH_MEAN_C, CV_THRESH_BINARY, 11, 5 );
	//cvNamedWindow( "bwdst1", 0 );
    //cvShowImage( "bwdst1", bwdst1 );
	cvSaveImage("bwdst1.bmp",bwdst1 );
 
	//canny
	cannydst = cvCreateImage(cvGetSize(src), IPL_DEPTH_8U, 1);
	cvCanny(src, cannydst, 50, 100, 3);
	//cvNamedWindow( "cannydst", 0 );
    //cvShowImage( "cannydst", cannydst );
	cvSaveImage("cannydst.bmp",cannydst );
 
	//search templet region
	countmax = 0;
	targeti = 0;
	targetj = 0;
	for(i=0; i<(srcsize.height-templetsize.height); i=i+4)
	{
		for(j=0; j<(srcsize.width-templetsize.width); j=j+4)
		{
			count = 0;
			for(ii=0; ii<templetsize.height; ii=ii+4)
			{
				for(jj=0; jj<templetsize.width; jj=jj+4)
				{
					if( ((uchar *)(templet->imageData + ii*templet->widthStep))[jj] !=
						((uchar *)(cannydst->imageData + (i+ii)*cannydst->widthStep))[(j+jj)] )
					{
						count++;
					}
 
				}
			}
			if(countmax < count)
			{
				countmax = count;
				targeti = i;
				targetj = j;
			}
			printf("i=%d, countmax=%d\n",i,countmax);
		}
	}
	//roiRegion = cvRect(0, 0, templetsize.width, templetsize.height);  
	//cvSetImageROI(cannydst, roiRegion);
	//cvResetImageROI(cannydst);
	cvRectangle(cannydst, cvPoint(targetj,targeti),cvPoint((targetj+templetsize.width),
		(targeti+templetsize.height)),CV_RGB(255,255,255),5);
	cvSaveImage("cannydst1.bmp",cannydst );
 
	cvWaitKey(0);
 
	//release
	cvReleaseImage( &templet );
	cvReleaseImage( &src );
	//cvReleaseImage( &bwdst );
	//cvReleaseImage( &bwdst1 );
	cvReleaseImage( &cannydst );
 
 
	return 0;
}
Views
Personal tools