Created
February 15, 2019 07:56
-
-
Save yassineAlouini/32c06482e00238a60098d08c38f18496 to your computer and use it in GitHub Desktop.
Predict the top Imagenet labels using a pre-trained Keras model.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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