Home > other >  Iterating over a multi-dimentional array
Iterating over a multi-dimentional array

Time:12-06

I have array of shape (3,5,96,96), where channels= 3, number of frames = 5 and height and width = 96 I want to iterate over dimension 5 to get images with size (3,96,96). The code which I have tried is below.

b = frame.shape[1]
for i in range(b):
     fr = frame[:,i,:,:]

But this is not working.

CodePudding user response:

You could swap axis (using numpy.swapaxes(a, axis1, axis2) to get the second (frame) in first position

import numpy as np

m = np.zeros((3, 5, 96, 96))

n = np.swapaxes(m, 0, 1)


print(n.shape)
(5, 3, 96, 96)

CodePudding user response:

You need to iterate over the first axis to achieve your desired result, this means you need to move the axis you want to iterate over to the first position. You can achieve this with np.moveaxis

m = np.zeros((3, 5, 96, 96))
np.moveaxis(m, 1, 0).shape
(5, 3, 96, 96)
  • Related