SHARE
TWEET

Global_Thresholding

a guest Sep 19th, 2019 86 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. clear, clc, close all
  2.  
  3. % Load test image
  4. img = im2double(imread('paper.png'));
  5.  
  6. % Perform global thresholding with Otsu's method
  7. level = graythresh(img);
  8. globalBwImg = im2bw(img, level);
  9.  
  10. % Decide local thresholding parameters
  11. [row col] = size(img);
  12. stepSize = 16;
  13. tileSize = 32;
  14. varThresh = 0.0005;
  15.  
  16. % Perform locally adaptive thresholding
  17. localBwImg = zeros(row, col);
  18. uniformMask = zeros(row, col);
  19. threshIm = zeros(row / stepSize, col/ stepSize);
  20. for i = 1: row / stepSize
  21.  
  22. % Get indices for row
  23. rowStep = (i - 1) * stepSize + 1 : i * stepSize;
  24. rowTile = (i - 1) * stepSize + 1 : (i + 1) * stepSize;
  25. if i == row / stepSize
  26. rowTile = (i-2) * stepSize + 1 : i * stepSize;
  27. end
  28.  
  29. % Calculate Otsu's threshold for row
  30. rowThresh = graythresh(img(rowTile, :));
  31. for j = 1: col / stepSize
  32.  
  33. % Get indices for column
  34. colStep = (j - 1) * stepSize + 1 : j * stepSize;
  35. colTile = (j - 1) * stepSize + 1 : (j + 1) * stepSize;
  36. if j == col / stepSize
  37. colTile = (j - 2) * stepSize + 1 : j * stepSize;
  38. end
  39.  
  40. % Calculate local variance
  41. step = img(rowStep, colStep);
  42. varStep = var(step(:));
  43.  
  44. % Calculate local Otsu's threshold
  45. tile = img(rowTile, colTile);
  46. localThresh = graythresh(tile);
  47.  
  48. % Threshold based on local Otsu's threshold
  49. if (varStep > varThresh)
  50. localBwImg(rowStep, colStep) = im2bw(step, localThresh);
  51. uniformMask(rowStep, colStep) = ones(stepSize, stepSize);
  52. threshIm(i, j) = localThresh;
  53.  
  54. % Threshold based on local mean
  55. else
  56. localMean = mean(tile(:));
  57. threshIm(i, j) = 0;
  58. if (localMean > min(rowThresh,level))
  59. localBwImg(rowStep, colStep) = ones(stepSize, stepSize);
  60. else
  61. localBwImg(rowStep, colStep) = zeros(stepSize, stepSize);
  62. end
  63. uniformMask(rowStep, colStep) = zeros(stepSize, stepSize);
  64. end
  65. end % j
  66. end % i
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top