我得到了这个学校项目,目标是拍照,应用 RLE 方法将其压缩为二进制文件 (.txt),并节省一些空间。在苦苦挣扎了 3 天之后,我现在遇到了麻烦。
def read():
f2=open("data2.txt",'rb') #open a binary file in reading mod.
im3=zeros((962,800,3),dtype="uint8") #create picture which size is 962*800 where every pixels are coded on 3 bytes.
d=0#pixel counter
i=0#lign indexation
j=0#column indexation
b=ord(f2.read(1))# the informations are read a first time
a=ord(f2.read(1))
red=ord(f2.read(1))
green=ord(f2.read(1))
blue=ord(f2.read(1))
while i!=im3.shape[0]: #as long as it doesn't reach the final lign
if d<=(a+b*255):
im3[i,j,0] = red
im3[i,j,1] = green
im3[i,j,2] = blue
d+=1
j+=1
if j==im3.shape[1]:
j=0
i+=1
else: #resets pixel counter and starts reading next informations
d=0
b=ord(f2.read(1))
a=ord(f2.read(1))
red=ord(f2.read(1))
green=ord(f2.read(1))
blue=ord(f2.read(1))
f2.close()
imsave("done.bmp",im3)
return im3
imshow(read());
show();
当我执行 pgrm 时,它给了我标题中写的这个错误。我觉得这是不可能纠正的,因为它是用十六进制写的。
这里有更多信息: 像素在这里不使用字节编码,就像我们通常对 .bmp 等格式所做的那样。 这里 RLE 将通过比较 3 级颜色来搜索相同 lign 上的相同像素,并计算它遇到它的次数。最后它存储了两个比 RGB 字节多的字节:a 和 b。 a是像素数。 b 是 255 个像素堆叠的数量。 (因为我把数据编码成 8bits,而且图片通常大于 255*255 大小)
请您参考如下方法:
您的文件太短,数据用完了。 file.read(..) 找到 EOF 时返回一个空字符串。也许您的剩余字节应该保留为 0?
您读取数据的效率极低。使用 struct module将您的数据解压缩为整数,并创建一个由 (R, G, B) 三元组组成的长 numpy 数组,然后 reshape 数据以形成您的图像矩阵:
import numpy as np
import struct
def lecture_fichier_compresse():
width, height = 800, 962
with open("data2.txt", 'rb') as rle_data:
image = np.zeros((width * height, 3), dtype="uint8")
pos = 0
# decompress RLE data; 2 byte counter followed by 3 RGB bytes
# read until the file is done
for data in iter(lambda: rle_data.read(5), ''):
if len(data) < 5:
# not enough data to store another RLE RGB chunk
break
count, r, g, b = struct.unpack('>HBBB', data)
image[pos:pos + count, :] = [[r, g, b]] * count
pos += count
# reshape continuous stream into an image matrix
image = image.reshape((height, width, 3))
imsave("Copie_compresse.bmp",im3)
return image
也就是说,使用您的样本文件数据我似乎无法构建连贯的图像。解压缩产生 695046 个像素的数据,这不能生成连贯的矩形图像(数字因素的最高短维度是 66,因此非常拉长)。即使最后允许丢失数据,我似乎也找不到任何能产生连贯图像的纵横比。结论是您输入的数据不完整或不正确。
