#include <iostream.h> #include <math.h> #include <cv.h> #include <highgui.h> #include <stdio.h> #include <windows.h> int height; int width;
void otsu(IplImage* A, IplImage* B) { long N = height * width; int h[256]; double p[256],u[256],w[256];
for(int i = 0; i < 256; i++) { h[i] = 0; p[i] = 0; u[i] = 0; w[i] = 0; }
for(i = 0; i < height; i++) for(int j = 0; j < width; j++) for(int k = 0; k < 256; k++) { if(((uchar*)(A->imageData + A->widthStep*i))[j] == k) h[k]++; }
for(i = 0; i < 256; i++) p[i] = h[i] / double(N);
int T = 0; double uT,thegma2fang; double thegma2fang_max = -10000;
for(int k = 0; k < 256; k++) { uT = 0; for(i = 0; i <= k; i++) { u[k] += i*p[i]; w[k] += p[i]; }
for(i = 0; i < 256; i++) uT += i*p[i]; thegma2fang = (uT*w[k] - u[k])*(uT*w[k] - u[k]) / (w[k]*(1-w[k]));
if(thegma2fang > thegma2fang_max) { thegma2fang_max = thegma2fang; T = k; } }
for(i = 0; i < height; i++) //根据最佳阈值,对原图像进行处理二值化处理 for(int j = 0; j < width; j++) if(((uchar*)(A->imageData + A->widthStep*i))[j] > T) ((uchar*)(B->imageData + B->widthStep*i))[j] = 255; else ((uchar*)(B->imageData + B->widthStep*i))[j] = 0;
}
int main(int argc, char** argv) { const char* filename = argc >= 2 ? argv[1] : "lena.jpg"; IplImage* source = cvLoadImage( filename, 0 ); IplImage *gray = cvCreateImage(cvSize(InPut->width,InPut->height),IPL_DEPTH_8U,1); height = source->height; width = source->width;
otsu(source,gray);
cvNamedWindow( "Resource", 1 ); cvShowImage( "Resource", source ); cvNamedWindow( "Result", 1 ); cvShowImage( "Result", gray); cvWaitKey(0);
return 0; }
转自:http://blog.sina.com.cn/s/blog_66bdb39d0100jjd3.html
|