Reputation: 439
I have an array of shape ( 2084, 2084) i want to reshape it to (2084, 2084 , 3). I tried using np.dstack but it gives me something like this (1, 2084, 2084)
patch = (2084, 2084)
patch_new = np.dstack(patch)
How do I do it?
Upvotes: 0
Views: 223
Reputation: 61365
You missed promoting your array to 3D before depth stacking. So, you can use something like:
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)
Another way to do the same is (i.e. if you don't wish to promote your input array explicitly to 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
Upvotes: 1
Reputation: 231395
In [730]: x = np.arange(8).reshape(2,4)
In [731]: x
Out[731]:
array([[0, 1, 2, 3],
[4, 5, 6, 7]])
Your dstack
not only adds an initial dimension, it transposes the rest. That's because it treats your array as a list, np.dstack([x[0,:], x[1,:]])
.
In [732]: np.dstack(x)
Out[732]:
array([[[0, 4],
[1, 5],
[2, 6],
[3, 7]]])
This is a repeat
task
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]]])
Upvotes: 1
Reputation: 9
Kmario, so you repeat the same array 3 times over the third dimension ?
Upvotes: 0