Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 709
Kuysea Avatar asked May 07 '17 09:05

Kuysea


People also ask

How do you change channel from first to channel last image?

Try img. transpose(2,0,1) or img. transpose(2,1,0) .

What is channel first and channel last?

There are two ways to represent the image data as a three dimensional array. The first involves having the channels as the last or third dimension in the array. This is called “channels last“. The second involves having the channels as the first dimension in the array, called “channels first“.

What does channel first mean?

Channels first means that in a specific tensor (consider a photo), you would have (Number_Of_Channels, Height , Width) .

What is number of channels in image?

An RGB image has three channels: red, green, and blue. RGB channels roughly follow the color receptors in the human eye, and are used in computer displays and image scanners.


2 Answers

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) 
like image 119
cemsazara Avatar answered Sep 18 '22 12:09

cemsazara


To reorder data

You can use numpy.rollaxis to roll the axis 3 to position 1 (considering you have the batch size as dimension 0).

np.rollaxis(imagesArray, 3, 1)   

But, if you're using keras, you might want to change its configuration or define it per layer. Theano doesn't require anything from you if you're using Keras.

Keras can be configured with channels first or channels last, besides allowing you to define it in every individual layer, so you don't have to change your data.

To configure keras

Find the keras.json file and change it. The file is usually installed in C:\Users\yourusername\.keras or ~/.keras depending on your OS.

Change "image_data_format": "channels_last" to "channels_first" or vice-versa, as you wish.

Usually, working with "channels_last" is less troublesome because of a great amount of other (non convolutional) functions that work only on the last axis.

Defining channel order in layers.

The Keras documentation has all information about parameters for layers, including the data_format parameter.

like image 29
Daniel Möller Avatar answered Sep 19 '22 12:09

Daniel Möller