将2D矩阵重新组合成3D? (x,y) - > (X / 72,72,y)的

时间:2016-02-09 14:53:03

标签: python-2.7 numpy matrix reshape

我有一个text file,我可以从中加载原始矩阵。

文本文件带有#的注释,它基本上有多个矩阵77 * 44。

我想阅读这个文件并存储完整数量的垫子中的每个矩阵。

import os
import sys
import numpy as np
from numpy import zeros, newaxis
import io

#read the txt file and store all vaules into a np.array
f = open('/path/to/akiyo_cif.txt','r')
x = np.loadtxt(f,dtype=np.uint8,comments='#',delimiter='\t')

nof = x.shape[0]/72
print ("shape after reading the file is "+ str(x.shape) )

#example program that works
newmat =np.zeros((nof+1,72,44))
for i in range(0,nof+1):
    newmat[i,:,:]= x[i*72 : (i*72)+72 , :]
print ("Shape after resizing the file is "+ str(newmat.shape) )

输出: - Shape after reading the file is (21240, 44)

Shape after resizing the file is (274, 72, 44)

如果我运行

newmat=x.reshape((nof,72,44))

newmat = x.reshape((nof,72,44))
ValueError: total size of new array must be unchanged

我想将此矩阵的大小调整为(21240/72,72,44)。 其中前77行对应newmat[0,:,:],后77行对newmat[1,:,:]

1 个答案:

答案 0 :(得分:1)

使用x.reshape(-1, 72, 44)

In [146]: x = np.loadtxt('data' ,dtype=np.uint8, comments='#', delimiter='\t')

In [147]: x = x.reshape(-1, 72, 44)

In [148]: x.shape
Out[148]: (34, 72, 44)

当您将其中一个维度指定为-1时,np.reshape会将-1替换为从数组长度和其余维度推断出的值。