输入图像与张量流模型输入形状不兼容

问题描述 投票:0回答:1

我正在构建一个模型,我想测试它的性能,因此我导入了一个本地文件并加载它,并尝试使用以下代码预测它的标签:

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)

但是我收到以下错误:

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)

我在训练模型中有一个输入层,其 input_shape=[256,256,3] (来自图像宽度、高度和 RGB 值)

你能帮我理解这个问题并解决它吗?

python tensorflow machine-learning tensorflow-datasets
1个回答
0
投票

Dr. Snoopy
已经在评论中给出了答案,但为了完整起见,从TF load_image页面复制了一个简短的解决方案

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()
需要批量图像。此解决方案会将您的
(256, 256, 3)
形状转变为
(1, 256, 256, 3)
。还有其他解决方案,例如如果您想直接使用张量而不是数组,请使用
tf.expand_dims(image, 0)

© www.soinside.com 2019 - 2024. All rights reserved.