Skip to content

Commit 1691075

Browse files
committed
upload
1 parent 517ddf1 commit 1691075

File tree

1 file changed

+134
-0
lines changed

1 file changed

+134
-0
lines changed

improved-huffman-decode_image.cpp

Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
#include <bits/stdc++.h>
2+
3+
using namespace std;
4+
5+
#define STB_IMAGE_WRITE_IMPLEMENTATION
6+
#include "stb_image_write.h"
7+
8+
struct pixel{
9+
int label;
10+
pixel* left, *right;
11+
12+
pixel(int x): label(x){
13+
left = NULL;
14+
right = NULL;
15+
}
16+
17+
};
18+
19+
bool flag[256];
20+
int cnt = 256;
21+
22+
pixel* add(pixel* root, int i, string s, string label, int level = 0){
23+
24+
if(root == NULL){
25+
root = new pixel(cnt++);
26+
}
27+
28+
if(i == s.length()){
29+
cout << s << " " << (stoi(label)) << " " << label << endl;
30+
root->label = stoi(label);
31+
if(level > 3){
32+
flag[root->label] = 1;
33+
}
34+
return root;
35+
}
36+
37+
if(s[i] == '0'){
38+
root->left = add(root->left, i+1, s, label, level+1);
39+
}
40+
else{
41+
root->right = add(root->right, i+1, s, label, level+1);
42+
}
43+
44+
return root;
45+
}
46+
47+
void preoder(pixel* root, string s){
48+
49+
if(root == NULL)
50+
return;
51+
52+
if(root->label < 256){
53+
cout << setfill(' ') << setw(3) << root->label
54+
<< " -> " << setw(7) << s << endl;
55+
return;
56+
}
57+
58+
preoder(root->left, s + '0');
59+
preoder(root->right, s + '1');
60+
61+
return;
62+
}
63+
64+
int main(){
65+
ifstream in("improved_huffman_encoded.txt");
66+
int n;
67+
in>>n;
68+
pixel* root = new pixel(cnt++);
69+
for(int i=0; i<n; i++){
70+
string b, c;
71+
string a;
72+
in>>a>>b>>c;
73+
add(root, 0, c, a);
74+
}
75+
76+
// for checking
77+
preoder(root, "");
78+
79+
string w;
80+
in >> w;
81+
82+
pixel* ptr = root;
83+
pixel* tmp = root;
84+
85+
int height, width, num_channel;
86+
87+
in>>height>>width>>num_channel;
88+
89+
uint8_t* rgb_image;
90+
rgb_image = (uint8_t*) malloc(width*height*num_channel);
91+
92+
int itr = 0;
93+
bool f = 0;
94+
int level = 0;
95+
for(auto i:w){
96+
if(f){
97+
if(i == '0'){
98+
// do nothing
99+
}
100+
else{
101+
ptr = tmp;
102+
}
103+
f = 0;
104+
continue;
105+
}
106+
107+
if(i=='0')
108+
ptr = ptr->left;
109+
else
110+
ptr = ptr->right;
111+
112+
level += 1;
113+
114+
if(level == 3)
115+
tmp = ptr;
116+
117+
if(ptr->label < 256){
118+
119+
rgb_image[itr++] = ptr->label;
120+
121+
level = 0;
122+
123+
if(flag[ptr->label])
124+
f = 1;
125+
126+
ptr = root;
127+
}
128+
}
129+
130+
stbi_write_png("improved_image.png", width, height, num_channel, rgb_image, width*num_channel);
131+
132+
133+
return 0;
134+
}

0 commit comments

Comments
 (0)