-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmultithresh.cpp
More file actions
79 lines (71 loc) · 2.19 KB
/
multithresh.cpp
File metadata and controls
79 lines (71 loc) · 2.19 KB
1
2
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
/*
* multithresh.cpp
*
* Created on: 19-Jan-2016
* Author: mukesh_kumar
* function
* int calculatethreshold(Mat img);
*
* calculate threshold using Otsu's Binarization method and return int ;
* link for Otsu's Binarization
* https://en.wikipedia.org/wiki/Otsu%27s_method#Method
*
*/
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int calculatethreshold(Mat img){
int nbHistLevels = 256;
// calculate histogram
int *histData = (int*)calloc(nbHistLevels, sizeof(int));
int ptr = 0;
while (ptr < img.total()) {
int h = img.data[ptr];
histData[h]++;
ptr ++;
}
// total number of pixels
int total = img.total();
float sum = 0;
int t;
float sumB = 0;
int wB = 0;
int wF = 0;
float varMax = 0;
int threshold = 0;
for (t=0; t < nbHistLevels; t++)
sum += t * histData[t];
for (t=0; t < nbHistLevels; t++) {
wB += histData[t]; // Weight Background
if (wB == 0)
continue;
wF = total - wB; // Weight Foreground
if (wF == 0)
break;
sumB += (float) (t * histData[t]);
float mB = sumB / wB; // Mean Background
float mF = (sum - sumB) / wF; // Mean Foreground
// Calculate Between Class Variance
float varBetween = (float)wB * (float)wF * (mB - mF) * (mB - mF);
// Check if new maximum found
if (varBetween > varMax) {
varMax = varBetween;
threshold = t;
}
}
return threshold;
}
int main(int argc, char **argv) {
Mat img=imread(argv[1],0);
Mat src32f;
img.convertTo(src32f,CV_8UC1); //convert image to CV_8UC1
int thresholdvalue=calculatethreshold(src32f);// calculate threshold value
cout<<"Otsu's Binarization threshold for image is "<<threshold<<endl;
namedWindow("threshold image",WINDOW_AUTOSIZE);
Mat dest;
threshold(img,dest,(double)thresholdvalue,255,THRESH_OTSU);
imshow("threshold image",dest);
waitKey();
return 0;
}