BoltzmannBrain BoltzmannBrain - 3 months ago 24
Python Question

How to move one dimension of a numpy matrix?

I have a matrix

A
of shape
(480, 640, 3)
, and I would like to use the values to populate another matrix
B
, of shape
(3, 480, 640)
. I've tried
numpy.reshape(A, B.shape)
, but I think this is not doing the trick.

For some context, the 480 and 640 dimensions are the frame height and width of an image, and the 3 dimension is for the color (RGB) values.

(I'm looking for an efficient way of doing this, not a bunch of nested for loops.)

Answer

I think that you want to swap or roll the axes. Let's start with an 3-D array:

>>> mat = np.arange(24).reshape(2, 4, 3)
>>> mat.shape
(2, 4, 3)

Now, let's reorder the axes with swapaxes:

>>> mat.swapaxes(0, 2).swapaxes(1, 2).shape
(3, 2, 4)

Or, let's roll the axes:

>>> rolled = np.rollaxis(mat, 2)
>>> rolled.shape
(3, 2, 4)