python - 值错误 : cannot reshape array of size 2352 into shape (1, 28,28)

标签 python tensorflow keras mnist

我想将我的绘图用于我的神经网络。我在 MNIST 上训练了它。我无法从任何方面做好准备。我以 28x28 的图片分辨率画了一个图形。我尝试通过神经网络运行它,但它不起作用。我不明白如何解决这个问题。

代码

    #norm_image = np.asarray(pixels, dtype=np.float32) / 255
img_size=28
img = cv2.resize(img, (img_size,img_size))
x=img
x=np.asarray(img)
x = img.astype('float32')
x /= 255.0
x = np.expand_dims(x, axis=0)
images = np.vstack([x])
print(images.shape)
images = np.reshape(images,(1, 28, 28))

#print(pixels)
#print(x.shape)
#res=model.predict(x)
#print (res)
#print(f"Распознанная цифра: {np.argmax(res)}")
#x = np.expand_dims(x, axis=0)
#plt.imshow(img, cmap=plt.cm.binary)
#plt.show()

错误

    ValueError                                Traceback (most recent call last)
<ipython-input-167-3fe66f8f6d63> in <module>()
     13 images = np.vstack([x])
     14 print(images.shape)
---> 15 images = np.reshape(images,(1, 28, 28))
     16 
     17 #print(pixels)

<__array_function__ internals> in reshape(*args, **kwargs)

1 frames
/usr/local/lib/python3.7/dist-packages/numpy/core/fromnumeric.py in _wrapfunc(obj, method, *args, **kwds)
     56 
     57     try:
---> 58         return bound(*args, **kwds)
     59     except TypeError:
     60         # A TypeError occurs if the object does have such a method in its

ValueError: cannot reshape array of size 2352 into shape (1,28,28)

最佳答案

问题是您以彩色模式而不是灰度模式(OpenCV 中的 BGR)读取图像,但 channel 的顺序在这里并不重要(ofc 2352 // 3 = 784 )。

当您读取图像 28x28x3 时=2352 ,你想将其 reshape 为 28x28x1 =784 ,这当然不会像错误所暗示的那样工作。

问题在于您读取图像的方式:img = cv2.imread("t7.png") 。而是使用img = cv2.imread("t7.png",0) ,参数0是灰度图像的默认标志。

关于python - 值错误 : cannot reshape array of size 2352 into shape (1, 28,28),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69493634/

相关文章:

python - 如何旋转 Python 列表以将特定值居中

python - 使用 Tensorflow 构建适用于可变批量大小的图形

python - 尝试重命名 tf.keras 上的预训练模型时出错

python - args python 解析器,一个空格和 Spark

python - 数值积分循环 Python

python - 使用 tkinter lib 在 Python 中显示表情符号/符号

python - TensorFlow 中损失函数 (MLP) 的奇怪 NaN 值

python - 如何从具有向量列的 DataFrame 创建 tensorflow 数据集?

r - 检查输入 : expected lstm_1_input to have 3 dimensions, 时出错,但得到形状为 (3653, 3) 的数组

python - 如何在自定义训练循环中使用 tf.keras.layers.BatchNormalization() ?