forked from karansiwach360/Image-Segmentation
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathotsu.cpp
More file actions
75 lines (75 loc) · 1.66 KB
/
otsu.cpp
File metadata and controls
75 lines (75 loc) · 1.66 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
75
#include <iostream>
#include <omp.h>
#include <opencv/cv.h>
#include "opencv2/highgui/highgui.hpp"
#include <vector>
#include <math.h>
using namespace cv;
using namespace std;
float var(int hist[],int level,float val,int pix_num )
{
long long total=pix_num*val;
int n=0;
long long m=0;
for(int i=0;i<level;i++)
{
m+=i*hist[i];
n+=hist[i];
}
long long rem=total-m;
int rempix=pix_num-n;
float w0=(1.0*n)/(1.0*pix_num);
float w1=(1.0*rem)/(1.0*pix_num);
float u0=(1.0*m)/(1.0*n);
float u1=(1.0*rem)/(1.0*rempix);
return w0*w1*(u0-u1)*(u0-u1);
}
int main()
{
Mat img;
string name="edited.png";
img=imread(name);
cvtColor(img,img,CV_RGB2GRAY);
long long u=0;
int hist[256];
for(int i=0;i<256;i++)
hist[i]=0;
int sz=img.cols*img.rows;
for (int i=0;i<img.rows;i++)
{
for(int j=0;j<img.cols;j++)
{
int n=img.at<uchar>(i,j);
u+=n;
hist[n]++;
}
}
int pix_num=img.rows*img.cols;
float val=(1.0*u)/float(pix_num);
float max=0;
int threshold=0;
for(int i=1;i<255;i++)
{
int x=var(hist,i,val,pix_num);
if(x>max)
{
max=x;
threshold=i;
}
}
for(int i=0;i<img.rows;i++)
{
for(int j=0;j<img.cols;j++)
{
if(img.at<uchar>(i,j)>threshold)
{
img.at<uchar>(i,j)=255;
}
else
img.at<uchar>(i,j)=0;
}
}
imwrite("otsu.png",img);
waitKey(5000);
return 0;
}