如何将输入图像赋予训练模型?预期输入_1有4个维度,但得到了形状为(224,224,3)的数组

2024-04-19 15:05:04 发布

您现在位置:Python中文网/ 问答频道 /正文

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)


Tags: tofromimportimgmodelmodelstftensorflow
1条回答
网友
1楼 · 发布于 2024-04-19 15:05:04

您应该按照模型所期望的那样扩展输入图像维度。你可以用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]

希望能有帮助。你知道吗

相关问题 更多 >