【问题标题】:Cannot reshape array of size 921600 into shape (1,128,128,1)无法将大小为 921600 的数组重塑为形状 (1,128,128,1)
【发布时间】:2018-11-05 17:23:35
【问题描述】:

我将图像作为用户输入的表单,然后尝试将其大小调整为 (1,128,128,1) 但得到 ValueError: cannot reshape array of size 921600 into shape (1,128,128,1)

下面是sn-p,用于拍摄图像,然后将其调整为(1,128,128,1)-

def predit():
   im = Image.open(request.files['image'])
   image_data = np.asarray(im)
   input_img_flatten = cv2.resize(image_data,(128,128)).flatten()
   im2arr = np.reshape(input_img_flatten,(1,128,128,1))
   return str(np.argmax(model.predict(im2arr)))

当我没有将输入图像作为表单输入而只是使用以下方法从我的桌面打开它时,我的代码运行正常。

model = load_model('./latest.hdf5')
img = cv2.imread('/Users/swastik/thapar/test/test2.jpg',0)
input_img_flatten = cv2.resize(img,(128,128).flatten()
im2arr = np.array(input_img_flatten).reshape((1, 128, 128, 1)) 
print(np.argmax(model.predict(im2arr)))

怎么做?

我已经看到了这个答案Getting error: Cannot reshape array of size 122304 into shape (52,28,28),但操作人员没有接受任何答案,甚至我也无法正确理解给定的解决方案。

完整代码-

from keras.models import load_model
from PIL import Image
import numpy as np
import cv2

model = load_model('./latest.hdf5')
im = Image.open('Anyimageinyourfolder.jpg')
image_data = np.asarray(im)
input_img_flatten = cv2.resize(image_data,(128,128)).flatten()
im2arr = np.array(input_img_flatten).reshape((1, 128, 128, 1))
print(np.argmax(model.predict(im2arr)))

【问题讨论】:

  • @BradSolomon 是的,我也在想同样的事情,但请注意重塑之前的 resize...
  • 这是该模型的谷歌驱动器链接-drive.google.com/open?id=1rti2ct0MQz4pSq4dNbZ-WA6to_5vvq1p
  • 当我在这里尝试时,我得到“大小为 49152 的数组”而不是 921600。这很容易解释,因为它正好是 3x128x128 - 即您加载了一个 3 通道图像并保持原样.然而,另一个变体(使用cv2.imread)强制图像以灰度加载(这就是神奇数字0 的含义)。 PIL 等价物类似于Image.open(request.files['image']).convert('L')
  • 谢谢,它有效,但使用 PIL 等效项会弄乱所需的输出。 cv2.imread 和 PIL 渲染图像是否与使用 PIL 等效项时给出错误输出相同
  • @DanMašek,另一个问题也解决了。显然open cv和PIL读取图像的方式有所不同,如果长度大于宽度,PIL会将图像更改为横向模式。跨度>

标签: python python-3.x opencv keras


【解决方案1】:

很难说是什么导致了您的问题。假设图像是灰度(单色通道),就像在您的示例中一样,也许这段代码有帮助:

img = cv2.imread('messi5.jpg', cv2.IMREAD_GRAYSCALE)
img = cv2.resize(img, (128,128))
img = img[np.newaxis,:,:,np.newaxis]
print(img.shape)
>>> (1, 128, 128, 1)

另外,如果你只预测一张图像,你仍然需要像这样索引返回的预测:print(np.argmax(model.predict(img)[0]))

希望对你有帮助

【讨论】:

  • 感谢您的回答,但我想将图像作为表单输入,我已经想出了如何使用 cv.imread 方法
猜你喜欢
  • 2022-06-12
  • 2020-10-15
  • 2019-08-23
  • 2020-02-18
  • 2020-04-14
  • 2020-10-05
  • 2020-01-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多