写一份哈夫曼图像压缩代码c++
时间: 2023-08-06 22:19:16 浏览: 85
Huffman coding.rar_teacherm55_哈夫曼编码_图像压缩_编码 压缩
5星 · 资源好评率100%
以下是一个简单的 C++ 实现的哈夫曼图像压缩代码,仅供参考:
```c++
#include <iostream>
#include <fstream>
#include <queue>
using namespace std;
// 定义哈夫曼树节点结构体
struct HuffmanTreeNode {
int weight; // 权值
int parent, leftChild, rightChild; // 父节点、左孩子、右孩子
};
// 定义比较函数,用于优先队列中的节点排序
struct cmp {
bool operator() (const HuffmanTreeNode &a, const HuffmanTreeNode &b) const {
return a.weight > b.weight;
}
};
// 哈夫曼编码表结构体
struct HuffmanCode {
int bit[100]; // 编码位串
int start; // 编码起始位置
};
// 构建哈夫曼树
void buildHuffmanTree(HuffmanTreeNode *huffmanTree, int n) {
// 初始化哈夫曼树节点
for (int i = 0; i < 2 * n - 1; i++) {
huffmanTree[i].weight = 0;
huffmanTree[i].parent = -1;
huffmanTree[i].leftChild = -1;
huffmanTree[i].rightChild = -1;
}
// 输入各个叶子节点的权值
for (int i = 0; i < n; i++) {
cout << "请输入第 " << i + 1 << " 个叶子节点的权值:";
cin >> huffmanTree[i].weight;
}
// 构建哈夫曼树
priority_queue<HuffmanTreeNode, vector<HuffmanTreeNode>, cmp> q;
for (int i = 0; i < n; i++) {
q.push(huffmanTree[i]);
}
for (int i = n; i < 2 * n - 1; i++) {
HuffmanTreeNode node1 = q.top();
q.pop();
HuffmanTreeNode node2 = q.top();
q.pop();
huffmanTree[i].weight = node1.weight + node2.weight;
huffmanTree[i].leftChild = node1.weight < node2.weight ? node1.parent : node2.parent;
huffmanTree[i].rightChild = node1.weight < node2.weight ? node2.parent : node1.parent;
huffmanTree[node1.parent].parent = i;
huffmanTree[node2.parent].parent = i;
q.push(huffmanTree[i]);
}
}
// 生成哈夫曼编码表
void generateHuffmanCode(HuffmanTreeNode *huffmanTree, HuffmanCode *huffmanCode, int n) {
for (int i = 0; i < n; i++) {
int j = i;
int start = huffmanCode[i].start = n;
while (huffmanTree[j].parent != -1) {
if (huffmanTree[huffmanTree[j].parent].leftChild == j) {
huffmanCode[i].bit[--start] = 0;
} else {
huffmanCode[i].bit[--start] = 1;
}
j = huffmanTree[j].parent;
}
}
}
int main() {
int n; // 叶子节点个数
HuffmanTreeNode huffmanTree[200]; // 哈夫曼树
HuffmanCode huffmanCode[200]; // 哈夫曼编码表
cout << "请输入叶子节点个数:";
cin >> n;
buildHuffmanTree(huffmanTree, n);
generateHuffmanCode(huffmanTree, huffmanCode, n);
// 输出哈夫曼编码表
cout << "哈夫曼编码表如下:" << endl;
for (int i = 0; i < n; i++) {
cout << "权值为 " << huffmanTree[i].weight << " 的编码为:";
for (int j = huffmanCode[i].start; j < n; j++) {
cout << huffmanCode[i].bit[j];
}
cout << endl;
}
return 0;
}
```
注意:上面的代码仅供参考,实际应用中还需要考虑许多细节问题,例如图像压缩的读写、色彩空间转换等。
阅读全文