利用哈夫曼编码压缩图像的代码
时间: 2023-11-04 11:13:16 浏览: 80
基于哈夫曼编码,算术编码、字典编码、行程编码-Lempel-zev 编码正交变换编码实现图像压缩算法附Matlab代码.zip
以下是利用哈夫曼编码压缩图像的 Python 代码示例:
```python
import heapq
import numpy as np
# 定义哈夫曼树节点类
class HuffmanNode:
def __init__(self, freq, pixel=None):
self.freq = freq
self.pixel = pixel
self.left = None
self.right = None
# 定义节点比较方法
def __lt__(self, other):
return self.freq < other.freq
# 计算像素值频率
def calc_freq(img):
freq = {}
for i in range(img.shape[0]):
for j in range(img.shape[1]):
pixel = img[i][j]
if pixel in freq:
freq[pixel] += 1
else:
freq[pixel] = 1
return freq
# 构建哈夫曼树
def build_tree(freq):
heap = []
for pixel in freq:
heapq.heappush(heap, HuffmanNode(freq[pixel], pixel))
while len(heap) > 1:
node1 = heapq.heappop(heap)
node2 = heapq.heappop(heap)
parent = HuffmanNode(node1.freq + node2.freq)
parent.left = node1
parent.right = node2
heapq.heappush(heap, parent)
return heap[0]
# 递归遍历哈夫曼树,生成编码表
def traverse(node, code, code_table):
if node.pixel is not None:
code_table[node.pixel] = code
else:
traverse(node.left, code + '0', code_table)
traverse(node.right, code + '1', code_table)
# 哈夫曼编码压缩图像
def huffman_compress(img):
freq = calc_freq(img)
tree = build_tree(freq)
code_table = {}
traverse(tree, '', code_table)
compressed_img = ''
for i in range(img.shape[0]):
for j in range(img.shape[1]):
pixel = img[i][j]
compressed_img += code_table[pixel]
# 将压缩后的二进制字符串转换为字节数组
compressed_bytes = bytearray()
for i in range(0, len(compressed_img), 8):
compressed_bytes.append(int(compressed_img[i:i+8], 2))
return compressed_bytes, code_table
# 哈夫曼解压缩图像
def huffman_decompress(compressed_bytes, code_table, width, height):
compressed_bits = ''
for byte in compressed_bytes:
compressed_bits += bin(byte)[2:].zfill(8)
img = np.zeros((height, width), dtype=np.uint8)
node = build_tree({pixel: len(code_table[pixel]) for pixel in code_table})
for i in range(height):
for j in range(width):
node = node.left if compressed_bits[i*width+j] == '0' else node.right
if node.pixel is not None:
img[i][j] = node.pixel
node = build_tree({pixel: len(code_table[pixel]) for pixel in code_table})
return img
```
在上述代码中,`calc_freq()` 函数用于计算像素值频率,`build_tree()` 函数用于构建哈夫曼树,`traverse()` 函数用于递归遍历哈夫曼树,生成编码表,`huffman_compress()` 函数用于哈夫曼编码压缩图像,`huffman_decompress()` 函数用于哈夫曼解压缩图像。这里使用了 Python 标准库中的 `heapq` 模块实现优先队列,以便构建哈夫曼树。
阅读全文