LZW解码功能

问题描述 投票:0回答:1

这里是一个lzw解码函数,它对输入图像进行解码。我不明白它是如何做到这一点的, 如果有人能为我解释一下,我将不胜感激

def lzw_decode(encoded_img, decoded_img):
    with open(encoded_img, "rb") as f:
        code_arr, shape = pickle.load(f)
    dictionary = dict()
    dict_size = 256
    for i in range(256):
        dictionary[i] = chr(i) 
     
    img = ""
    s = chr(code_arr.pop(0))
    img += s
    for k in code_arr:
        if k in dictionary.keys():
            entry = dictionary[k]
        elif k == dict_size:
            entry = s + s[0]
        img += entry    
        
        dictionary[dict_size] = s + entry[0]
        dict_size += 1
        s = entry
        
    img = [ord(x) for x in img]
    img = np.array(img, dtype=np.uint16).reshape(shape)
    cv2.imwrite(decoded_img, img)

python compression lzw
1个回答
0
投票

它似乎并没有解码任意 LZW 数据,而是从另一个 Python 例程中腌制的数据。直接 LZW 数据的代码具有额外的困难,必须在处理之前将任意位长度的数据转换为整数。

否则,该算法似乎与 Michael Dipperstein 在 <https://michaeldipperstein.github.io/lzw.html> 中解释的几乎相同:

  1. 初始化字典以包含每个字节的一个条目。
  2. 从输入流中读取第一个代码字并写出它编码的字节。
  3. 从输入流中读取下一个代码字。
  4. 如果代码字是 EOF 退出。
  5. 写出码字编码的字符串。
  6. 将新代码字中的第一个字符连接到前一个代码字生成的字符串,并将生成的字符串添加到字典中。
  7. 转到步骤 3。

请注意,为了处理字典中尚未存在的代码,请将最后解码值的第一个字节附加到该值,并将新代码添加到字典中。

然后,代码获取所有整数值并使用

ord()
将它们转换为 Unicode,然后使用其他一些导入代码将数据
reshape
转换为图像。

© www.soinside.com 2019 - 2024. All rights reserved.