How to Give input image to trained model ? expected input_1 to have 4 dimensions, but got array with shape (224, 224, 3)

Viewed 689
import tensorflow as tf
from tensorflow import keras
from keras.models import load_model
from keras.preprocessing import image
import numpy as np
import cv2
import matplotlib.pyplot as plt

model=tf.keras.models.load_model('model_ex-024_acc-0.996875.h5')
img_array = cv2.imread('30.jpg')  # convert to array

img_rgb = cv2.cvtColor(img_array, cv2.COLOR_BGR2RGB)

img_rgb = cv2.resize(img_rgb,(224,224),3)
plt.imshow(img_rgb)  # graph it
plt.show()
model.predict(img_rgb)

ValueError: Error when checking input: expected input_1 to have 4 dimensions, but got array with shape (224, 224, 3)

1 Answers

You should expand your input image dimension as the model expects. And you can do that using np.expand_dims. Additionally you may want to scale your image.

img_rgb = cv2.resize(img_rgb,(224,224),3)  # resize
img_rgb = np.array(img_rgb).astype(np.float32)/255.0  # scaling
img_rgb = np.expand_dims(img_rgb, axis=0)  # expand dimension
y_pred = model.predict(img_rgb) # prediction
y_pred_class = y_pred.argmax(axis=1)[0]

Hope it will help.

Related