因此,我必须执行这两个函数,一个函数保存.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发布于 2019-03-23 04:57:37
两次创建一个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不起作用。它将输入输入到2d数组中,并将它们连接到第一个轴上:
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,)与a (3,)和a (1,3)以及a (4,3)连接时工作。注意常见的“最后”维度。
根本的问题是,您试图模仿附加的列表,而不完全了解维度,也不了解concatenate的功能。它每次都会生成一个全新的数组。np.append不是list.append的克隆!
您应该做的是从一个[]列表(或两个)开始,在其上附加新的值,列出一个列表。然后np.array(alist)将其转换为数组(当然,所有子列表在大小上都匹配)。
我没有注意你的写作,也没有注意你是如何读台词的,所以我不能说这是否有意义。
https://stackoverflow.com/questions/55310603
复制相似问题