BoltzmannBrain - 8 months ago 58

Python Question

I have a matrix

`A`

`(480, 640, 3)`

`B`

`(3, 480, 640)`

`numpy.reshape(A, B.shape)`

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)
```