使用【c++】写【设有图像的灰度级X={x1,x2,x3,x4,x5},出现的概率分别为P=P(xi){0.33,0.27,0.1,0.13,0.17},利用哈夫曼编码输出各字符的码字并计算其平均码长、信源熵。】的代码
时间: 2024-11-25 07:21:53 浏览: 5
在C++中,我们可以使用哈夫曼树(Huffman Tree)算法来生成每个灰度级的最优二进制码字,并计算信源熵和平均码长。首先,我们需要创建一个优先队列以及定义一个节点结构来表示概率和值。以下是简单的实现步骤:
```cpp
#include <iostream>
#include <queue>
#include <vector>
// 节点结构体
struct HuffmanNode {
int value;
double probability;
std::string code;
HuffmanNode* left, *right;
};
// 计算两个节点的合并概率
double combineProb(HuffmanNode* node1, HuffmanNode* node2) {
return (node1->probability + node2->probability);
}
// 构建哈夫曼树
HuffmanNode* buildHuffmanTree(std::vector<HuffmanNode>& nodes) {
if (nodes.size() == 1)
return &nodes[0];
std::priority_queue<std::pair<double, HuffmanNode*>, std::vector<std::pair<double, HuffmanNode*>>, std::greater<std::pair<double, HuffmanNode*>>> pq(nodes.begin(), nodes.end());
while (pq.size() > 1) {
double minProb = pq.top().first;
pq.pop();
double secondMinProb = pq.top().first;
pq.pop();
HuffmanNode* left = pq.top().second;
pq.pop();
HuffmanNode* right = pq.top().second;
pq.pop();
HuffmanNode* newNode = new HuffmanNode();
newNode->probability = combineProb(left, right);
newNode->left = left;
newNode->right = right;
pq.push({minProb + secondMinProb, newNode});
}
return pq.top().second;
}
// 从根节点开始,递归分配编码
void assignCodes(HuffmanNode* root, std::string code, std::vector<HuffmanNode*>& codes) {
if (root->left == nullptr && root->right == nullptr) {
codes[root->value] = code;
} else {
assignCodes(root->left, code + "0", codes);
assignCodes(root->right, code + "1", codes);
}
}
// 计算信源熵
double calculateEntropy(const std::vector<int>& probabilities) {
double entropy = 0.0;
for (int i : probabilities) {
if (i > 0) {
entropy += -i * log2(i);
}
}
return entropy;
}
int main() {
// 图像灰度级和概率
std::vector<int> X = {x1, x2, x3, x4, x5};
std::vector<double> P = {0.33, 0.27, 0.1, 0.13, 0.17}; // 确保概率总和为1
// 创建节点数组
std::vector<HuffmanNode> nodes(X.size());
for (size_t i = 0; i < X.size(); ++i) {
nodes[i].value = X[i];
nodes[i].probability = P[i];
nodes[i].code = "";
}
// 构建哈夫曼树
HuffmanNode* root = buildHuffmanTree(nodes);
// 为每个灰度级分配编码
std::vector<HuffmanNode*> codes(X.size());
assignCodes(root, "", codes);
// 输出码字和计算信源熵
for (auto& node : codes) {
std::cout << "灰度级 " << node->value << " 的码字是: " << node->code << '\n';
}
double avgCodeLength = 0;
for (size_t i = 0; i < X.size(); ++i) {
avgCodeLength += codes[i]->probability * codes[i]->code.length();
}
avgCodeLength /= X.size();
std::cout << "平均码长: " << avgCodeLength << "\n";
double sourceEntropy = calculateEntropy(P);
std::cout << "信源熵: " << sourceEntropy << "\n";
return 0;
}
```
这个程序会构建哈夫曼树,生成每个灰度级的码字,并计算信源熵和平均码长。注意,`x1`, `x2`, `x3`, `x4`, 和 `x5` 需要在实际应用中替换为你所给的具体灰度级数值。
阅读全文