tf.keras | Image classification with MobileNetV2 model

In this tutorial we will see how to use MobileNetV2 pre trained model for image classification. MobileNetV2 is pre-trained on the ImageNet dataset. MobileNetV2 model is available with tf.keras api.

Import modules and sample image


import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np

file = tf.keras.utils.get_file(
    "mountains.jpg",
    "https://storage.googleapis.com/gcptutorials.com/examples/mountains.jpg")
img = tf.keras.preprocessing.image.load_img(file, target_size=[224, 224]
                                            )
plt.imshow(img)
plt.axis('off')


Example Output:

Convert image to numpy array with tf.keras.preprocessing.image.img_to_array


x = tf.keras.preprocessing.image.img_to_array(img)
print(x.shape)
x = tf.keras.applications.mobilenet.preprocess_input(
    x[tf.newaxis,...])
print(x.shape)

Download ImagenetLabels, MobileNetV2 was trained on ImageNet Dataset


labels_path = tf.keras.utils.get_file(
    'ImageNetLabels.txt',
    'https://storage.googleapis.com/download.tensorflow.org/data/ImageNetLabels.txt')
labels = np.array(open(labels_path).read().splitlines())
print(len(labels))

Load model and predict classes for sample image


model = tf.keras.applications.MobileNetV2()
predictions = model(x)
print(predictions.shape)

top_5_classes_index = np.argsort(predictions)[0 , ::-1][:5]+1

print(top_5_classes_index)

top_5_classes = labels[top_5_classes_index]
print(top_5_classes)

 

Example Output:


(1, 1000)
[971 981 426 980 916]
['alp' 'volcano' 'barn' 'valley' 'yurt']

Complete code snippet for image classification with MobileNetV2


import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np

file = tf.keras.utils.get_file(
    "mountains.jpg",
    "https://storage.googleapis.com/gcptutorials.com/examples/mountains.jpg")
img = tf.keras.preprocessing.image.load_img(file, target_size=[224, 224]
                                            )
plt.imshow(img)
plt.axis('off')
x = tf.keras.preprocessing.image.img_to_array(img)
print(x.shape)
x = tf.keras.applications.mobilenet.preprocess_input(
    x[tf.newaxis,...])
print(x.shape)

labels_path = tf.keras.utils.get_file(
    'ImageNetLabels.txt',
    'https://storage.googleapis.com/download.tensorflow.org/data/ImageNetLabels.txt')
labels = np.array(open(labels_path).read().splitlines())
print(len(labels))

model = tf.keras.applications.MobileNetV2()
predictions = model(x)
print(predictions.shape)

top_5_classes_index = np.argsort(predictions)[0 , ::-1][:5]+1

print(top_5_classes_index)

top_5_classes = labels[top_5_classes_index]
print(top_5_classes)



Category: TensorFlow