Advertisement
Guest User

Untitled

a guest
Sep 19th, 2019
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.03 KB | None | 0 0
  1. /*
  2. * To change this license header, choose License Headers in Project Properties.
  3. * To change this template file, choose Tools | Templates
  4. * and open the template in the editor.
  5. */
  6. package otsu;
  7.  
  8. /**
  9. *
  10. * @author muham
  11. */
  12. class OtsuThresholder {
  13. private int histData[];
  14. private int maxLevelValue;
  15. private int threshold;
  16.  
  17. public OtsuThresholder()
  18. {
  19. histData = new int[256];
  20. }
  21.  
  22. public int[] getHistData()
  23. {
  24. return histData;
  25. }
  26.  
  27. public int getMaxLevelValue()
  28. {
  29. return maxLevelValue;
  30. }
  31.  
  32. public int getThreshold()
  33. {
  34. return threshold;
  35. }
  36.  
  37. public int doThreshold(byte[] srcData, byte[] monoData)
  38. {
  39. int ptr;
  40.  
  41. // Clear histogram data
  42. // Set all values to zero
  43. ptr = 0;
  44. while (ptr < histData.length) histData[ptr++] = 0;
  45.  
  46. // Calculate histogram and find the level with the max value
  47. // Note: the max level value isn't required by the Otsu method
  48. ptr = 0;
  49. maxLevelValue = 0;
  50. while (ptr < srcData.length)
  51. {
  52. int h = 0xFF & srcData[ptr];
  53. histData[h] ++;
  54. if (histData[h] > maxLevelValue) maxLevelValue = histData[h];
  55. ptr ++;
  56. }
  57.  
  58. // Total number of pixels
  59. int total = srcData.length;
  60.  
  61. float sum = 0;
  62. for (int t=0 ; t<256 ; t++) sum += t * histData[t];
  63.  
  64. float sumB = 0;
  65. int wB = 0;
  66. int wF = 0;
  67.  
  68. float varMax = 0;
  69. threshold = 0;
  70.  
  71. for (int t=0 ; t<256 ; t++)
  72. {
  73. wB += histData[t]; // Weight Background
  74. if (wB == 0) continue;
  75.  
  76. wF = total - wB; // Weight Foreground
  77. if (wF == 0) break;
  78.  
  79. sumB += (float) (t * histData[t]);
  80.  
  81. float mB = sumB / wB; // Mean Background
  82. float mF = (sum - sumB) / wF; // Mean Foreground
  83.  
  84. // Calculate Between Class Variance
  85. float varBetween = (float)wB * (float)wF * (mB - mF) * (mB - mF);
  86.  
  87. // Check if new maximum found
  88. if (varBetween > varMax) {
  89. varMax = varBetween;
  90. threshold = t;
  91. }
  92. }
  93.  
  94. // Apply threshold to create binary image
  95. if (monoData != null)
  96. {
  97. ptr = 0;
  98. while (ptr < srcData.length)
  99. {
  100. monoData[ptr] = ((0xFF & srcData[ptr]) >= threshold) ? (byte) 255 : 0;
  101. ptr ++;
  102. }
  103. }
  104.  
  105. return threshold;
  106. }
  107. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement