学习opencv——习题8-10提取Hu矩的字符图像

#include <cv.h>
#include <opencv2/legacy/legacy.hpp>
#include <stdio.h>
#include <stdlib.h>
#include "highgui.h"
using namespace std;
using namespace cv;

int main( int argc, char** argv )
{
for (int i=1;i<argc;i++)
{
IplImage* img = cvLoadImage(argv[i], CV_LOAD_IMAGE_GRAYSCALE);
cvNamedWindow("image");
cvShowImage("image",img);
//二值化
IplImage* img_threshold=cvCreateImage(cvGetSize(img),img->depth,1);
cvThreshold(img,img_threshold,100,255,CV_THRESH_BINARY);
//检测轮廓
cvZero(img);
CvSeq* contours = 0;
CvMemStorage* storage_ct = cvCreateMemStorage(0);
cvFindContours( img_threshold, storage_ct, &contours, sizeof(CvContour),CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE );
//多边形逼近
contours = cvApproxPoly( contours, sizeof(CvContour), storage_ct, CV_POLY_APPROX_DP, 3, 1 );
cvDrawContours(img, contours, cvScalarAll(255), cvScalarAll(255), 100 );
cvNamedWindow( "contour" );
cvShowImage( "contour", img );

//计算Hu矩
CvMoments moment;
cvMoments(contours,&moment,0);
CvHuMoments humoments;
cvGetHuMoments(&moment,&humoments);
cout<<"输出Hu矩:"<<endl;
for (int i=0;i<7;++i)
{
cout<<" h["<<i+1<<"]:"<<((double*)&humoments)[i];
/*cout<<setiosflags(ios::scientific)<<setprecision(4)
<<((double*)&humoments)[i]<<" ";*/
}
cout<<endl;

cvWaitKey(0);
cvDestroyAllWindows();
cvReleaseMemStorage( &storage_ct );
cvReleaseImage( &img );
cvReleaseImage(&img_threshold);
}
return 0;
}

猜你喜欢

转载自www.cnblogs.com/yanzhixue/p/11368462.html