// writer: qiaoshan
// message: 里面的一些图像指针需要适当改动才可应用, 不麻烦奥
// mail: uyskio@yahoo.com.cn
LPSTR lpDIB;
LPSTR lpDIBBits;
DWORD width;
DWORD height;
DWORD widthLine;
CCh1_1Doc* pDoc = GetDocument();
lpDIB = (LPSTR)GlobalLock(pDoc->GetHDIB());
lpDIBBits = FindDIBBits(lpDIB);
width = DIBWidth(lpDIB);
height = DIBHeight(lpDIB);
widthLine = WIDTHBYTES(width*8);
DWORD hist[256];
memset(hist, 0, 256*4);
int i, j;
for(j=0; j<height; j++)
{
for(i=0; i<width; i++)
{
hist[*(lpDIBBits+j*widthLine+i)]+=1; //calculate the histgram;
}
}
float P[257];
for(i=1; i<257; i++)
{
P[i] = hist[i-1]/float(height*width); // calculate the probility
}
float q1[257];
// float q2[257];
float u1[257];
float u2[257];
float det[257];
float u;
u = P[1];
for(i=2; i<257; i++)
{
u += i*P[i];
}
q1[1] = P[1];
u1[1] = 1;
for(i=2; i<257; i++)
{
q1[i] = q1[i-1] + P[i];
u1[i] =( q1[i-1]*u1[i-1] + i*P[i] )/q1[i];
u2[i] =( u-q1[i]*u1[i] )/( 1-q1[i] );
}
float temp;
int out;
temp = (float)-1e33;
for(i=1; i<257; i++)
{
det[i] = q1[i]*(1-q1[i])*(u1[i]-u2[i])*(u1[i]-u2[i]);
if(det[i] > temp)
out = i;
temp = det[i];
}
for(j=0; j<height; j++) //output the image
{
for(i=0; i<width; i++)
{
if(*(lpDIBBits+j*widthLine+i)<out-1)
*(lpDIBBits+j*widthLine+i) = 0;
else
*(lpDIBBits+j*widthLine+i) = -1;
}
}
GlobalUnlock(pDoc->GetHDIB());