Skip to content

Instantly share code, notes, and snippets.

@yassineAlouini
Created February 15, 2019 07:56
Show Gist options
  • Save yassineAlouini/32c06482e00238a60098d08c38f18496 to your computer and use it in GitHub Desktop.
Save yassineAlouini/32c06482e00238a60098d08c38f18496 to your computer and use it in GitHub Desktop.
Predict the top Imagenet labels using a pre-trained Keras model.
import numpy as np
import keras.preprocessing.image as image_utils
from keras.applications.imagenet_utils import decode_predictions, preprocess_input
# You can import any other model if you would like to :)
from keras.applications.resnet50 import ResNet50
IMG_SIZE = (224, 224)
# Loading the model only once
CLASSIFICATION_MODEL = ResNet50()
def get_top_label(img_path):
"""Given an image path, return the top detected label using a ResNet50 model. """
image = image_utils.load_img(img_path, target_size=IMG_SIZE)
image = image_utils.img_to_array(image)
image = np.expand_dims(image, axis=0)
image = preprocess_input(image)
preds = CLASSIFICATION_MODEL.predict(image)
top_label = decode_predictions(preds)[0][0][1]
return top_label
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment