-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcpp_py_test_had.cpp
More file actions
366 lines (300 loc) · 12.3 KB
/
cpp_py_test_had.cpp
File metadata and controls
366 lines (300 loc) · 12.3 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
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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
#include "image_encoding_had.hpp"
#include "encoding_library/ArithmeticCoder.hpp"
#include "encoding_library/BitIoStream.hpp"
#include "encoding_library/FrequencyTable.hpp"
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
#include <ctime>
#define BLOCK_SIZE 8
using namespace std;
std::unordered_map<int32_t, int32_t> computeFrequencyTable(const std::vector<int32_t>& data) {
std::unordered_map<int32_t, int32_t> freqMap;
for (const auto& val : data) {
freqMap[val]++;
}
return freqMap;
}
void arithmeticEncodeFromFile(const std::string& inputFile, const std::string& outputFile) {
time_t timestamp;
// Open input file for reading
std::ifstream inFile(inputFile, std::ios::binary);
if (!inFile.is_open()) {
throw std::runtime_error("Failed to open input file");
}
// Read metadata (rows, cols, channels)
int32_t rows, cols, channels;
inFile.read(reinterpret_cast<char*>(&rows), sizeof(rows));
inFile.read(reinterpret_cast<char*>(&cols), sizeof(cols));
inFile.read(reinterpret_cast<char*>(&channels), sizeof(channels));
// Validate metadata
if (rows <= 0 || cols <= 0 || channels <= 0) {
throw std::runtime_error("Invalid image dimensions in the input file");
}
cout << "Encodin with dimensions (W, H)" << cols << rows <<endl;
// Read pixel data
size_t totalPixels = static_cast<size_t>(rows) * cols * channels;
std::vector<int32_t> imgData(totalPixels);
inFile.read(reinterpret_cast<char*>(imgData.data()), totalPixels * sizeof(int32_t));
inFile.close();
// Compute frequency table
auto freqMap = computeFrequencyTable(imgData);
// Prepare frequency table for Nayuki encoder
std::vector<uint32_t> freqs;
std::vector<int32_t> symbols;
for (const auto& pair : freqMap) {
symbols.push_back(pair.first);
freqs.push_back(pair.second);
}
SimpleFrequencyTable freqTable(freqs);
// Open output file for writing
std::ofstream outFile(outputFile, std::ios::binary);
if (!outFile.is_open()) {
throw std::runtime_error("Failed to open output file");
}
// Write image shape to file
outFile.write(reinterpret_cast<const char*>(&rows), sizeof(rows));
outFile.write(reinterpret_cast<const char*>(&cols), sizeof(cols));
outFile.write(reinterpret_cast<const char*>(&channels), sizeof(channels));
// Write number of unique symbols
int32_t numSymbols = freqMap.size();
outFile.write(reinterpret_cast<const char*>(&numSymbols), sizeof(numSymbols));
// Write symbols and frequencies
for (size_t i = 0; i < symbols.size(); ++i) {
int32_t symbol = symbols[i];
int32_t freq = freqs[i];
outFile.write(reinterpret_cast<const char*>(&symbol), sizeof(symbol));
outFile.write(reinterpret_cast<const char*>(&freq), sizeof(freq));
}
// Initialize arithmetic encoder
BitOutputStream bitOut(outFile);
ArithmeticEncoder encoder(32, bitOut);
// Encode data
// Precompute symbol index for fast lookup
std::unordered_map<int32_t, size_t> symbolIndexMap;
size_t index = 0;
for (const auto& pair : freqMap) {
symbolIndexMap[pair.first] = index++;
}
// Encode data using precomputed indexes (O(1) lookup instead of std::find)
for (const auto& val : imgData) {
encoder.write(freqTable, symbolIndexMap[val]);
}
// Finish encoding
encoder.finish();
//bitOut.close();
outFile.close();
std::cout << "Encoding complete. Output written to " << outputFile << std::endl;
}
BigPixelMatrix get_pixel_matrix(string image_path) {
// Open the file in binary mode
std::ifstream inFile(image_path, std::ios::binary);
if (!inFile.is_open()) {
throw std::runtime_error("Failed to open input file");
}
// Read metadata (rows, cols, channels)
int32_t rows, cols, channels;
inFile.read(reinterpret_cast<char*>(&rows), sizeof(rows));
inFile.read(reinterpret_cast<char*>(&cols), sizeof(cols));
inFile.read(reinterpret_cast<char*>(&channels), sizeof(channels));
// Validate metadata
if (rows <= 0 || cols <= 0 || channels <= 0) {
throw std::runtime_error("Invalid image dimensions in the input file");
}
// Compute total number of pixels
size_t totalPixels = static_cast<size_t>(rows) * cols * channels;
// Create a buffer to read the pixel data
vector<int32_t> buffer(totalPixels);
// Read pixel data into the buffer
inFile.read(reinterpret_cast<char*>(buffer.data()), totalPixels * sizeof(int32_t));
inFile.close();
// Initialize the BigPixelMatrix to store the 3D image data
BigPixelMatrix imgData(rows, vector<vector<int32_t>>(cols, vector<int32_t>(channels)));
// Populate imgData from the flat buffer
size_t index = 0;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
for (int k = 0; k < channels; ++k) {
imgData[i][j][k] = buffer[index++];
}
}
}
return imgData;
}
void write_pixel_matrix(const BigPixelMatrix& imgData, const string& output_path) {
// Get dimensions from the matrix
int32_t rows = imgData.size();
int32_t cols = imgData[0].size();
int32_t channels = imgData[0][0].size();
// Open output file for writing in binary mode
std::ofstream outFile(output_path, std::ios::binary);
if (!outFile.is_open()) {
throw std::runtime_error("Failed to open output file");
}
// Write metadata (rows, cols, channels)
outFile.write(reinterpret_cast<const char*>(&rows), sizeof(rows));
outFile.write(reinterpret_cast<const char*>(&cols), sizeof(cols));
outFile.write(reinterpret_cast<const char*>(&channels), sizeof(channels));
// Compute total number of pixels
size_t totalPixels = static_cast<size_t>(rows) * cols * channels;
// Create a buffer to store the flattened data
vector<int32_t> buffer(totalPixels);
// Flatten the 3D matrix into the buffer
size_t index = 0;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
for (int k = 0; k < channels; ++k) {
buffer[index++] = imgData[i][j][k];
}
}
}
// Write the pixel data
outFile.write(reinterpret_cast<const char*>(buffer.data()), totalPixels * sizeof(int32_t));
outFile.close();
if (!outFile) {
throw std::runtime_error("Error occurred while writing to file");
}
}
BigPixelMatrix transform_pixels(BigPixelMatrix pixelMatrix, TransformationMatrix transformationMatrix, TransformationMatrix transposedTransformationMatrix) {
int orig_height = pixelMatrix.size();
int orig_width = pixelMatrix[0].size();
int channels = pixelMatrix[0][0].size();
int block_size = BLOCK_SIZE;
// Calculate padded dimensions
int padded_height = ((orig_height + block_size - 1) / block_size) * block_size;
int padded_width = ((orig_width + block_size - 1) / block_size) * block_size;
cout << "Original dimensions: " << orig_height << "x" << orig_width << endl;
cout << "Padded dimensions: " << padded_height << "x" << padded_width << endl;
// Create padded matrix
BigPixelMatrix transformed(padded_height, BigPixelRow(padded_width, vector<int32_t>(channels, 0)));
int block_counter = 0;
for (int channel = 0; channel < channels; ++channel) {
for (int row = 0; row < padded_height; row += block_size) {
for (int col = 0; col < padded_width; col += block_size) {
block_counter++;
vector<vector<int32_t>> segment(block_size, vector<int32_t>(block_size, 0)); // Initialize with zeros
// Extract the segment for the current channel, using original data where available
for (int i = 0; i < block_size; ++i) {
for (int j = 0; j < block_size; ++j) {
if (row + i < orig_height && col + j < orig_width) {
segment[i][j] = pixelMatrix[row + i][col + j][channel];
}
// else leave as 0 (padding)
}
}
// Apply transformation
if (channel==0 && row == 0 && col == 0) {
testVec(segment);
}
segment = matrix_multiply(transformationMatrix, segment);
if (channel==0 && row == 0 && col == 0) {
testVec(segment);
}
segment = matrix_multiply(segment, transposedTransformationMatrix);
if (channel==0 && row == 0 && col == 0) {
testVec(segment);
}
// Store the transformed segment
for (int i = 0; i < block_size; ++i) {
for (int j = 0; j < block_size; ++j) {
transformed[row + i][col + j][channel] = (segment[i][j]);
}
}
}
}
}
cout << "Number of blocks created: " << block_counter << endl;
return transformed;
}
TransformationMatrix get_quantization_matrix_luminance() {
return {
{4, 3, 4, 4, 4, 6, 11, 15},
{3, 3, 3, 4, 5, 8, 14, 19},
{3, 4, 4, 5, 8, 12, 16, 20},
{4, 5, 6, 7, 12, 14, 18, 20},
{6, 6, 9, 11, 14, 17, 21, 23},
{9, 12, 12, 18, 23, 22, 25, 21},
{11, 13, 15, 17, 21, 23, 25, 21},
{13, 12, 12, 13, 16, 19, 21, 21},
};
}
TransformationMatrix get_quantization_matrix_chrominance() {
return {
{12, 12, 12, 12, 12, 12, 12, 12},
{12, 12, 12, 12, 12, 12, 12, 12},
{12, 12, 12, 12, 12, 12, 12, 12},
{12, 12, 12, 12, 12, 12, 12, 12},
{12, 12, 12, 12, 12, 12, 12, 12},
{12, 12, 12, 12, 12, 12, 12, 12},
{12, 12, 12, 12, 12, 12, 12, 12},
{12, 12, 12, 12, 12, 12, 12, 12},
};
return {
{4, 4, 6, 10, 21, 21, 21, 21},
{4, 5, 6, 21, 21, 21, 21, 21},
{6, 6, 12, 21, 21, 21, 21, 21},
{10, 14, 21, 21, 21, 21, 21, 21},
{21, 21, 21, 21, 21, 21, 21, 21},
{21, 21, 21, 21, 21, 21, 21, 21},
{21, 21, 21, 21, 21, 21, 21, 21},
{21, 21, 21, 21, 21, 21, 21, 21}
};
}
BigPixelMatrix quantize_pixel_matrix (BigPixelMatrix pixelMatrix, int quantization_factor) {
int row_c = 0;
int col_c = 0;
int zero_count=0;
TransformationMatrix cqm = get_quantization_matrix_chrominance();
TransformationMatrix lqm = get_quantization_matrix_luminance();
if (quantization_factor == 0) {
return pixelMatrix;
}
cout << "quantize" << endl;
for (auto& row : pixelMatrix) {
col_c = 0;
for (auto& pixel : row) {
for (int i = 0; i < pixel.size(); i++) {
pixel[i] = (pixel[i] / (cqm[row_c % 8][col_c % 8]*quantization_factor))*(cqm[row_c % 8][col_c % 8]*quantization_factor);
}
col_c++;
}
row_c++;
}
cout << "zeros: " << zero_count << endl;
return pixelMatrix;
}
void test (BigPixelMatrix pixelMatrix) {
int rows = pixelMatrix.size();
int cols = pixelMatrix[0].size();
int ch = pixelMatrix[0][0].size();
cout << "Rows: " << rows << ", Cols: " << cols << ", Ch: " << ch << endl;
for (int row = 0; row < 8; row++){
for (int col = 0; col < 8; col++){
cout << pixelMatrix[row][col][0] << " " ;
}cout << endl;}cout << endl;
}
int main(int argc, char *argv[]) {
string src_image_path = argv[1];
int quantization_level = atoi(argv[2]);
BigPixelMatrix pixelMatrix = get_pixel_matrix(src_image_path);
cout<<"start conversion"<<endl;
TransformationMatrix transformationMatrix = get_transformation_matrix(BLOCK_SIZE);
TransformationMatrix transposedTransformationMatrix = get_transposed_transformation_matrix(BLOCK_SIZE);
if (quantization_level == 0) {
write_pixel_matrix(pixelMatrix, src_image_path);
cout<< "finished writing" <<endl;
arithmeticEncodeFromFile(src_image_path, src_image_path);
return 0;
}
BigPixelMatrix pixelMatrixConverted = transform_pixels(pixelMatrix, transformationMatrix, transposedTransformationMatrix);
cout<<"finished conversion"<<endl;
BigPixelMatrix pixelMatrixQuantized = quantize_pixel_matrix (pixelMatrixConverted, quantization_level);
write_pixel_matrix(pixelMatrixQuantized, src_image_path);
cout<< "finished writing" <<endl;
//test(pixelMatrix);
//test(pixelMatrixConverted);
//test(pixelMatrixQuantized);
//arithmeticMatrixEncode(pixelMatrix, src_image_path);
arithmeticEncodeFromFile(src_image_path, src_image_path);
return 0;
}