Classifying Images Using Keras MobileNet and TensorFlow - Js in Google Chrome - Gogul Ilango
Classifying Images Using Keras MobileNet and TensorFlow - Js in Google Chrome - Gogul Ilango
Contents X
Chrome model
References
Deep Learning | 27 July 2018
10 Comments
In this blog post, we will understand how to perform image classification using
Keras MobileNet, deploy it in Google Chrome using TensorFlow.js and use it to make
live predictions in the browser.
https://gogul.dev/software/mobile-net-tensorflow-js 1/15
12/16/2019 Classifying images using Keras MobileNet and TensorFlow.js in Google Chrome – Gogul Ilango
Contents X
The interactive demo of what we will be making at the end of the tutorial is shown
Basic MobileNet in Python
below. You can play around with the buttons provided to make predictions on an
Convert Keras model into Tf
image. JS layers format
Keras model into TensorFlow
JS
1. Click Load Model to load MobileNet model in your browser.
1. Load Keras model into
2. Loading image -
TF.js
Click Demo Image to import a random image that belongs to an ImageNet
2. Upload image from disk
category. 3. Predict using MobileNet
Click Upload Image if you want to import an image from your model
disk.
References
3. Click Predict to make predictions on the image loaded in the browser.
Note: The above demo uses state-of-the-art Keras MobileNet that's trained
on ImageNet with 1000 categories. If you upload an image that doesn't
belong to any of the 1000 ImageNet categories, then the prediction might
not be accurate!
Downloads
In Keras, MobileNet resides in the applications module. Keras offers out of the box
image classification using MobileNet if the category you want to predict is available
in the ImageNet categories. If the category doesn’t exist in ImageNet categories,
https://gogul.dev/software/mobile-net-tensorflow-js 2/15
12/16/2019 Classifying images using Keras MobileNet and TensorFlow.js in Google Chrome – Gogul Ilango
there is a method called fine-tuning that tunes MobileNet for your dataset and
classes which we will discuss in another tutorial.
Contents X
MobileNet offers tons of advantages than other state-of-the-art convolutional neural
Basic MobileNet in Python
networks such as VGG16, VGG19, ResNet50, InceptionV3 and Xception.
Convert Keras model into Tf
JS layers format
MobileNets are light weight deep neural networks best suited forKeras
mobile and
model into TensorFlow
JS
embedded vision applications.
1. Load Keras model into
MobileNets are based on a streamlined architecture that uses depthwise separable
TF.js
convolutions. 2. Upload image from disk
MobileNet uses two simple global hyperparameters that e ciently tradesusing
3. Predict off MobileNet
between accuracy and latency. model
References
MobileNet could be used in object detection, negrain classi cation, face recognition,
large-scale geo localization etc.
Following are the advantages of using MobileNet over other state-of-the-art deep
learning models.
Advantages always come up with some disadvantages and with MobileNet, it’s the
accuracy. Yes! Eventhough MobileNet has reduced size, reduced parameters and
performs faster, it is less accurate than other state-of-the-art networks as
discussed in this paper. But don’t worry. There is only a slight reduction in accuracy
when compared to other networks.
In this tutorial, we will follow the steps shown in Figure 1 to make Keras MobileNet
available in a web browser using TensorFlow.js.
https://gogul.dev/software/mobile-net-tensorflow-js 3/15
12/16/2019 Classifying images using Keras MobileNet and TensorFlow.js in Google Chrome – Gogul Ilango
Contents X
First, we will write a simple python script to make predictions on a test image using
Keras MobileNet.
Before sending an image into MobileNet, we need to process the image using 4
simple steps. And to do that, you don’t need OpenCV. Keras provides all the
necessary functions under keras.preprocessing module, and with some basic
numpy functions, you are ready to go!
1. Load the image and convert it to MobileNet’s input size (224, 224) using load_img()
function.
2. Convert the image into a numpy array using img_to_array() .
3. Expand the dimensions of the numpy array using np.expand_dims() .
https://gogul.dev/software/mobile-net-tensorflow-js 4/15
12/16/2019 Classifying images using Keras MobileNet and TensorFlow.js in Google Chrome – Gogul Ilango
4. Preprocess the image by rescaling all the values to the range [-1, 1] using
mobilenet.preprocess_input() .
Contents X
basic-mobile-net.py code
Basic MobileNet in Python
Convert Keras model into Tf
JS layers format
1 # organize imports
Keras model into TensorFlow
2 import numpy as np
3 from keras.models import Model JS
4 from keras.preprocessing import image 1. Load Keras model into
5 from keras.applications import imagenet_utils, mobilenetTF.js
6 import tensorflowjs as tfjs 2. Upload image from disk
7
3. Predict using MobileNet
8 # process an image to be mobilenet friendly
model
9 def process_image(img_path):
10 img = image.load_img(img_path, target_size=(224, 224)) References
11 img_array = image.img_to_array(img)
12 img_array = np.expand_dims(img_array, axis=0)
13 pImg = mobilenet.preprocess_input(img_array)
14 return pImg
15
16 # main function
17 if __name__ == '__main__':
18
19 # path to test image
20 test_img_path = "G:\\git-repos\\mobile-net-projects\\dataset\\test\\test_im
21
22 # process the test image
23 pImg = process_image(test_img_path)
24
25 # define the mobilenet model
26 mobilenet = mobilenet.MobileNet()
27
28 # make predictions on test image using mobilenet
29 prediction = mobilenet.predict(pImg)
30
31 # obtain the top-5 predictions
32 results = imagenet_utils.decode_predictions(prediction)
33 print(results)
34
35 # convert the mobilenet model into tf.js model
36 save_path = "output\\mobilenet"
37 tfjs.converters.save_keras_model(mobilenet, save_path)
38 print("[INFO] saved tf.js mobilenet model to disk..")
https://gogul.dev/software/mobile-net-tensorflow-js 5/15
12/16/2019 Classifying images using Keras MobileNet and TensorFlow.js in Google Chrome – Gogul Ilango
Please make sure you change the test_img_path in line 19 to test an image from
your disk. Figure 2 (shown below) is the test image that I have chosen and the
MobileNet model accurately predicted it as a peacock with a probability of 99.99%.
Pretty cool! 😍
https://gogul.dev/software/mobile-net-tensorflow-js 6/15
12/16/2019 Classifying images using Keras MobileNet and TensorFlow.js in Google Chrome – Gogul Ilango
Contents X
Cool! Everything works perfectly in our Python environment. Now, we will use this
pretrained mobile net model in a web browser.
Before deploying a keras model in web, we need to convert the Keras mobilenet
python model into tf.js layers format (which we already did in lines 36-38).
To deploy a Keras model in web, we need a package called tensorflowjs . Run the
below command to get it.
https://gogul.dev/software/mobile-net-tensorflow-js 7/15
12/16/2019 Classifying images using Keras MobileNet and TensorFlow.js in Google Chrome – Gogul Ilango
Contents X
After installing it, you can either run the command as a standalone one or you can
Basic MobileNet in Python
integrate it in your python script as shown below (which I prefer).
Convert Keras model into Tf
JS layers format
Keras model into TensorFlow
1. keras to tf.js layers format cmd
JS
1. Load Keras model into
TF.js
1 tensorflowjs_converter --input_format keras \
2 path_to_keras_model.h5 \ 2. Upload image from disk
3 path/to/tfjs_target_dir 3. Predict using MobileNet
model
References
For this tutorial, I used my GitHub pages repo to hold the keras mobilenet model
files. I copied the entire folder under save_path here.
This is crucial for our application to work because if you host these model files in a
different server, you might face CORS issue in your web app. Storing your model
https://gogul.dev/software/mobile-net-tensorflow-js 8/15
12/16/2019 Classifying images using Keras MobileNet and TensorFlow.js in Google Chrome – Gogul Ilango
files in the same domain as your web app is safer and preferred way.
Once you load all the above three scripts, you can open up a new file named mobile-
net.js that will have all the functionality needed to make Keras MobileNet model
work in a web browser.
The user interface that I made at the start of the tutorial has HTML, CSS and
JavaScript code combined. We will look into model specific part instead of looking
into every single line of code.
Firstly, you need to load the Keras pretrained model json that you have stored in
your web server. To do this, you can use the below code snippet.
The below code snippet is an async function that loads a keras model json using
tf.loadModel() . In line 17, await means without disturbing the UI, you are asking
JavaScript to load model behind the scenes. To view the status of model loading,
we use a progress bar as well as console.log() .
https://gogul.dev/software/mobile-net-tensorflow-js 9/15
12/16/2019 Classifying images using Keras MobileNet and TensorFlow.js in Google Chrome – Gogul Ilango
mobile-net.js code
To upload an image from disk, you can use the below code snippet which makes
use of HTML5 File API. I have used a button Upload Image which has a change
index.html code
mobile-net.js code
https://gogul.dev/software/mobile-net-tensorflow-js 10/15
12/16/2019 Classifying images using Keras MobileNet and TensorFlow.js in Google Chrome – Gogul Ilango
1
2 // if there is a change to "Upload Image" button,
3 // load and render the image
4 $("#select-file-image").change(function() {
5 renderImage(this.files[0]); Contents X
6 }
Basic MobileNet in Python
7
8 // renders the image which is loaded from disk to the imgConvert
tag Keras model into Tf
9 function renderImage(file) { JS layers format
10 var reader = new FileReader(); Keras model into TensorFlow
11 reader.onload = function(event) { JS
12 img_url = event.target.result; 1. Load Keras model into
13 document.getElementById("test-image").src = img_url;
TF.js
14 }
reader.readAsDataURL(file); 2. Upload image from disk
15
} 3. Predict using MobileNet
model
References
To make predictions using mobilenet that’s now loaded into Tf.js environment, we
need to perform two steps.
As I have already mentioned, input image size to mobilenet is [224, 224] as well as
the features are scaled between [-1, 1]. You need to perform these two steps before
making predictions using the model. To do this, we use preprocessImage() function
that takes in two arguments image and modelName .
The input image can easily be loaded using tf.fromPixels() , resized using
resizeNearestNeighbor() and converting all the values in the image to float using
toFloat() .
After that, we feature scale the values in the image tensor using a scalar value of
127.5 which is the center value of image pixel range [0, 255]. For each pixel value in
the image, we subtract this offset value and divide by this offset value to scale
between [-1, 1]. We then expand the dimensions using expandDims() .
https://gogul.dev/software/mobile-net-tensorflow-js 11/15
12/16/2019 Classifying images using Keras MobileNet and TensorFlow.js in Google Chrome – Gogul Ilango
mobile-net.js code
Results from the predictions are mapped to an array named results using
IMAGENET_CLASSES that we loaded at the beginning of this tutorial. We also sort this
array based on the probability that is highest using sort() and take only the top-5
probabilities using slice() .
https://gogul.dev/software/mobile-net-tensorflow-js 12/15
12/16/2019 Classifying images using Keras MobileNet and TensorFlow.js in Google Chrome – Gogul Ilango
mobile-net.js code
https://gogul.dev/software/mobile-net-tensorflow-js 13/15
12/16/2019 Classifying images using Keras MobileNet and TensorFlow.js in Google Chrome – Gogul Ilango
There you go! We now have the power of state-of-the-art Keras pretrained model
MobileNet in a client browser that is able to make predictions on images that
belong to ImageNet category.
Contents X
In case if you found something useful to add to this article or you found a
bug in the code or would like to improve some points mentioned, feel free
to write it down in the comments. Hope you found something useful here.
10 Comments
https://gogul.dev/software/mobile-net-tensorflow-js 14/15
12/16/2019 Classifying images using Keras MobileNet and TensorFlow.js in Google Chrome – Gogul Ilango
https://gogul.dev/software/mobile-net-tensorflow-js 15/15