此二值化阈值计算理论并非本人提出,只是之前在一个博客上看到过(忘了作者,对不住啊
),故用c实现了下,很简单的一个方法
![微笑](http://static.blog.csdn.net/xheditor/xheditor_emot/default/smile.gif)
基本思想:二值化取阈值 先随机设置一个阈值 然后求255和0两部分像素的平均值 再求二值化平均作为当前阈值 直到两次阈值相等
GrayImage是指向YUV原图像的指针,ImageWidth是图像宽度
int ThreshforBinary(unsigned char *GrayImage, POINT ColX, POINT RowY, int InitThresh)
{
int iCol, iRow;
int ForeThresh , CurThresh = 0;
int sum255value = 0, sum0value = 0, num255 = 0, num0 = 0, avg255 = 0, avg0 = 0;
ForeThresh = InitThresh;
while(1)
{
sum255value = 0,sum0value = 0; num255 = 0, num0 = 0, avg255 = 0, avg0 = 0;
for(iCol = ColX.x; iCol <= ColX.y; iCol++)
{
for(iRow = RowY.x; iRow <= RowY.y; iRow++)
{
if( *(GrayImage + 2 * (iRow ) * ImageWidth + 2 * iCol) >= ForeThresh)
{
sum255value += *(GrayImage + 2 * (iRow ) * ImageWidth + 2 * iCol);
num255 ++;
}
else
{
sum0value += *(GrayImage + 2 * (iRow ) * ImageWidth + 2 * iCol);
num0 ++;
}
}
}
avg255 = sum255value / num255;
avg0 = sum0value / num0;
CurThresh = (avg255 + avg0) / 2;
if(abs(CurThresh - ForeThresh) >=1)
ForeThresh = CurThresh;
else
break;
}
return CurThresh;
}