如何将形状为(N,N)的形状数组重塑为(N,N,3)

时间:2019-03-30 10:26:55

标签: arrays numpy multidimensional-array reshape numpy-ndarray

我有一个形状数组(2084,2084),我想将其重塑为(2084,2084,3)。我尝试使用np.dstack,但它给了我这样的东西(1,2084,2084)

patch = (2084, 2084)
patch_new = np.dstack(patch)

我该怎么做?

3 个答案:

答案 0 :(得分:1)

在深度堆叠之前,您没有将阵列提升到3D中。因此,您可以使用类似以下内容的

In [93]: patch = (2084, 2084)

In [94]: arr = np.random.random_sample(patch)

# make it as 3D array
In [95]: arr = arr[..., np.newaxis]

# and then stack it along the third dimension (say `n` times; here `3`)
In [96]: arr_3d = np.dstack([arr]*3)

In [97]: arr_3d.shape
Out[97]: (2084, 2084, 3)

另一种相同的方法是(即,如果您不希望将输入数组明确提升到3D):

In [140]: arr_3d = np.dstack([arr]*3)
In [141]: arr_3d.shape
Out[141]: (2084, 2084, 3)

# sanity check
In [146]: arr_3 = np.dstack([arr[..., np.newaxis]]*3)

In [147]: arr_3.shape
Out[147]: (2084, 2084, 3)

In [148]: np.allclose(arr_3, arr_3d)
Out[148]: True

答案 1 :(得分:1)

In [730]: x = np.arange(8).reshape(2,4)                                         
In [731]: x                                                                     
Out[731]: 
array([[0, 1, 2, 3],
       [4, 5, 6, 7]])

您的dstack不仅添加了初始尺寸,还转置了其余尺寸。那是因为它将数组视为列表np.dstack([x[0,:], x[1,:]])

In [732]: np.dstack(x)                                                          
Out[732]: 
array([[[0, 4],
        [1, 5],
        [2, 6],
        [3, 7]]])

这是一个repeat任务

In [733]: np.repeat(x[...,None],3,axis=2)                                       
Out[733]: 
array([[[0, 0, 0],
        [1, 1, 1],
        [2, 2, 2],
        [3, 3, 3]],

       [[4, 4, 4],
        [5, 5, 5],
        [6, 6, 6],
        [7, 7, 7]]])

答案 2 :(得分:0)

Kmario,因此您在第三个维度上重复了3次相同的数组?

相关问题