Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save okiriza/72663a4a2bfb4ee5c32db52280851f96 to your computer and use it in GitHub Desktop.
Save okiriza/72663a4a2bfb4ee5c32db52280851f96 to your computer and use it in GitHub Desktop.
Python function for extracting image features using bottleneck layer of Keras' ResNet50
from keras.applications.resnet50 import ResNet50, preprocess_input
from keras.preprocessing import image
import numpy as np
resnet = ResNet50(include_top=False)
def extract_features(img_paths, batch_size=64):
""" This function extracts image features for each image in img_paths using ResNet50 bottleneck layer.
Returned features is a numpy array with shape (len(img_paths), 2048).
"""
global resnet
n = len(img_paths)
img_array = np.zeros((n, 224, 224, 3))
for i, path in enumerate(img_paths):
img = image.load_img(path, target_size=(224, 224))
img = image.img_to_array(img)
img = np.expand_dims(img, axis=0)
x = preprocess_input(img)
img_array[i] = x
X = resnet.predict(img_array, batch_size=batch_size, verbose=1)
X = X.reshape((n, 2048))
return X
@dineshbvadhia
Copy link

Hi! Where is the "bottleneck" layer defined? The code is very similar to https://keras.io/applications/#resnet50 which I don't think is the bottleneck layers. Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment