2

I'm building an image classifier and trying to compute the features for a dataset using keras but my array dimension is not on the right format. I'm getting

ValueError: Error when checking : expected input_1 to have 4 dimensions, but got array with shape (324398, 1)

My code is this:

import glob
from keras.applications.resnet50 import ResNet50

def extract_resnet(X):  
    # X : images numpy array
    resnet_model = ResNet50(input_shape=(image_h, image_w, 3), 
    weights='imagenet', include_top=False)  # Since top layer is the fc layer used for predictions
    features_array = resnet_model.predict(X)
    return features_array
filelist = glob.glob('dataset/*.jpg')
myarray = np.array([np.array(Image.open(fname)) for fname in filelist])
print(extract_resnet(myarray))

So it looks like for some reason the images array is only two dimensional when it should be 4 dimensional. How can I convert myarray so that it is able to work with the feature extractor?

6
  • 1
    Looks like it expects an array of RGB images. Commented May 10, 2018 at 6:39
  • @cᴏʟᴅsᴘᴇᴇᴅ I'm feeding it RGB images. Color should be 1 dimension either way, returned array is still 2 dimensions. Commented May 10, 2018 at 6:41
  • Yes, it expects each RGB image to be in its original, 3D shape. Commented May 10, 2018 at 6:42
  • 1
    From the code he doesn't seem to be reshaping anything though. @Juanvulcano, just random guessing, could it be that the images don't all have the same shape so you're building a list of arrays instead of a tensor? Commented May 10, 2018 at 7:01
  • @filippo True, that's the case. Any reference on how to resize the images so that I can get the 4d array? Commented May 10, 2018 at 7:22

1 Answer 1

2

First up, make sure that all of the images in dataset directory have the same size (image_h, image_w, 3):

print([np.array(Image.open(fname)).shape for fname in filelist])

If they are not, you won't be able to make a mini-batch, so you'll need to select only the subset of suitable images. If the size is right, you can then reshape the array manually:

myarray = myarray.reshape([-1, image_h, image_w, 3])

... to match ResNet specification exactly.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.