Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

keras reshape input image to work with CNN

There are other post with similar questions but none of the answers are helping me. I´m new to this CNN world.

I followed this tutorial for training a CNN with Keras using theano as BackEnd with the MNIST dataset. Now I want to pass to the CNN my own jpg image but I dont know how to reshape it. Can you help me please? Im super new at this.

So far, I tried this to reshape

image = np.expand_dims(image, axis=0) image = preprocess_input(image)

but get the following error when predicting:

ValueError: Error when checking : expected conv2d_1_input to have shape (None, 1, 28, 28) but got array with shape (1, 3, 28, 28)

As you can see, my CNN uses width = 28, height = 28 and depth =1.

like image 696
Danny Julian Avatar asked Aug 07 '17 00:08

Danny Julian


People also ask

Why reshape in CNN?

Most convolutional neural networks are designed in a way so that they can only accept images of a fixed size. This creates several challenges during data acquisition and model deployment. The common practice to overcome this limitation is to reshape the input images so that they can be fed into the networks.

How do you reshape a layer in keras?

Reshape class Layer that reshapes inputs into the given shape. Arbitrary, although all dimensions in the input shape must be known/fixed. Use the keyword argument input_shape (tuple of integers, does not include the samples/batch size axis) when using this layer as the first layer in a model.


2 Answers

Try using Numpy for reshaping. Since, you have been using a 2D-Convolutional model:

 image = np.reshape(image, (28, 1, 28, 1))
like image 194
Saurav-- Avatar answered Oct 03 '22 05:10

Saurav--


The error message shows the network expects the image shape is 1*28*28, but your input is in 3*28*28. I guess the image you input is a color image, 3 channels(RGB), while the network expects a gray image, one channel.

When you call opencv to read image, please use code below. img = cv2.imread(imgfile, cv2.IMREAD_GRAYSCALE)

like image 24
VictorLi Avatar answered Oct 03 '22 05:10

VictorLi