PageRenderTime 39ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 1ms

/image_analysisII/bookcode/visionbook/06Segm1/imthresh.m

http://uppsala-university.googlecode.com/
Objective C | 56 lines | 49 code | 7 blank | 0 comment | 2 complexity | 3069297246fe6085bb83b49fb3d93293 MD5 | raw file
Possible License(s): BSD-2-Clause
  1. function [out,threshold]=imthresh(im)
  2. %IMTHRESH Iterative (optimal) image thresholding.
  3. % CMP Vision Algorithms http://visionbook.felk.cvut.cz
  4. %
  5. % Threshold a grayscale image using an automatic iterative threshold selection
  6. % .
  7. %
  8. % Usage: [out,threshold] = imthresh(im)
  9. % Inputs:
  10. % im [m x n] Input grayscale image with intensities 0... 255.
  11. % Outputs:
  12. % out [m x n] Binary output image, contains ones where the pixel
  13. % values of im are above or equal to the threshold and
  14. % zeros elsewhere.
  15. % threshold 1x1 Threshold value.
  16. %
  17. % We pre-calculate the histogram and cumulative histogram. This way
  18. % we can evaluate in constant time the mean of the pixels above or below
  19. % threshold.
  20. histogram = hist( im(:), 0:255 );
  21. hist_times_gray = cumsum( histogram.*[0:255] );
  22. cumulative_histogram = cumsum( histogram );
  23. % A first approximation of the background mean mean_1 is
  24. % the mean of the corner pixels. A first approximation of the foreground
  25. % mean mean_2 is the mean of the rest of the image.
  26. % The initial threshold
  27. % is set as an average of the two means.
  28. [m,n] = size(im);
  29. sum_background = sum( im([1 m n*(m-1)+1 n*m]) );
  30. num_pix_background = 4;
  31. mean_1 = sum_background / num_pix_background;
  32. mean_2 = (sum(im(:))-sum_background) / (n*m-num_pix_background);
  33. threshold = ceil( (mean_1+mean_2)/2 );
  34. if (threshold~=0)&&(cumulative_histogram(threshold)==0)
  35. threshold_old=threshold;
  36. end;
  37. % We calculate new foreground and background means defined by the
  38. % threshold and use them to calculate the new threshold, repeating until
  39. % convergence. The procedure is very fast because the actual thresholding
  40. % only takes place once the final threshold is found.
  41. threshold_old = 0;
  42. while threshold~=threshold_old
  43. threshold_old = threshold;
  44. mean_1 = hist_times_gray(threshold) / cumulative_histogram(threshold);
  45. mean_2 = (hist_times_gray(end)-hist_times_gray(threshold+1)) / ...
  46. (cumulative_histogram(end)-cumulative_histogram(threshold+1));
  47. threshold = ceil( (mean_1+mean_2)/2 );
  48. end
  49. out = im>=threshold;