TypeError:ord()需要一个字符,但找到长度为0的字符串

2024-09-29 00:19:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我得到了这个学校的项目,目标是拍摄一张照片,应用RLE方法将其压缩成二进制文件(.txt),并节省一些空间。在挣扎了三天之后,我现在有麻烦了。在

def lecture_fichier_compresse():
    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))
    rouge=ord(f2.read(1))
    vert=ord(f2.read(1))
    bleu=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] = rouge
            im3[i,j,1] = vert
            im3[i,j,2] = bleu
            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))
            rouge=ord(f2.read(1))
            vert=ord(f2.read(1))
            bleu=ord(f2.read(1))       
    f2.close()
    imsave("Copie_compresse.bmp",im3)
    return im3

imshow(lecture_fichier_compresse());show()

当我执行pgrm时,它会给我一个写在标题中的错误。我觉得这是不可能纠正的,因为它是用十六进制书写的。在

以下是更多信息: 像素在这里不是用字节编码的,就像我们通常在.bmp格式上那样。 在这里,RLE将在同一条直线上搜索相同的像素,并通过比较3个级别的颜色来计算遇到它的次数。最后,它比RGB存储了两个额外的字节:a和b。 a代表像素数。 b是255个像素堆栈的数目。(因为我将数据编码为8位,而且图片通常大于255*255)


Tags: txtread像素openf2readinglecturerouge
1条回答
网友
1楼 · 发布于 2024-09-29 00:19:43

你的文件太短,你的数据用完了。file.read(..)在找到EOF时返回一个空字符串。也许您的剩余字节应该保留为0?在

你的数据读取效率极低。使用^{} module将数据解压为整数,并创建一个由(R,G,B)三元组组成的单个长numy数组,然后对数据进行整形以形成图像矩阵:

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,因此非常拉长)。即使考虑到最后缺失的数据,我似乎也找不到任何能产生连贯图像的纵横比。结论是您的输入数据不完整或不正确。在

相关问题 更多 >