图像自适应二值化方法---迭代阈值法

通过迭代方法选择阈值, 计算方法如下:

(1)选择灰度图的平均值作为初始阈值T0 ;

(2)计算小于等于T0的平均值T1, 和大于T0的平均值T2;

(3)新的阈值为T = (T1 + T2)/ 2;

(4)比较T和T0,若相等,则返回T,即为迭代阈值; 否则 T0 = T,重复(1)-(3)

  1. #include'cv.h'
  2. #include 'highgui.h'
  3. int IterationThreshold(CvMat* gray);
  4. int main()
  5. {
  6. IplImage *src = cvLoadImage('flower.jpg',1);
  7. const int width = src->width;
  8. const int height = src->height;
  9. CvMat *gray = cvCreateMat(height, width, CV_8UC1);
  10. cvCvtColor(src, gray, CV_BGR2GRAY);
  11. int thres = IterationThreshold(gray);
  12. cvThreshold(gray, gray, thres, 255, CV_THRESH_BINARY);
  13. cvShowImage('SRC', src);
  14. cvShowImage('GRAY', gray);
  15. cvWaitKey(0);
  16. cvCvtColor(gray, src, CV_GRAY2BGR);
  17. cvSaveImage('DST.bmp', src);
  18. cvReleaseMat(&gray);
  19. return 0;
  20. }
  21. int IterationThreshold(CvMat* gray)
  22. {
  23. int width = gray->width;
  24. int height = gray->height;
  25. //直方图统计
  26. int histData[256] = {0};
  27. for(int j = 0; j < height; j ++)
  28. {
  29. uchar*data = (uchar*)(gray->data.ptr + j * gray->step);
  30. for (int i = 0; i < width; i ++)
  31. {
  32. histData[data[i]]++;
  33. }
  34. }
  35. //求图像的平均灰度值作为初始阈值
  36. int T0 = 0;
  37. for (int i = 0; i < 256; i ++)
  38. {
  39. T0 += i * histData[i];
  40. }
  41. T0 /= width * height;
  42. //迭代
  43. int T1 = 0, T2 = 0;
  44. int num1 = 0, num2 = 0;
  45. int T = 0;
  46. while (1)
  47. {
  48. for ( int i = 0; i < T0+1; i ++)
  49. {
  50. T1 += i * histData[i];
  51. num1 += histData[i];
  52. }
  53. if (num1 == 0)
  54. continue;
  55. for ( int i = T0 + 1; i < 256; i ++)
  56. {
  57. T2 += i * histData[i];
  58. num2 += histData[i];
  59. }
  60. if (num2 == 0)
  61. continue;
  62. T = (T1 / num1 + T2 / num2) / 2;
  63. if ( T == T0 )
  64. break;
  65. else
  66. T0 = T;
  67. }
  68. return T;
  69. }

源图和效果图如下:

(0)

相关推荐