我将图像作为用户输入的表单,然后尝试将其大小调整为 (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/