How to feed multiple images into Keras feature extraction?

Viewed 1613

Here is the code the Keras documentation page:

from keras.applications.vgg16 import VGG16
from keras.preprocessing import image
from keras.applications.vgg16 import preprocess_input
import numpy as np

model = VGG16(weights='imagenet', include_top=False)

img_path = 'elephant.jpg'
img = image.load_img(img_path, target_size=(224, 224))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)

features = model.predict(x)

Here a single image is being fed.

I have extracted a few (12) images into a list and converted that list into a numpy array. I would like to feed that list of images to the Keras feature extractor.

In other words I want to feed multiple images to it. How can I go about doing this?

1 Answers

This line x = np.expand_dims(x, axis=0) in your code turns the single image into an array of single image. So the shape of x will be (1, 224, 224, 3).

In your example you already have 12 images which you have kept it in numpy array. Check the shape of your numpy array. It has to be resized to (12, 224,224, 3). Number of channels can be 1, 3 or 4. Then, you will have to preprocess it. Check this code what happens in preprocess_input(x) function. After that you can pass to model.predict function.

Hope this answer helps you.

Related