Advertisement
Guest User

Untitled

a guest
Feb 18th, 2020
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.02 KB | None | 0 0
  1. #include <stdio.h>
  2. #include<opencv2/core/core.hpp>
  3. #include<opencv2/highgui/highgui.hpp>
  4. #include <opencv2/imgproc/imgproc.hpp>
  5. #include <stdlib.h>
  6. #include <opencv2/opencv.hpp>
  7. #include <iostream>
  8.  
  9.  
  10. using namespace std;
  11. using namespace cv;
  12.  
  13. uchar maxentropie(const Mat1b& src, Mat1b& dst)
  14. {
  15. // Histogram
  16. Mat1d hist(1, 256, 0.0);
  17. for (int r = 0; r < src.rows; ++r) {
  18.  
  19.  
  20.  
  21. for (int c = 0; c < src.cols; ++c)
  22. hist(src(r, c))++;
  23.  
  24. // Normalize
  25. hist = hist / double(src.rows * src.cols);
  26.  
  27.  
  28. }
  29.  
  30. // Cumulative histogram
  31. Mat1d cumhist(1, 256, 0.0);
  32. float sum = 0;
  33. for (int i = 0; i < 256; ++i)
  34. {
  35. sum += hist(i);
  36. cumhist(i) = sum;
  37. }
  38.  
  39. Mat1d hl(1, 256, 0.0);
  40. Mat1d hh(1, 256, 0.0);
  41.  
  42. for (int t = 0; t < 256; ++t)
  43. {
  44. // low range entropy
  45. double cl = cumhist(t);
  46. if (cl > 0)
  47. {
  48. for (int i = 0; i <= t; ++i)
  49. {
  50. if (hist(i) > 0)
  51. {
  52. hl(t) = hl(t) - (hist(i) / cl) * log(hist(i) / cl);
  53. }
  54. }
  55. }
  56.  
  57. // high range entropy
  58. double ch = 1.0 - cl; // constraint cl + ch = 1
  59. if (ch > 0)
  60. {
  61. for (int i = t + 1; i < 256; ++i)
  62. {
  63. if (hist(i) > 0)
  64. {
  65. hh(t) = hh(t) - (hist(i) / ch) * log(hist(i) / ch);
  66. }
  67. }
  68. }
  69. }
  70.  
  71. // choose best threshold
  72.  
  73. Mat1d entropie(1, 256, 0.0);
  74. double h_max = hl(0) + hh(0);
  75. uchar threshold = 0;
  76. entropie(0) = h_max;
  77.  
  78. for (int t = 1; t < 256; ++t)
  79. {
  80. entropie(t) = hl(t) + hh(t);
  81. if (entropie(t) > h_max)
  82. {
  83. h_max = entropie(t);
  84. threshold = uchar(t);
  85. printf("%d, ", threshold);
  86.  
  87. }
  88.  
  89. printf("%d, ", threshold);
  90. }
  91.  
  92. // Create output image
  93. dst = src > threshold;
  94.  
  95. return threshold;
  96. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement