pythonnumpymachine-learningkerastheano

What is the correct way to change image channel ordering between channels first and channels last?


I can not for the life of me figure out how to switch the image ordering. images are read in (x,x,3) format, theano requires it to be in (3,x,x) format. I tried changing the order with numpy.array([img[:,:,i] for i in range(3)])

which i guess gets the job done, but it is both ugly and i can't figure out how to reverse it to get the original image back.


Solution

  • I agree with @Qualia 's comment, np.moveaxis(a, source, destination) is easier to understand. This does the job:

    x = np.zeros((12, 12, 3))
    x.shape
    #yields: 
    (12, 12, 3)
    
    x = np.moveaxis(x, -1, 0)
    x.shape
    #yields: 
    (3, 12, 12)