Skip to main content
 首页 » 编程设计

python之值错误 : cannot reshape array of size 50176 into shape (1, 224,224,3)

2025年05月04日22lyhabc

我正在做图像分类,我训练了一个模型并保存了一个模型。当我尝试预测模型时,它显示输入错误。我正在使用 ResNet 架构构建分类器,最初将 input_size 声明为 224 x 224。现在我需要预测测试图像的类别。

我将图像转换为 224x224 numpy 数组。当我尝试下面的代码时

#plot the figure 
fig = plt.figure() 
 
for num,data in enumerate(test_data): 
 
    img_num = data[1] 
    img_data = data[0] 
 
    y = fig.add_subplot(9,3,num+1) 
    orig = img_data 
    data = img_data.reshape(1,IMG_SIZ,IMG_SIZ,3) 
 
    #predict the model 
    model_out = model.predict_classes([orig])[0] 
 
    if np.argmax(model_out) == 1: str_label='Dog' 
    else: str_label='Cat' 
 
    y.imshow(orig,cmap = 'gray') 
    plt.title(str_label) 
    y.axes.get_xaxis().set_visible(False) 
    y.axes.get_yaxis().set_visible(False) 
 
 
plt.show() 
plt.savefig('test_labeled.jpg') 

它向我显示以下错误

ValueError: cannot reshape array of size 50176 into shape (1,224,224,3)

我必须以多大的尺寸 reshape 正确的尺寸?

谢谢!

请您参考如下方法:

您的输入似乎是 [224, 224, 1] 而不是 [224, 224, 3]。看起来您在 process_test_data()

中将输入转换为 灰度

您可能需要更改:

img = cv2.imread(path,cv2.IMREAD_GRAYSCALE) 
img = cv2.resize(img,(IMG_SIZ,IMG_SIZ)) 

到:

img = cv2.imread(path) 
img = cv2.resize(img,(IMG_SIZ,IMG_SIZ),3)