LZW图像和文本的压缩python,无法保存文件只能打印

问题描述

import re
import numpy as np
from PIL import Image
import sys
from sys import argv
from struct import *


def lzwCompression (text):
    n = 20
    input_file = text
    data = text
    maximum_table_size = pow(2,int(n))   
    #Costruzione del Dizionario
    lenDictionary = 256
    dictionary = {chr(i): i for i in range(lenDictionary)}
    stringSaved = ""
    compressed = []

    for i in data:
        string_symbol = stringSaved + i
        if string_symbol in dictionary :
            stringSaved = string_symbol
        else:
            compressed.append(dictionary[stringSaved])
            if(len(dictionary)) <= maximum_table_size :
                dictionary[string_symbol] = lenDictionary
                lenDictionary +=1
                stringSaved= i 

    if stringSaved in dictionary:
        compressed.append(dictionary[stringSaved])

**

将图像转换为数组然后转换为列表后,我希望能够使用扩展名 .lzw 保存压缩文件,但我不明白为什么它不保存文件,只有印刷作品。有什么建议吗?

    out = input_file.split(".")[0]
    output_file = open(out + ".lzw","wb")

    for data in compressed:
        output_file.write(pack('>H',int(data)))
    
    output_file.close()
    data.close() 

    print("LZW Image Compression Algorithm")
print("=================================================================")

h = int(input("Enter 1 if you want to input an colour image file"))

if h == 1:
    file = input("Enter the filename:")
    my_string = np.asarray(Image.open(file),np.uint8)
    sudhi = my_string
    shape = my_string.shape
    print ("Enetered string is:",my_string)
    stringToEncode = str(my_string.tolist())
else:
    print("You entered invalid input")
path=".'FileCompressed.txt"
lzwCompression(stringToEncode) 

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)