青少年编程与数学 02-016 Python数据结构与算法 30课题、数据压缩算法 ...

打印 上一主题 下一主题

主题 1878|帖子 1878|积分 5634

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
课题摘要:
先容一些常见的数据压缩算法,并提供更详细的Python代码实现。
  
一、无损压缩算法

1. Huffman编码

Huffman编码是一种基于字符频率的编码方法,通过构建一棵Huffman树来天生每个字符的唯一编码。
详细代码示例(Python)
  1. import heapq
  2. from collections import defaultdict, Counter
  3. class Node:
  4.     def __init__(self, char, freq):
  5.         self.char = char
  6.         self.freq = freq
  7.         self.left = None
  8.         self.right = None
  9.     def __lt__(self, other):
  10.         return self.freq < other.freq
  11. def build_huffman_tree(frequency):
  12.     heap = [Node(char, freq) for char, freq in frequency.items()]
  13.     heapq.heapify(heap)
  14.    
  15.     while len(heap) > 1:
  16.         left = heapq.heappop(heap)
  17.         right = heapq.heappop(heap)
  18.         merged = Node(None, left.freq + right.freq)
  19.         merged.left = left
  20.         merged.right = right
  21.         heapq.heappush(heap, merged)
  22.    
  23.     return heap[0]
  24. def generate_codes(node, prefix="", code_dict=None):
  25.     if code_dict is None:
  26.         code_dict = {}
  27.     if node is not None:
  28.         if node.char is not None:
  29.             code_dict[node.char] = prefix
  30.         generate_codes(node.left, prefix + "0", code_dict)
  31.         generate_codes(node.right, prefix + "1", code_dict)
  32.     return code_dict
  33. def huffman_encode(s):
  34.     frequency = Counter(s)
  35.     huffman_tree = build_huffman_tree(frequency)
  36.     huffman_codes = generate_codes(huffman_tree)
  37.     encoded_string = ''.join(huffman_codes[char] for char in s)
  38.     return encoded_string, huffman_codes
  39. def huffman_decode(encoded_string, huffman_codes):
  40.     reverse_dict = {code: char for char, code in huffman_codes.items()}
  41.     current_code = ""
  42.     decoded_string = ""
  43.     for bit in encoded_string:
  44.         current_code += bit
  45.         if current_code in reverse_dict:
  46.             decoded_string += reverse_dict[current_code]
  47.             current_code = ""
  48.     return decoded_string
  49. # 示例
  50. s = "this is an example for huffman encoding"
  51. encoded_string, huffman_codes = huffman_encode(s)
  52. print("Encoded string:", encoded_string)
  53. print("Huffman dictionary:", huffman_codes)
  54. decoded_string = huffman_decode(encoded_string, huffman_codes)
  55. print("Decoded string:", decoded_string)
复制代码
2. Lempel-Ziv-Welch (LZW) 编码

LZW编码是一种基于字典的压缩算法,通过动态构建字典来编码重复的字符串。
详细代码示例(Python)
  1. def lzw_encode(s):
  2.     dictionary = {chr(i): i for i in range(256)}
  3.     w = ""
  4.     result = []
  5.     for c in s:
  6.         wc = w + c
  7.         if wc in dictionary:
  8.             w = wc
  9.         else:
  10.             result.append(dictionary[w])
  11.             dictionary[wc] = len(dictionary)
  12.             w = c
  13.     if w:
  14.         result.append(dictionary[w])
  15.     return result
  16. def lzw_decode(encoded):
  17.     dictionary = {i: chr(i) for i in range(256)}
  18.     w = chr(encoded.pop(0))
  19.     result = [w]
  20.     for k in encoded:
  21.         if k in dictionary:
  22.             entry = dictionary[k]
  23.         elif k == len(dictionary):
  24.             entry = w + w[0]
  25.         result.append(entry)
  26.         dictionary[len(dictionary)] = w + entry[0]
  27.         w = entry
  28.     return ''.join(result)
  29. # 示例
  30. s = "TOBEORNOTTOBEORTOBEORNOT"
  31. encoded = lzw_encode(s)
  32. print("Encoded:", encoded)
  33. decoded = lzw_decode(encoded)
  34. print("Decoded:", decoded)
复制代码
3. Run-Length Encoding (RLE)

RLE是一种简单的无损压缩算法,通过将连续重复的字符替换为字符和重复次数的组合。
详细代码示例(Python)
  1. def rle_encode(s):
  2.     if not s:
  3.         return ""
  4.    
  5.     result = []
  6.     prev_char = s[0]
  7.     count = 1
  8.    
  9.     for char in s[1:]:
  10.         if char == prev_char:
  11.             count += 1
  12.         else:
  13.             result.append((prev_char, count))
  14.             prev_char = char
  15.             count = 1
  16.     result.append((prev_char, count))
  17.    
  18.     return ''.join([f"{char}{count}" for char, count in result])
  19. def rle_decode(encoded):
  20.     result = []
  21.     i = 0
  22.     while i < len(encoded):
  23.         char = encoded[i]
  24.         count = int(encoded[i+1])
  25.         result.append(char * count)
  26.         i += 2
  27.     return ''.join(result)
  28. # 示例
  29. s = "AAAABBBCCDAA"
  30. encoded = rle_encode(s)
  31. print("Encoded:", encoded)
  32. decoded = rle_decode(encoded)
  33. print("Decoded:", decoded)
复制代码
二、有损压缩算法

1. JPEG压缩(有损)

JPEG是一种广泛利用的图像压缩标准,通常用于有损压缩。虽然JPEG压缩的实现较为复杂,但可以利用Python的Pillow库来处置惩罚JPEG图像。
详细代码示例(Python)
  1. from PIL import Image
  2. # 压缩图像
  3. def compress_image(input_path, output_path, quality=85):
  4.     image = Image.open(input_path)
  5.     image.save(output_path, "JPEG", quality=quality)
  6. # 示例
  7. compress_image("input.jpg", "output.jpg", quality=50)
复制代码
2. DEFLATE(ZIP压缩)

DEFLATE是一种结合了LZ77算法和Huffman编码的压缩算法,广泛用于ZIP文件格式。
详细代码示例(Python)
  1. import zlib
  2. def deflate_compress(data):
  3.     compressed_data = zlib.compress(data.encode())
  4.     return compressed_data
  5. def deflate_decompress(compressed_data):
  6.     decompressed_data = zlib.decompress(compressed_data)
  7.     return decompressed_data.decode()
  8. # 示例
  9. data = "this is an example for deflate compression"
  10. compressed_data = deflate_compress(data)
  11. print("Compressed data:", compressed_data)
  12. decompressed_data = deflate_decompress(compressed_data)
  13. print("Decompressed data:", decompressed_data)
复制代码
3. Brotli

Brotli是一种现代的压缩算法,结合了多种压缩技术,提供比DEFLATE更好的压缩率。
详细代码示例(Python)
  1. import brotli
  2. def brotli_compress(data):
  3.     compressed_data = brotli.compress(data.encode())
  4.     return compressed_data
  5. def brotli_decompress(compressed_data):
  6.     decompressed_data = brotli.decompress(compressed_data)
  7.     return decompressed_data.decode()
  8. # 示例
  9. data = "this is an example for brotli compression"
  10. compressed_data = brotli_compress(data)
  11. print("Compressed data:", compressed_data)
  12. decompressed_data = brotli_decompress(compressed_data)
  13. print("Decompressed data:", decompressed_data)
复制代码
4. LZMA

LZMA是一种高效的压缩算法,广泛用于7z文件格式。
详细代码示例(Python)
  1. import lzma
  2. def lzma_compress(data):
  3.     compressed_data = lzma.compress(data.encode())
  4.     return compressed_data
  5. def lzma_decompress(compressed_data):
  6.     decompressed_data = lzma.decompress(compressed_data)
  7.     return decompressed_data.decode()
  8. # 示例
  9. data = "this is an example for lzma compression"
  10. compressed_data = lzma_compress(data)
  11. print("Compressed data:", compressed_data)
  12. decompressed_data = lzma_decompress(compressed_data)
  13. print("Decompressed data:", decompressed_data)
复制代码
5. Zstandard (Zstd)

Zstd是一种现代的压缩算法,结合了高压缩率和快速解压缩的特点。
详细代码示例(Python)
  1. import zstandard
  2. def zstd_compress(data):
  3.     compressed_data = zstandard.compress(data.encode())
  4.     return compressed_data
  5. def zstd_decompress(compressed_data):
  6.     decompressed_data = zstandard.decompress(compressed_data)
  7.     return decompressed_data.decode()
  8. # 示例
  9. data = "this is an example for zstd compression"
  10. compressed_data = zstd_compress(data)
  11. print("Compressed data:", compressed_data)
  12. decompressed_data = zstd_decompress(compressed_data)
  13. print("Decompressed data:", decompressed_data)
复制代码
总结

这些数据压缩算法在不同的场景下具有各自的优势和适用性。无损压缩算法如Huffman编码、LZW编码和RLE适用于需要完全恢复原始数据的场景,而有损压缩算法如JPEG压缩则适用于对数据质量要求不高的场景。根据具体需求选择符合的压缩算法可以有效节省存储空间和传输带宽。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

宝塔山

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表