如何将形状 (N , N) 维度的数组重塑为 (N , N , 3)
How to reshape an array of shape (N , N) dimension to (N , N , 3)
我有一个形状数组 (2084, 2084),我想将它重塑为 (2084, 2084, 3)。我尝试使用 np.dstack 但它给了我这样的结果 (1, 2084, 2084)
patch = (2084, 2084)
patch_new = np.dstack(patch)
我该怎么做?
Kmario,所以你在第三个维度上重复同一个数组 3 次?
您错过了在深度堆叠之前将您的阵列提升 到 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
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]]])
我有一个形状数组 (2084, 2084),我想将它重塑为 (2084, 2084, 3)。我尝试使用 np.dstack 但它给了我这样的结果 (1, 2084, 2084)
patch = (2084, 2084)
patch_new = np.dstack(patch)
我该怎么做?
Kmario,所以你在第三个维度上重复同一个数组 3 次?
您错过了在深度堆叠之前将您的阵列提升 到 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
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]]])