python - 无法将大小为 921600 的数组 reshape 为形状 (1,128,128,1)

标签 python python-3.x opencv keras

我将图像作为用户输入的表单,然后尝试将其大小调整为 (1,128,128,1) 但得到 ValueError:无法将大小为 921600 的数组 reshape 为形状 (1,128,128,1)

以下是拍摄图像然后将其调整为 (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)但是运算符(operator)没有接受任何答案,甚至我也无法正确理解给定的解决方案。

完整代码-

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)))

最佳答案

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

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]))

希望对你有帮助

关于python - 无法将大小为 921600 的数组 reshape 为形状 (1,128,128,1),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53159232/

相关文章:

c++ - OpenCV : Open Mobotix Camera Feed

python - 如何检查字母是否不在单词中?

python-3.x - 如何从 python 3 中的可迭代生成器中采样?

python - 如何将圆形图像裁剪为内切正方形,然后裁剪为内切圆,最后裁剪为内切正方形?

python - heroku无法安装zbar

python - 如何从 Bokeh 图中删除工具提示上的箭头

opencv - 估计单目相机的运动

python - 我如何使用请求库在python中下载所有类型的文件

python - 参数 #2 'mat1' 的张量在 CPU 上,但预计它在 GPU 上

python - 想要乘法,而不是重复变量