Solved – Keras: run prediction on a single object after loading weights

I'd like to make a prediction for a single image with Keras. I've trained my model so I'm just loading the weights.

from keras.preprocessing.image import ImageDataGenerator from keras.models import Sequential from keras.layers import Conv2D, MaxPooling2D from keras.layers import Activation, Dropout, Flatten, Dense from keras import backend as K import numpy as np import cv2  # dimensions of our images. img_width, img_height = 150, 150    def create_model():   if K.image_data_format() == 'channels_first':     input_shape = (3, img_width, img_height)   else:     input_shape = (img_width, img_height, 3)    model = Sequential()   model.add(Conv2D(32, (3, 3), input_shape=input_shape))   model.add(Activation('relu'))   model.add(MaxPooling2D(pool_size=(2, 2)))    model.add(Conv2D(32, (3, 3)))   model.add(Activation('relu'))   model.add(MaxPooling2D(pool_size=(2, 2)))    model.add(Conv2D(64, (3, 3)))   model.add(Activation('relu'))   model.add(MaxPooling2D(pool_size=(2, 2)))    model.add(Flatten())   model.add(Dense(64))   model.add(Activation('relu'))   model.add(Dropout(0.5))   model.add(Dense(1))   model.add(Activation('sigmoid'))    return model   img = cv2.imread('./test1/1.jpg') model = create_model() model.load_weights('./weight.h5') model.predict(img) 

I'm loading the image using:

img = cv2.imread('./test1/1.jpg') 

And using the predict function of the model:


But I get the error:

ValueError: Error when checking : expected conv2d_1_input to have 4 dimensions, but got array with shape (499, 381, 3) 

How should I proceed to have predictions on a single image ?

Just like it states in the error, your first convolution 2D layer is expecting a tensor with 4 dimensions but you are giving it a tensor with only 3 (img). Try this instead:


EDIT: Also, your network is setup to receive images of size (150,150,3) as input. The image you are using for your prediction seems to be of size (499,381,3). You want to apply all the same pre-processing (re-sizing, normalization, cropping etc.) to your input image for prediction as you do for training.

Similar Posts:

Rate this post

Leave a Comment