[代码片段]OSTU算法

时间:2021-11-06 07:58:04

用在片上系统上的

 //OSTU求图像的阈值
u8 otsuThreshold(u8 **img, u16 height, u16 width)
{
// int width = frame->width;
// int height = frame->height;
u16 pixelCount[];
float pixelPro[];
u16 i, j, pixelSum = width * height, threshold = ;
//遍历灰度级[0,255]
float w0, w1, u0tmp, u1tmp, u0, u1, u, deltaTmp, deltaMax = ;
//u8* data = (uchar*)frame->imageData; for(i = ; i < ; i++)
{
pixelCount[i] = ;
pixelPro[i] = ;
} //统计灰度级中每个像素在整幅图像中的个数
for(i = ; i < height; i++)
{
for(j = ;j < width;j++)
{
pixelCount[ img[i][j] ]++;
}
} //计算每个像素在整幅图像中的比例
for(i = ; i < ; i++)
{
pixelPro[i] = (float)pixelCount[i] / pixelSum;
} for(i = ; i < ; i++)
{
w0 = w1 = u0tmp = u1tmp = u0 = u1 = u = deltaTmp = ;
for(j = ; j < ; j++)
{
if(j <= i) //背景部分
{
w0 += pixelPro[j];
u0tmp += j * pixelPro[j];
}
else //前景部分
{
w1 += pixelPro[j];
u1tmp += j * pixelPro[j];
}
}
u0 = u0tmp / w0;
u1 = u1tmp / w1;
u = u0tmp + u1tmp;
deltaTmp = w0 * pow((u0 - u), ) + w1 * pow((u1 - u), );
if(deltaTmp > deltaMax)
{
deltaMax = deltaTmp;
threshold = i;
}
} return threshold;
}