I have an image as a numpy array with shape (channels, height, width)
how can I reshape it so that it has shape (height, width, channels)
?
Asked
Active
Viewed 2.2k times
8

Alex Riley
- 169,130
- 45
- 262
- 238

Aly
- 15,865
- 47
- 119
- 191
-
you can't use `numpy_image.reshape(height, width, channels)`? – farhawa May 20 '15 at 10:24
3 Answers
11
I assume it would be quicker to use the built-in numpy function.
np.rollaxis(array_name,0,3).shape

Rob
- 538
- 2
- 11
-
1don't you mean `np.rollaxis(array_name,0,3).shape`, yours will reorder it as `(height, channels, width)` – Lanting May 20 '15 at 10:36
-
Yes, you are correct. I got my directions confused. I will update my original post. – Rob May 20 '15 at 10:41
-
This function continues to be supported for backward compatibility, but you should prefer moveaxis. The moveaxis function was added in NumPy 1.11. – WurmD May 26 '22 at 13:32
9
You can use transpose()
to choose the order of the axes. In this case you want:
array.transpose(1, 2, 0)
This creates a new view onto the original array whenever possible (no data will be copied).

Alex Riley
- 169,130
- 45
- 262
- 238
0
You could do:
import numpy as np
newim = np.zeros((height, width, channels))
for x in xrange(channels):
newim[:,:,x] = im[x,:,:]

Julien Spronck
- 15,069
- 4
- 47
- 55