BOOL Fenbutongji(LPSTR lpDIBBits,int lmageWidth,int lmageHeight,int *tongji) //统计
{
// 循环变量
LONG i;
LONG j;
//变量初始化
memset(tongji,0,sizeof(int) * 256);
// 对各像素进行灰度转换
for (j = 0; j < lmageHeight; j ++)
{
for (i = 0; i <lmageWidth; i++)
{
// 对各像素进行灰度统计
unsigned char temp = *((unsigned char *)lpDIBBits + lmageWidth * j + i);
tongji[temp]++;
}
}
return TRUE;
}
BOOL Diedaifazhi(LPSTR lpDIBBits,int lmageWidth,int lmageHeight,int *tongji) //迭代法二值化 程序中要调用上面的函数
{
// 循环变量
LONG i;
LONG j;
// 迭代阀值
int T1, T2;
T1 = 127;
T2 = 0;
// 临时变量
int Temp0, Temp1, Temp2, Temp3;
Temp0 = Temp1 = Temp2 = Temp3 = 0;
while (true)
{
// 计算下一个迭代阀值
for (i = 0; i < T1 + 1; i++)
{
Temp0 += tongji[i] * i;
Temp1 += tongji[i];
}
for (i = T1 + 1; i < 256; i++)
{
Temp2 += tongji[i] * i;
Temp3 += tongji[i];
}
T2 = (Temp0 / Temp1 + Temp2 / Temp3) / 2;
// 看迭代结果是否已收敛
if (T1 == T2)
break;
else
T1 = T2;
}
// 对各像素进行灰度转换
for (j = 0; j < lmageHeight; j ++)
{
for (i = 0; i < lmageWidth; i ++)
{
// 读取像素
unsigned char temp = *((unsigned char *)lpDIBBits + lmageWidth * j + i);
// 判断像素灰度值是否超出范围
if (temp < T1)
temp = 0;
else
temp = 255;
// 回写处理完的像素
*((unsigned char *)lpDIBBits + lmageWidth * j + i) = temp;
}
}
return TRUE;
}
void CDImageProcessView::OnDiedaierzhihua() //迭代法二值化响应在视类中的处理函数
{
CDImageProcessDoc* pDoc = GetDocument();
// 指向DIB的指针
LPSTR lpDIB;
// 指向DIB象素指针
LPSTR lpDIBBits;
// 锁定DIB
lpDIB = (LPSTR) ::GlobalLock((HGLOBAL) pDoc->GetHObject());
// 找到DIB图像象素起始位置
lpDIBBits = pDoc->m_dib.GetBits(lpDIB);
// 判断是否是8-bpp位图
if (pDoc->m_dib.GetColorNum(lpDIB) != 256)
{
// 提示用户
MessageBox("目前只支持256色位图!", "系统提示" ,
MB_ICONINFORMATION | MB_OK);
// 解除锁定
::GlobalUnlock((HGLOBAL) pDoc->GetHObject());
// 返回
return;
}
// 更改光标形状
BeginWaitCursor();
int tongji[256];
//初始为0
memset(tongji, 0, sizeof(tongji));
//统计直方图灰度值和迭代法二值化
if (Fenbutongji(lpDIBBits, pDoc->m_dib.GetWidth(lpDIB), pDoc->m_dib.GetHeight(lpDIB),tongji)&&Diedaifazhi(lpDIBBits, pDoc->m_dib.GetWidth(lpDIB), pDoc->m_dib.GetHeight(lpDIB),tongji))
{
// 设置脏标记
pDoc->SetModifiedFlag(TRUE);
// 更新视图
pDoc->UpdateAllViews(NULL);
}
else
{
// 提示用户
MessageBox("分配内存失败!", "系统提示" , MB_ICONINFORMATION | MB_OK);
}
// 解除锁定
::GlobalUnlock((HGLOBAL) pDoc->GetHObject());
// 恢复光标
EndWaitCursor();// TODO: Add your command handler code here // TODO: Add your command handler code here
// TODO: Add your command handler code here
}