forked from sundeshgupta/encoding-algorithm
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhuffman_decode_image.cpp
135 lines (101 loc) · 2.34 KB
/
huffman_decode_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
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
124
125
126
127
128
129
130
131
132
133
134
135
#include <bits/stdc++.h>
using namespace std;
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"
int parseLine(char* line){
// This assumes that a digit will be found and the line ends in " Kb".
int i = strlen(line);
const char* p = line;
while (*p <'0' || *p > '9') p++;
line[i-3] = '\0';
i = atoi(p);
return i;
}
int getValue(){ //Note: this value is in KB!
FILE* file = fopen("/proc/self/status", "r");
int result = -1;
char line[128];
while (fgets(line, 128, file) != NULL){
if (strncmp(line, "VmRSS:", 6) == 0){
result = parseLine(line);
break;
}
}
fclose(file);
return result;
}
struct pixel{
int label;
pixel* left, *right;
pixel(int x): label(x){
left = NULL;
right = NULL;
}
};
pixel* add(pixel* root, int i, string s, string label){
if(root == NULL){
root = new pixel(-1);
}
if(i == s.length()){
// cout << s << " " << label << endl;
root->label = stoi(label);
return root;
}
if(s[i] == '0'){
root->left = add(root->left, i+1, s, label);
}
else{
root->right = add(root->right, i+1, s, label);
}
return root;
}
void preoder(pixel* root, string s){
if(root == NULL)
return;
if(root->label != -1){
cout << setfill(' ') << setw(3) << root->label
<< " -> " << setw(7) << s << endl;
return;
}
preoder(root->left, s + '0');
preoder(root->right, s + '1');
return;
}
int main()
{
auto start = chrono::high_resolution_clock::now();
ifstream in("huffman_encoded.txt");
int n;
in>>n;
pixel* root = new pixel(-1);
for(int i=0; i<n; i++){
string a,b,c;
in>>a>>b>>c;
add(root, 0, c, a);
}
// for checking
// preoder(root, "");
string w;
in >> w;
pixel* ptr = root;
int height, width, num_channel;
in>>height>>width>>num_channel;
uint8_t* rgb_image;
rgb_image = (uint8_t*) malloc(width*height*num_channel);
int itr = 0;
for(auto i:w){
if(i=='0')
ptr = ptr->left;
else
ptr = ptr->right;
if(ptr->label != -1){
rgb_image[itr++] = char(ptr->label);
ptr = root;
}
}
stbi_write_png("image.bmp", width, height, num_channel, rgb_image, width*num_channel);
auto stop = chrono::high_resolution_clock::now();
auto duration = chrono::duration_cast<chrono::microseconds>(stop - start);
cout<<(duration.count()/1000000.0)<<","<<getValue()<<"\n";
return 0;
}