首页 > 解决方案 > 无法从 Python 3.x 中的文件中读取二进制矩阵

问题描述

因此,我必须执行这两个函数,一个将二进制矩阵保存在 .bin 文件中,另一个读取同一文件并返回 .bin 文件numpy.array

我的问题是,当我尝试 .vstack 行和最终图像(我基本上想保存黑白图像)时,我收到此消息错误:

'ValueError:除连接轴外的所有输入数组维度必须完全匹配'

这是有道理的,因为在我阅读了第二行 binaryLine 和最终图像的长度不同之后,由于某种原因我无法理解。

def save_binary_matrix(img, fileName):
    file = open(fileName, "w+")
    heigth, width = img.shape
    image = convert_BW_to_0_1(img) # converts from 0 and 255 to 0 and 1
    for y in range(heigth):
        for x in range(0, width, 8):
            bits = image[y][x:x+8]# gets every 8 bits
            s = ''
            # converts bits to a string
            for i in range(len(bits)):
                s = s + str(bits[i])
            file.write(str(int(s,2)))# saves the string as a integer
        file.write("\n")# line change
    file.close()

def read_binary_matrix(fileName):
    file = open(fileName, "r")
    #saves first line of the file
    finalImage = np.array([])
    line = file.readline()
    for l in range(len(line)):
        if line[l] != '\n':
            finalImage = np.append(finalImage, np.array([int(x) for x in list('{0:08b}'.format(int(line[l])))]))
    #reads and saves other lines
    for line in file:
        binaryLine = np.array([])
        for l in range(len(line)):
            if line[l] != '\n':
                #read and saves line as binary value
                binaryLine = np.append(binaryLine, np.array([int(x) for x in list('{0:08b}'.format(int(line[l])))]))
            finalImage = np.vstack((finalImage, binaryLine))
    return finalImage

标签: python-3.xnumpynumpy-ndarray

解决方案


两次创建一个np.array([]). 注意它的形状:

In [140]: x = np.array([])                                                      
In [141]: x.shape                                                               
Out[141]: (0,)

它确实起作用np.append- 那是因为没有轴参数,append只是concatenate((x, y), axis=0),例如添加一个 (0,) 形状和一个 (3,) 形状来创建一个 (3,) 形状:

In [142]: np.append(x, np.arange(3))                                            
Out[142]: array([0., 1., 2.])

vstack不起作用。它将输入变成二维数组,并在第一个轴上连接它们:

In [143]: np.vstack((x, np.arange(3)))                                          
ValueError: all the input array dimensions except for the concatenation axis must match exactly

所以我们在新的第一个轴上连接 (0,) 和 (3,),例如第一个轴上的 (1,0) 和 (1,3)。0 和 3 不匹配,因此出现错误。

vstack在将 (3,) 与 (3,) 和 (1,3) 以及 (4,3) 连接时起作用。请注意常见的“最后一个”维度。

潜在的问题是您正在尝试模拟列表附加,而没有完全了解尺寸或做什么concatenate。它每次都会创建一个全新的数组。 np.append不是list.append! 的克隆。

您应该做的是从一个[](或两个)列表开始,将新值附加到该列表中,制作一个列表列表。然后np.array(alist)将其转换为数组(当然,前提是所有子列表的大小都匹配)。

我没有注意你的写作,或者你如何阅读这些台词,所以不能说这是否有意义。


推荐阅读