WX_M
WX_M

Reputation: 488

flatten / reshape 3D array in python

I have a 3D vector of size (450,552,30) where 450 = x-dimension, 552 = y-dimension, and 30 = time steps. Essentially, a time-lapse of a 2-dimensional object. I know there are convLSTM's and LSTM CNN's that are possible, but I want to flatten this data into a 1D LSTM model for testing.

To simplify things, let's take a 2D array such that

a = np.array([[1,2,3],[4,5,6],[7,8,9]])

And then let's concatenate this a couple times with a 3rd dimension:

a = np.expand_dims(a,axis=-1)
b = a
b = np.concatenate((b,a),axis=-1)
b = np.concatenate((b,a),axis=-1)
b = np.concatenate((b,a),axis=-1)
print(b.shape)
(3,3,4)

such that b is simply the same data (a), concatenated upon itself to act as a sort of small-scale exercise to the full-scale data I wish to implement this to. If I do:

b.flatten()
array([1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6,
       6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9])

this does not give me the answer I am looking for. I am looking moreso for:

array([[1,1,1,1],[2,2,2,2],[3,3,3,3],[4,4,4,4], ..., [9,9,9,9]])

where the full-scale output should have dimensions of (450 * 552, 30). instead of (450 * 552 * 30,). Is there an elegant way of doing this?

Upvotes: 0

Views: 1691

Answers (2)

hpaulj
hpaulj

Reputation: 231395

In [63]: a = np.arange(1,10).reshape(3,3)

lets do one concatenate with a list (stack does the expand_dims for us):

In [66]: b = np.stack([a,a,a,a],2)
In [67]: b.shape
Out[67]: (3, 3, 4)
In [68]: b.ravel()
Out[68]: 
array([1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6,
       6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9])
In [69]: b.reshape(9,4)
Out[69]: 
array([[1, 1, 1, 1],
       [2, 2, 2, 2],
       [3, 3, 3, 3],
       [4, 4, 4, 4],
       [5, 5, 5, 5],
       [6, 6, 6, 6],
       [7, 7, 7, 7],
       [8, 8, 8, 8],
       [9, 9, 9, 9]])

OR

In [71]: a1=a.reshape(9,1)
In [72]: np.concatenate([a1,a1,a1,a1],axis=1)

or

In [73]: np.repeat(a1,4,1)

Guess these last ones aren't relevant if you already have the (k,m,n) array. You just need the (reshape(k*m,n) or (-1, n) for short.

Upvotes: 1

Binyamin Even
Binyamin Even

Reputation: 3382

Try:

cv2.merge([a,a,a,a])

output:

array([[[1, 1, 1, 1],
        [2, 2, 2, 2],
        [3, 3, 3, 3]],
       [[4, 4, 4, 4],
        [5, 5, 5, 5],
        [6, 6, 6, 6]],
       [[7, 7, 7, 7],
        [8, 8, 8, 8],
        [9, 9, 9, 9]]], dtype=int32)

Upvotes: 0

Related Questions