opencv 对hu不变矩的测试程序cvGetHuMoments,opencv第八章第10题

程序对使用轮廓的hu矩进行测试

如下:

#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;

void imRotate(IplImage *src,IplImage *dst,double angle , CvPoint2D32f center,double scale = 1 );

int main()
{
	time_t StartTime = clock();

	IplImage *src = cvLoadImage("f:\\images\\test1.bmp",CV_LOAD_IMAGE_GRAYSCALE);
	cvShowImage("src",src);
	CvMemStorage *storage = cvCreateMemStorage();
	CvSeq *contour = NULL;

	CvRNG rng = cvRNG(-1);
	while(1){
		double scalar = cvRandReal(&rng)*0.8;
		if(scalar < 0.3 )
			continue;
		double angle = cvRandReal(&rng)*360;
	
		IplImage *dst = cvCreateImage(cvSize(src->width,src->height),8,1);
		imRotate(src,dst,angle,cvPoint2D32f(src->width/2,src->height/2),scalar);
		cvShowImage("dst",dst);

		cvThreshold(dst,dst,100,255,CV_THRESH_BINARY);
		
		cvFindContours(dst,storage,&contour);
		CvMoments moments;
		CvHuMoments huMoments;
		cvMoments(dst,&moments,1);
		cvGetHuMoments(&moments, &huMoments);
		
		cout<<"("<<setprecision(3)<<dec<<scalar<<")"<<" ";
		for(int i = 0;i<7;++i){
			cout<<setiosflags(ios::scientific)<<setprecision(4)<<((double*)&huMoments)[i]<<' ';
		}
		cout<<endl;
		cvReleaseImage(&dst);
		cvClearSeq(contour);
		if(cvWaitKey() == 27)
			break;
	}
	
	time_t EndTime = clock();
	cout<<double(EndTime - StartTime)/CLOCKS_PER_SEC<<endl;
}


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);
	cv2DRotationMatrix(center,angle,scale,mapMatrix); //旋转缩放为仿射变换,此处求变换矩阵
	
	cvWarpAffine(src,dst,mapMatrix);
}


测试用图为:



测试结果为:

opencv 对hu不变矩的测试程序cvGetHuMoments,opencv第八章第10题_第1张图片


不同的缩放加旋转的情况下的hu不变矩

结果发现,对于旋转加缩放的情况下,得到的7个Hu矩中

hu1 的前三位是可以保持不变的( 不变性最好)

hu2~hu7 保证一位不变了




你可能感兴趣的:(ios,image,测试,360,DST)