Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keras input shape ordering is (width, height, ch)?

I use Keras2 with TensorFlow as back-end and tried feed horizontal rectangle image (width:150 x height:100 x ch:3) into network.

I use cv2 for pre-processing images and cv2 & TensorFlow treats the shape of images as [height, width, ch] ordering (in my case, it's [100, 150, 3] This format is opposite of (width:150 x height:100 x ch:3), but it's not mistake.)

So I defined Keras model API input as follow code, but it occurred an error.

img = cv2.imread('input/train/{}.jpg'.format(id))
img = cv2.resize(img, (100, 150))

inputs = Input(shape=(100, 150, 3))
x = Conv2D(8, (3, 3), padding='same', kernel_initializer='he_normal')(inputs)
~~~

error message is below

ValueError: Error when checking input: expected input_4 to have shape
(None, 100, 150, 3) but got array with shape (4, 150, 100, 3)

By the way input = Input((150, 100, 3)) can be run.

I feel weird with discrepancy between Keras & TensorFlow, so I'm suspicious that it just don't occurred error, it does not worked properly.

Anybody can explain that? I couldn't locate the input shape ordering in Keras Document.

like image 830
横尾修平 Avatar asked Sep 04 '17 03:09

横尾修平


2 Answers

You can change the dimension ordering as you prefer. You can print and change the dimension ordering like this:

from keras import backend as K
print(K.image_data_format()) # print current format
K.set_image_data_format('channels_last') # set format

If you want to permanently change the dimension ordering, you should edit it in the keras.json file, usually located at ~/.keras/keras.json:

"image_data_format": "channels_last"
like image 109
McLawrence Avatar answered Nov 15 '22 09:11

McLawrence


My problem occurred from order of width&height at argument of cv2.resize(). cv2.resize() takes the argument like cv2.resize(img, (width, height)), whereas numpy treats image array order of (height, width).

like image 30
横尾修平 Avatar answered Nov 15 '22 07:11

横尾修平