【问题标题】:ValueError: cannot reshape array of size 50176 into shape (1,224,224,3)ValueError:无法将大小为 50176 的数组重塑为形状 (1,224,224,3)
【发布时间】:2018-10-22 17:30:09
【问题描述】:

我正在做图像分类,我训练了一个模型并保存了一个模型。当我尝试预测模型时,它显示输入错误。我正在使用 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: 无法将大小为 50176 的数组重新整形为形状 (1,224,224,3)

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

谢谢!

【问题讨论】:

  • 什么是data[0]?您是否尝试使用 .reshape() 调整图像大小?
  • 在 test_data 中有两个变量组合在一起。 data[1] 是 image-id,data[0] 是 shape(224x224) 的图像矩阵
  • 您的输入的大小似乎是 [224, 224, 1] 而不是 [224, 224, 3],所以相应地重新调整。
  • 我将尺寸更改为 (224x224x1) 但现在弹出此错误 ValueError: Error when checks input: expected resnet50_input to have shape (None, None, 3) but got array with shape (224, 224, 1)
  • 你能检查整个代码吗?我在 github 上发帖 code

标签: python tensorflow keras resnet


【解决方案1】:

您输入的大小似乎是 [224, 224, 1] 而不是 [224, 224, 3]。看起来您将输入转换为 gray scale in 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)

【讨论】:

    【解决方案2】:

    在我的情况下,函数期待 RGB 图像并且它失败了,因为它是 RGBA 一个自动意味着它有 4 个通道而不是 3 个。 所以我对它们的功能进行了翻新,以便能够吞下 RGBA

    def load_image_into_numpy_array(image):
        (im_width, im_height) = image.size
        if image.getdata().mode == "RGBA":
            image = image.convert('RGB')
        np_array = np.array(image.getdata())
        reshaped = np_array.reshape((im_height, im_width, 3))
        return reshaped.astype(np.uint8)
    

    【讨论】:

    • 感谢您的洞察力。看到未来的可能性真的很有帮助。
    猜你喜欢
    • 2021-08-02
    • 2021-03-20
    • 2021-03-21
    • 2019-11-29
    • 2020-01-29
    • 2021-07-18
    • 1970-01-01
    相关资源
    最近更新 更多