TensorFlow sequential model is not recognising the full shape of the data

Advertisements
import tensorflow as tf
from traffic import IMG_WIDTH, IMG_HEIGHT
import cv2
import os
import numpy as np
model = tf.keras.models.load_model("neural-network")
image = cv2.imread("gtsrb\\1\\00000_00000.ppm")
image = cv2.resize(image, (IMG_WIDTH, IMG_HEIGHT))
print(image.shape)
model.predict(image)

The image.shape doesn’t agree with the shape that the model reads in the model.predict() line

I run this code, and the image.shape is (30,30,3)
but when I predict the image, it raises an error, which states "ValueError: Input 0 of layer "sequential" is incompatible with the layer: expected shape=(None, 30, 30, 3), found shape=(None, 30, 3)"
Any help greatly appreciated as I have no clue why this is happening

>Solution :

You need to use expand_dims function from tensorflow:

import tensorflow as tf
from traffic import IMG_WIDTH, IMG_HEIGHT
import cv2
import os
import numpy as np

model = tf.keras.models.load_model("neural-network")
image = cv2.imread("gtsrb\\1\\00000_00000.ppm")
image = cv2.resize(image, (IMG_WIDTH, IMG_HEIGHT))

image = tf.convert_to_tensor(image, dtype=tf.float32)
image = tf.expand_dims(image , 0)

print(image.shape)
model.predict(image)

Also use this to convert it to RGB if not already in RGB before converting it to tensor:

image = cv.cvtColor(image, cv.COLOR_BGR2RGB)

Leave a ReplyCancel reply