| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 
 | #include <opencv/highgui.h>#include <opencv2/opencv.hpp>
 #include <cmath>
 
 
 int OSTU(cv::Mat& src)
 {
 int threshold=0;
 float sigma_temp=0.0f;
 float sigma_max = 0.0f;
 int pixel_num = src.rows * src.cols;
 int pixel_count[256];
 float pixel_pro[256];
 
 
 for(int i=0; i<256; i++)
 {
 pixel_count[i] = 0;
 }
 
 
 for(int i=0; i < src.rows; i++)
 {
 uchar* data = src.ptr<uchar>(i);
 
 for(int j=0; j < src.cols; j++)
 {
 pixel_count[data[j]]++;
 }
 }
 
 
 for(int i=0; i<256; i++)
 {
 pixel_pro[i] = (float)(pixel_count[i]) / (float)(pixel_num);
 }
 
 
 for(int i=0; i<256; i++)
 {
 float w0=0, w1=0, u0=0, u1=0, u=0;
 
 for(int j=0; j<256; j++)
 {
 
 if(j < i)
 {
 w0 += pixel_pro[j];
 u0 += pixel_pro[j] * j;
 }
 else
 {
 u1 += pixel_pro[j] * j;
 }
 }
 
 
 
 
 
 sigma_temp = w0 * (1-w0) * pow((u0 - u1), 2);
 
 
 if(sigma_temp > sigma_max)
 {
 sigma_max = sigma_temp;
 threshold = i;
 }
 }
 
 return threshold;
 }
 
 
 void BinaryImage(cv::Mat& src, cv::Mat& des, int threshold)
 {
 for(int i=0; i < src.rows; i++)
 {
 uchar* src_data = src.ptr<uchar>(i);
 uchar* des_data = des.ptr<uchar>(i);
 
 for(int j=0; j < src.cols; j++)
 {
 if(src_data[j] < threshold)
 {
 des_data[j] = 0;
 }
 else
 {
 des_data[j] = 255;
 }
 }
 }
 }
 
 int main()
 {
 cv::Mat src, gray;
 
 cv::namedWindow("src", cv::WINDOW_NORMAL);
 cv::namedWindow("gray", cv::WINDOW_NORMAL);
 cv::namedWindow("binary", cv::WINDOW_NORMAL);
 
 
 src = cv::imread("../wallhaven-698240.jpg", cv::IMREAD_COLOR);
 cv::cvtColor(src, gray, cv::COLOR_RGB2GRAY);
 
 int threshold = OSTU(gray);
 
 cv::Mat binary = cv::Mat(gray.rows, gray.cols, CV_8U);
 BinaryImage(gray, binary, threshold);
 
 printf("threshold: %d\n", threshold);
 
 
 cv::imshow("src", src);
 cv::imshow("gray", gray);
 cv::imshow("binary", binary);
 
 cv::waitKey(0);
 
 return 0;
 }
 
 |