Reputation: 197
I was building a model and I wanted to test its performance, thus I imported a local file and load it and try to predict its label with the following code:
from tensorflow.preprocessing import image
# Other imports for tensorlfow etc.
#...
# Sample image
img_path = "./Model/data/brain/train/Glioma/images/gg (2).jpg"
img = image.load_img(img_path,target_size=(256,256))
arr = image.img_to_array(img)
t_img = tf.convert_to_tensor(arr)
print(t_img.shape) # Returns (256,256,3)
# Client testing
client = Client("brain") # Custom Class. Contains model: Sequential (compiled and trained)
client.predict(img=t_img) # Calls self.model.predict(t_img)
However I get the following error:
Invalid input shape for input Tensor("data:0", shape=(32, 256, 3), dtype=float32). Expected shape (None, 256, 256, 3), but input has incompatible shape (32, 256, 3)
I have an input layer in the trained model which has input_shape=[256,256,3] (comes from image width, height, and rgb values)
Can you help me understand the issue and solve it?
Upvotes: -1
Views: 76
Reputation: 1833
Dr. Snoopy already gave the answer in the comments, but for the sake of completeness a short solution copied from the TF load_image page:
image = keras.utils.load_img(image_path)
input_arr = keras.utils.img_to_array(image)
input_arr = np.array([input_arr]) # Convert single image to a batch.
predictions = model.predict(input_arr)
model.predict()
expects batches of images. This solultion would transform your (256, 256, 3)
shape to (1, 256, 256, 3)
. There are also other solutions, e.g. with tf.expand_dims(image, 0)
if you rather want to work with tensors directly instead of arrays.
Upvotes: 1