Reputation: 631
I am taking image as a form input from the user and then trying to resizing it to (1,128,128,1) but getting
ValueError: cannot reshape array of size 921600 into shape (1,128,128,1)
Following is the snippet for taking image and then resizing it to (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)))
When I am not taking input image as a form input but just opening it from my desktop using the following approach , my code is running correctly.
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)))
How to do it?
I have seen this answer Getting error: Cannot reshape array of size 122304 into shape (52,28,28) but the op hasn't accepted any of the answers and even I am not able to understand the given solutions correctly.
Complete Code-
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)))
Upvotes: 1
Views: 4797
Reputation: 1317
Its hard to tell what is causing your issue. Assuming the images are grey-scale (single color channel) like they are in your example, maybe this code helps:
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)
Also, if you are only predicting one image, you still need to index the returned predictions like so: print(np.argmax(model.predict(img)[0]))
Hope this helps
Upvotes: 1