-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbinary_image.cpp
executable file
·68 lines (61 loc) · 1.78 KB
/
binary_image.cpp
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
#include <iostream>
#include <algorithm>
#include <fstream>
#include <vector>
#include <cstring>
#include "Base/color.h"
#include "Base/pixel.h"
#include "Base/image.h"
#include "binary_image.h"
binary_image::binary_image(Image i): Image(i) {
_bin_arr = new int*[_h];
for(int i = 0; i < _h; i++) {
_bin_arr[i] = new int[_w];
}
binarize(get_treshold());
}
void binary_image::binarize(int treshold) {
for(int i = 0; i < _h; i++) {
for(int j = 0; j < _w; j++) {
if(_arr[i][j].get_brightness() > treshold) {
_arr[i][j].set_color(255, 255, 255);
_bin_arr[i][j] = -1;
}
else {
_arr[i][j].set_color(0, 0, 0);
_bin_arr[i][j] = 0;
};
}
}
}
int** binary_image::get_bin_arr() const {
return _bin_arr;
}
int binary_image::get_treshold() {
int pixel_count[256]; // pixel count of each brightness value.
for(int i = 0; i < 256; i++) pixel_count[i] = 0;
for(int i = 0; i < _h; i++) {
for(int j = 0; j < _w; j++) {
pixel_count[_arr[i][j].get_brightness()%256]++;
}
}
std::vector<int> tresholds;
for(int i = 1; i < 255; i++) {
if(pixel_count[i] < pixel_count[i-1] && pixel_count[i] < pixel_count[i+1]) {
tresholds.push_back(i);
}
}
if(tresholds.size() == 0) {
std::cout << "No treshold found!" << std::endl;
exit(1);
return 0;
}
if(tresholds.size() % 2 == 1) {
std::sort(tresholds.begin(), tresholds.end());
return tresholds.at(tresholds.size()/2);
}
else {
std::sort(tresholds.begin(), tresholds.end());
return (tresholds.at(tresholds.size()/2 - 1) + tresholds.at(tresholds.size()/2))/2;
}
}