3
\$\begingroup\$

I'm sure my question exists on the internet, i just don't know the right formulations.

I have a data-sample as input for a NN. This sample has the shape (1, 8, 28, 80). Basically it is 80 timesteps of an image. -> y=8, x=28, time=80

i can extract the image at time=0 with:

np_img = image.data.numpy()   # shape (1, 8, 28, 80)
t0 = np_img[:, :, :, 0][0]

in order to be able to plot the images at each timestamp below each other, resulting in an array of (640, 28), ergo concatenating along the y-axis I do:

amount_timeslots = img.shape[-1]
new_array = img[:, :, :, 0][0]

for i in range(1, amount_timeslots):
    ti = img[:, :, :, i][0]
    new_array = np.concatenate((new_array, ti))

new_array.shape  # (640, 28)

Is there a more pythonic way by using build in numpy magic to do this?

\$\endgroup\$
1
  • \$\begingroup\$ @MaartenFabré that returns (28,640) and the values seem to be not in the right order (so .T does help changing the dimensions but the values are wrong) \$\endgroup\$ – Maikefer Jun 3 '20 at 13:30
3
\$\begingroup\$

concatenate

There is no need to do the concatenation pairwise np.concatenate([img[:, :, :, i][0] for i in range(img.shape[-1])]) should improve the speed already

numpy.moveaxis

You can use numpy.moveaxis

new_array2 = np.concatenate(np.moveaxis(img[0],(0,1,2), (1,2,0)))

To check whether the result is the same:

assert np.array_equal(new_array, new_array2)

Other improvements

Since you don't use the first axis of the image, you can do np_img = image.data.numpy()[0] so prevent you repeating the [0] in all subsequent code

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.