这里是一个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)
它似乎并没有解码任意 LZW 数据,而是从另一个 Python 例程中腌制的数据。直接 LZW 数据的代码具有额外的困难,必须在处理之前将任意位长度的数据转换为整数。
否则,该算法似乎与 Michael Dipperstein 在 <https://michaeldipperstein.github.io/lzw.html> 中解释的几乎相同:
请注意,为了处理字典中尚未存在的代码,请将最后解码值的第一个字节附加到该值,并将新代码添加到字典中。
然后,代码获取所有整数值并使用
ord()
将它们转换为 Unicode,然后使用其他一些导入代码将数据 reshape
转换为图像。