Huffman图像压缩
1、实现基于Huffman编码的图像压缩
实现大体思路遵循上述的原理,关于比特位的处理,如果直接用位运算的话,编写起来较复杂。于是我改用0和1的字符串来逐位表示一个个比特。也就是说,编码过程中经过像素值转成,再由字符串转成比特位,解码过程中经过比特位转成字符串,再由字符串转成像素值。通过字符串作为桥梁,可以避免复杂的位运算,而运行效率也不会下降多少。而至于像素值和字符串怎样转换,还要用到现成的bitset<32>类型。
c++代码如下:
HuffmanEncode.cpp:
HuffmanEncode函数对外使用。调用函数HuffmanEncode,输入图像的二维矩阵,图像的宽高,以及另存的压缩后的文件名,执行后得到压缩后的文件以及头部信息文件。
在HuffmanEncode函数内,findMinNode函数用于找到当前最少出现的节点;buildTree函数用于构建哈夫曼树;每个节点的下标为像素值,存有出现次数,指向左右子节点的下标,以及用来判断是否已删除的位;buildTable函数用于建立像素值和编码值的映射关系。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <bitset>
using namespace std;
struct Node {
int count;
int left;
int right;
int removed;
};
int findMinNode(Node* nodes, int length) {
int index = -1;
for (int i = 0; i < length; i++) {
if ((index == -1 || nodes[i].count < nodes[index].count) && !nodes[i].removed && nodes[i].count > 0) {
index = i;
}
}
if (index != -1) {
nodes[index].removed = 1;
}
return index;
}
int buildTree(Node* nodes, int* counts) {
for (int i = 0; i < 256; i++) {
nodes[i].left = -1;
nodes[i].right = -1;
nodes[i].count = counts[i];
nodes[i].removed = 0;
}
int length = 256;
while (1) {
int l = findMinNode(nodes, length);
if (l == -1) {
break;
}
int r = findMinNode(nodes, length);
if (r == -1) {
break;
}
nodes[length].left = l;
nodes[length].right = r;
nodes[length].count = nodes[l].count + nodes[r].count;
nodes[length].removed = 0;
length++;
}
return length;
}
void buildTable(Node* nodes, int pos, string bits, string * table) {
int l = nodes[pos].left;
int r = nodes[pos].right;
if (nodes[pos].left == -1 && nodes[pos].right == -1) {
table[pos] = bits;
return;
}
buildTable(nodes, r, bits + "1", table);
buildTable(nodes, l, bits + "0", table);
}
void HuffmanEncode(unsigned char ** data, int height, int width, const char *writepath) {
FILE* fp;
int counts[256];
memset(counts, 0, sizeof(int) * 256);
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
counts[data[i][j]]++;
}
}
Node nodes[256 * 2];
int length = buildTree(nodes, counts);
string table[256];
buildTable(nodes, length - 1, "", table);
string table_path = "";
table_path = table_path + writepath + "_table";
fp = fopen(table_path.c_str(), "w");
for (int i = 0; i < 256; i++) {
if (table[i].size() == 0) {
fprintf(fp, "2\n");
} else {
fprintf(fp, "%s\n", table[i].c_str());
}
}
fclose(fp);
int total_bit_length = 0;
for (int i = 0; i < 256; i++) {
total_bit_length += counts[i] * table[i].size();
}
char * str = new char[total_bit_length];
int cur = 0;
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
for (int k = 0; k < table[data[i][j]].size(); k++) {
str[cur] = table[data[i][j]][k];
cur++;
}
}
}
fp = fopen(writepath, "wb");
int times = total_bit_length / 32 + 1;
string total = "";
total = total + str;
for (int i = 0; i < 32 * times - total_bit_length; i++) {
total = total + "0"<