如何将输入图像赋予训练好的模型?INPUT_1应为4维,但获得了具有形状(224,224,3)的数组 [英] How to Give input image to trained model ? expected input_1 to have 4 dimensions, but got array with shape (224, 224, 3)

查看:0
本文介绍了如何将输入图像赋予训练好的模型?INPUT_1应为4维,但获得了具有形状(224,224,3)的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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:检查输入时出错:INPUT_1应有4维,但得到具有形状(224,224,3)的数组

推荐答案

您应该像模型预期的那样扩展您的输入图像维度。您可以使用np.expand_dims来实现这一点。此外,您可能希望缩放图像。

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]

希望它能有所帮助。

这篇关于如何将输入图像赋予训练好的模型?INPUT_1应为4维,但获得了具有形状(224,224,3)的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆