ValueError:无法将大小为 49897 的数组重塑为形状 (500,700,3)

问题描述

大家好,我正在实施 lzw 压缩算法图片压缩算法

使用的库

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

压缩

def lzwCompression (image,path):
    img = cv2.imread(image)
    shape = img.shape
    flat = img.reshape(-1)
       
    #Costruzione del Dizionario
    lenDictionary = 256
    dictionary = {chr(i): i for i in range(lenDictionary)}
    
    for i in range(256):
        dictionary[chr(i)] = i 

    compressed = list()
    stringSaved = chr(flat[0])
    print ("string symbl",stringSaved )
    for i in range(1,len(flat)):
        string_symbol = chr (flat[i])
        sc =  stringSaved + string_symbol
        if sc in dictionary.keys() :
            stringSaved = string_symbol
        else:
            compressed.append(dictionary[stringSaved])
            dictionary[sc] = lenDictionary
            lenDictionary = lenDictionary + 1

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

    with open(path,"wb") as f:
        pickle.dump((compressed,shape),f)

**L'algoritmo di compressione non fa altro che prendere l'immagine ed applicare lzw。

在解压阶段,当算法加载压缩文件然后返回原始图像时,它给了我以下错误:ValueError: cannot reshape array of size 49897 into shape (500,700,3).

我哪里做错了?

**

解压

def lzwDecompression (path,img_path) :
    with open(path,"rb") as f:
        compressed,shape = pickle.load(f)
    dictionary = dict()
    lenDictionary = 256
    for i in range(256):
        dictionary[i] = chr(i)

    img = ""
    s = chr(compressed.pop(0))
    img += s
    for k in compressed :
        if k in dictionary.keys():
            ins = dictionary[k]
        elif k == lenDictionary:
            ins = s + s[0]
            img += ins

        dictionary[lenDictionary] = s + ins[0]
        lenDictionary +=1
        s = ins 

    img = [ord(x) for x in img]
    img = np.array(img,dtype=np.uint16).reshape(shape)
    cv2.imwrite(img_path,img)

   
**MAIN**

from LZW import * 
from PIL import Image
import numpy as np 

path1 = "LZW-Project\im3.jpg"
path2 ="Outpit"
path3 = "Input"

lzwCompression(path1,path2)
lzwDecompression(path2,path3)

解决方法

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

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

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