用在片上系统上的
1 //OSTU求图像的阈值 2 u8 otsuThreshold(u8 **img, u16 height, u16 width) 3 { 4 // int width = frame->width; 5 // int height = frame->height; 6 u16 pixelCount[256]; 7 float pixelPro[256]; 8 u16 i, j, pixelSum = width * height, threshold = 0; 9 //遍历灰度级[0,255] 10 float w0, w1, u0tmp, u1tmp, u0, u1, u, deltaTmp, deltaMax = 0; 11 //u8* data = (uchar*)frame->imageData; 12 13 for(i = 0; i < 256; i++) 14 { 15 pixelCount[i] = 0; 16 pixelPro[i] = 0; 17 } 18 19 //统计灰度级中每个像素在整幅图像中的个数 20 for(i = 0; i < height; i++) 21 { 22 for(j = 0;j < width;j++) 23 { 24 pixelCount[ img[i][j] ]++; 25 } 26 } 27 28 //计算每个像素在整幅图像中的比例 29 for(i = 0; i < 256; i++) 30 { 31 pixelPro[i] = (float)pixelCount[i] / pixelSum; 32 } 33 34 for(i = 0; i < 256; i++) 35 { 36 w0 = w1 = u0tmp = u1tmp = u0 = u1 = u = deltaTmp = 0; 37 for(j = 0; j < 256; j++) 38 { 39 if(j <= i) //背景部分 40 { 41 w0 += pixelPro[j]; 42 u0tmp += j * pixelPro[j]; 43 } 44 else //前景部分 45 { 46 w1 += pixelPro[j]; 47 u1tmp += j * pixelPro[j]; 48 } 49 } 50 u0 = u0tmp / w0; 51 u1 = u1tmp / w1; 52 u = u0tmp + u1tmp; 53 deltaTmp = w0 * pow((u0 - u), 2) + w1 * pow((u1 - u), 2); 54 if(deltaTmp > deltaMax) 55 { 56 deltaMax = deltaTmp; 57 threshold = i; 58 } 59 } 60 61 return threshold; 62 }