Advertisement
Guest User

Untitled

a guest
May 23rd, 2019
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.51 KB | None | 0 0
  1. void otsu() {
  2.  
  3. char fname[10000];
  4.  
  5. while (openFileDlg(fname))
  6. {
  7.  
  8. Mat img = imread(fname, CV_LOAD_IMAGE_GRAYSCALE);
  9. imshow("original image", img);
  10.  
  11. Mat dst = Mat::zeros(img.rows, img.cols, CV_8UC1);
  12.  
  13.  
  14.  
  15. for (int i = 0; i < 256; i++)
  16. {
  17. histValues[i] = 0;
  18. }
  19.  
  20.  
  21. for (int i = 0; i < img.rows; i++)
  22. {
  23. for (int j = 0; j < img.cols; j++)
  24. {
  25. histValues[img.at<uchar>(i, j)]++;
  26. }
  27. }
  28.  
  29. for (int i = 0; i < 256; i++)
  30. {
  31. histNorm[i] = (double)histValues[i] / 256;
  32. }
  33.  
  34. showHistogram("MyHist", histValues, 256, 500);
  35. showHistogram("MyHistNormalized", histNorm, 256, 500);
  36.  
  37.  
  38. double miu = 0;
  39. double suma = 0, sumaB = 0;
  40. int N, threshold, q1 = 0, q2 = 0, miu1 = 0, miu2 = 0;
  41. N = img.rows * img.cols;
  42.  
  43. double teta = 0, var_max = 0;
  44.  
  45.  
  46. for (int i = 0; i < 256; i++)
  47. {
  48. suma += i * histValues[i];
  49. }
  50.  
  51.  
  52.  
  53.  
  54. for (int t = 0; t < 256; t++)
  55. {
  56. q1 += histValues[t];
  57.  
  58. if (q1 != 0)
  59. {
  60. q2 = N - q1;
  61.  
  62. sumaB += t * histValues[t];
  63.  
  64. miu1 = sumaB / q1;
  65. miu2 = (suma - sumaB) / q2;
  66.  
  67.  
  68. teta = q1 * q2 * (miu1 - miu2) * (miu1 - miu2);
  69.  
  70. if (teta > var_max)
  71. {
  72. threshold = t;
  73. var_max = teta;
  74. }
  75. }
  76.  
  77. }
  78.  
  79. printf("Threshold = %d", threshold);
  80.  
  81. for (int i = 0; i < img.rows; i++) {
  82. for (int j = 0; j < img.cols; j++)
  83. {
  84. if (img.at<uchar>(i, j) > threshold)
  85. dst.at<uchar>(i, j) = 255;
  86. else
  87. dst.at<uchar>(i, j) = 0;
  88.  
  89. }
  90. }
  91.  
  92. imshow("Otsu", dst);
  93.  
  94. }
  95.  
  96. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement