最大熵閾值分割演算法
阿新 • • 發佈:2018-12-29
#include <opencv2\opencv.hpp> #include <opencv\cv.h> using namespace cv; int HistogramBins = 256; float HistogramRange1[2]={0,255}; float *HistogramRange[1]={&HistogramRange1[0]}; typedef enum {back,object} entropy_state; int QueryHistValue_1D(CvHistogram* hist,int i) { return 1; } double caculateCurrentEntropy(CvHistogram * Histogram1,int cur_threshold,entropy_state state) { int start,end; if(state == back) { start = 0;end = cur_threshold; } else { start = cur_threshold;end = 256; } int total = 0; for(int i=start;i<end;i++) { total += (int)cvQueryHistValue_1D(Histogram1,i); } double cur_entropy = 0.0; for(int i=start;i<end;i++){ if((int)cvQueryHistValue_1D(Histogram1,i)==0) continue; double percentage = cvQueryHistValue_1D(Histogram1,i)/total; cur_entropy += -percentage*logf(percentage); } return cur_entropy; } void MaxEntropy(IplImage *src,IplImage *dst) { assert(src != NULL); assert(src->depth == 8 && dst->depth == 8); assert(src->nChannels == 1); CvHistogram * hist = cvCreateHist(1,&HistogramBins,CV_HIST_ARRAY,HistogramRange); cvCalcHist(&src,hist); double maxentropy = -1.0; int max_index = -1; for(int i=0;i<HistogramBins;i++) { double cur_entropy = caculateCurrentEntropy(hist,i,object)+caculateCurrentEntropy(hist,i,back); if(cur_entropy>maxentropy){ maxentropy = cur_entropy; max_index = i; } } cvThreshold(src,dst,(double)max_index,255,CV_THRESH_BINARY); cvReleaseHist(&hist); } int _tmain(int argc, _TCHAR* argv[]) { IplImage* src; //宣告IplImage指標 //載入影象 if( (src = cvLoadImage( "d:/1.JPG",0))!= 0 ) { cvShowImage("src",src); cvNamedWindow( "Image", 1 );//建立視窗 IplImage* dst = cvCreateImage(cvGetSize(src),IPL_DEPTH_8U,1); MaxEntropy(src,dst); cvShowImage( "Image", dst );//顯示影象 cvWaitKey(0); //等待按鍵 cvDestroyWindow( "Image" );//銷燬視窗 cvReleaseImage( &src ); //釋放影象 cvReleaseImage( &dst ); //釋放影象 return 0; } return -1; }
顯示效果: