代码如下:
#include <cv.h> #include <cxcore.h> #include <highgui.h> #include <cvaux.h> #include <iostream> #include <string> #include <strstream> #include <iomanip> #include <cmath> using namespace std; static void imRotate(IplImage *src,IplImage *dst,double angle , CvPoint2D32f center,double scale = 1 );//缩放图像 int main() { IplImage *src = cvLoadImage("f:\\images\\test3.bmp",CV_LOAD_IMAGE_GRAYSCALE); IplImage *src_cpy = cvCloneImage(src); CvMemStorage *storage = cvCreateMemStorage(); cvThreshold(src,src,50,255,CV_THRESH_BINARY); CvSeq *contour_src = NULL; cvFindContours(src_cpy,storage,&contour_src);//此函数会改变输入图像 CvContourTree *tree_src = cvCreateContourTree(contour_src,storage,0); cvReleaseImage(&src_cpy); CvSeq *contour = NULL; CvRNG rng = cvRNG(-1); bool flag = false; //控制scale和angle哪个变量变化 while(1){ //控制其中一个变化,另一个固定 //与原图像比较 double scale = 1 , angle = 0; if(flag){ scale = cvRandReal(&rng)*1.3; if(scale < 0.5) continue; }else angle = cvRandReal(&rng)*360; time_t StartTime = clock(); IplImage *dst = cvCreateImage(cvSize(src->width,src->height),8,1); imRotate(src,dst,angle,cvPoint2D32f(src->width/2,src->height/2),scale); cvShowImage("dst",dst); cvThreshold(dst,dst,100,255,CV_THRESH_BINARY); cvFindContours(dst,storage,&contour); CvContourTree *tree = cvCreateContourTree(contour,storage,0); double result = cvMatchContourTrees(tree_src,tree,CV_CONTOUR_TREES_MATCH_I1,0); time_t EndTime = clock(); cout<<"angle = "<<setprecision(3)<<angle<<" scale = "<<scale<<"\t"; cout<<"result = "<<setprecision(3)<<result<<"\ttime = "<<double(EndTime - StartTime)/CLOCKS_PER_SEC<<endl; cvReleaseImage(&dst); cvClearSeq(contour); int key = cvWaitKey(); if(key == 27) break; else if(key == 'n' || key == 'N') flag = !flag; } cvReleaseMemStorage(&storage); cvReleaseImage(&src); } void imRotate(IplImage *src, IplImage *dst,double angle , CvPoint2D32f center,double scale) { assert(src->width == dst->width && src->height == dst->height &&src->depth == dst->depth &&src->nChannels == dst->nChannels); CvMat *mapMatrix = cvCreateMat(2,3,CV_32FC1); IplImage *tmp = cvCreateImage(cvGetSize(src),src->depth,src->nChannels); cv2DRotationMatrix(center,angle,scale,mapMatrix); //旋转缩放为仿射变换,此处求变换矩阵 cvWarpAffine(src,(src->imageData == dst->imageData) ? tmp : dst,mapMatrix); //此函数不能src == dst if(src->imageData == dst->imageData) cvCopyImage(tmp,dst); cvReleaseImage(&tmp); }
在固定其中一个变量的情况下做匹配,发现得到的值差异很大,不知道这个轮廓树比较得到的结果有什么用处,请各位路过的大侠指教!
试验结果:
从结果中看几乎无关联 , 我又修改了程序
使无旋转时,图像的大小随着scale变化(上面的程序图像大小不变),即用cvResize缩放,仍然是一样的情况 ,看不出关联