Tag Archives: JavaScript

TensorFlow.js Image Classification with MobileNet Model

TensorFlow.js is a library for machine learning in JavaScript. Using TensorFlow.js one can,

  • Run existing model
  • Develop ML models in JavaScript
  • Use existing model and retrain it

Here in this blog post we will see first use case which is to run existing model. We will use MobileNet model to predict object through webcam.

TensorFlow.js Image Classification
tensorflow.js

TensorFlow.js Image Classification HTML

Let’s start it with basic HTML and add necessary scripts in it. First of all create one index.html file. Add following code in that file. Also create css folder and tfjs folder. Here we will out our style.css and our JS file to start image classification

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Image Classification</title>
    <link rel="stylesheet" href="css/style.css">
  </head>
  <body>
    <button id="webCam" class="btn webCam-button" onclick="openWebCam()">Start Web Cam</button>
    <div class="webcam-popup" id="webCamDisplay">
      <video autoplay playsinline muted id="webcam" width="224" height="224"></video>
      <button type="button" class="btn" id="predict" onclick="predictObject()">Predict</button>
      <button type="button" class="btn cancel" onclick="closeWebCamDisplay()">Close</button>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs/dist/tf.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/mobilenet"></script>
    <script src="tfjs/imageClassification.js"></script>
  </body>
</html>

As you can see in above HTML, we have very simple HTML here. We have button to start web cam. There is video element to show the preview of web cam. Then we have couple of buttons to start prediction. Now let’s add CSS. Create style.css in css folder and add following styles to it.

CSS Part

html {
  font-size: 60%;
  overflow-x: hidden;
  scroll-padding-top: 5rem;
  scroll-behavior: smooth;
}

header {
  margin-bottom: 2rem;
  position: relative;
  margin-left: 70px;
  margin-top: 30px;
  font-weight: bold;
}
header h1 {
  font-size: 30px;
  margin-left: 20px;
  font-weight: bold;
}

.btn {
  margin-top: 1rem;
  display: inline-block;
  padding: 1rem 2rem !important;
  border-radius: 1rem;
  color: #fff;
  background: #189ab4;
  font-size: 1.5rem !important;
  cursor: pointer;
  font-weight: 600 !important;
  margin-right: 10px;
}

.webCam-button {
  color: white;
  padding: 16px 20px;
  border: none;
  cursor: pointer;
  position: fixed;
  bottom: 140px;
  right: 28px;
}

.webcam-popup {
  display: none;
  position: fixed;
  bottom: 0;
  right: 15px;
  border: 3px solid #f1f1f1;
  z-index: 9;
  background-color: black;
}

JavaScript Part

Now we have html and css ready. It’s time for some JavaScript logic. We will create file with name imageClassification,js in tfjs folder and add following code to it.

const webcamElement = document.getElementById('webcam');
let startPrediction =  false;

async function app() {
  console.log('Loading mobilenet..');

  net = await mobilenet.load();
  console.log('Successfully loaded model');
  
  const webcam = await tf.data.webcam(webcamElement);
  while (true) {
    const img = await webcam.capture();
    const result = await net.classify(img);

    for(var i = 0 ; i < result.length ; i++ ) {
      res = result[i];
      if(res.probability > 0.5) {
        alert(res.className);
        location.reload();
        break;
      }
    }
    img.dispose();
    await tf.nextFrame();
  }
}

function openWebCam() {
  document.getElementById("webCamDisplay").style.display = "block";
}

function closeWebCamDisplay() {
  document.getElementById("webCamDisplay").style.display = "none";
}

function predictObject() {
  app();
}

Here we have functions to open & close pop up. There is predict button. Where we will start web cam preview and load the MobileNet Model. We are using async await syntax to wait till MobileNet model is loaded and then start the prediction. Following line loads the model.

net = await mobilenet.load();

Then we set the data source which is our webcam preview with following line.

const webcam = await tf.data.webcam(webcamElement);

Then we have while loop added where we capture the image frame and try to classify it with MobileNet model.

const img = await webcam.capture();
const result = await net.classify(img);

We are checking the results with accuracy over 50% to check if the classification is correct or not. If probability is good we show the classname in alert. This class name contains the name of object. It’s coming from MobileNet trained data.

When you run the code it may take a while to predict the object. You can check it out by placing multiple objects in front of web cam and check. Following are few examples.

As you can see in few cases the prediction is correct for example, mobile phone and mouse. But in the first case it’s wrong. I am not wearing bullet proof vest.

You can read more about TenorFlow.js on Official Website

Here is the link to MobileNet Model GitHub

Frontend Development trends to Look For in 2022

As we are moving to new year 2022, it’s good to keep an eye on Frontend Development trends. You should keep up with this latest trends so you don’t miss any opportunity that could be a turning point of your career.

In this blog I am going to mention some Frontend Development trends, you should not miss out. This is based on what I have learned from industry. If you have some different opinion, feel free to share your feedback in comments.

1) Progressive Web Apps

Progressive Web Applications
Progressive Web Applications

PWA is already trending since last few years thanks to its native app like capabilities. It can be installed like native app. You can work with it offline. It is blazing fast. Major mobile browsers now support it. With PWA, you can access hardwares like camera, microphone etc.

Above all capabilities, made PWA favourite among developers and businesses operating over internet. Lots of businesses are using it and many more are vouching for it in upcoming year. Hence if you are a PWA developer you may have great chances to work with major online businesses.

2) Micro Frontend Architecture

Micro Fronend Architecture

In a simple words, it’s about breaking monolith frontend to smaller and independent applications. Together it works as one single application. This gives you more control over development and CI /CD. Many teams can work together and combining it together makes your entire frontend.

Many companies have already adopted this architecture and their productivity has been increased. This trend is going to dominate in upcoming year. If you are front end developer or architect it will be good to learn about this.

3) Rise of Voice User Interface (VUI)

Voice User Interface (VUI)
Voice User Interface (VUI)

Accessibility is a prime thing to look for in web application now a days. This gives rise to Voice User Interface. As a human, voice / language is the most natural way of communication for us. This is also another major reason behind the rise of VUI. Major companies like Amazon, Google, Apple has introduced the platforms like Alexa, Assistant and Siri. These platforms are open for developers to build applications on top of that.

Power of text to speech and speech to text technologies has increased exponentially. These gives good accessibility to your web apps. Your users can interact with apps with voice and also it is blessing for visually impaired people. There are still major challenges in this area. Like understanding regional languages. But it’s worth adding VUI in web app.

4) Rise of JAMstack

JAMstack ==> JavaScript + API + Markup

JAMstack

Core principles of JAMstack are Pre rendering and decoupling. JAMstack makes web app faster, more secure and easily scalable. You can convert your entire frontend to highly optimised prebuilt static pages which can be delivered from CDN. Let’s understand each part of JAMstack

JavaScript

As we know JavaScript is most popular when it comes to building web application. Using the modern frameworks like ReactJS, Angular, Vue and Svelte, we can develop web apps which is modularised and easy to maintain.

API

API plays vital role in JAMstack. As a developer it’s up to you that how you can make your JAMstack app dynamic by utilizing the API in proper way. From JavaScript you can make API call to multiple host which will deliver the content.

Markup

This is the most critical part of JAMstack. To be considered a JAMstack app, your app should server the HTML statically, which means not being dynamically rendered from a server. Markups is your prebuilt and pre rendered content. It is requested by JavaScript through API. Frontend developers can use frameworks like Gatsby, NextJs for this.

5) Rise of GraphQL

GraphQL

Facebook introduced GraphQL in 2018 to address the issues with REST APIs. The issue with REST APIs are you have make multiple network requests to get the entire data. This leads to performance degrade both on front end and back end. Using GraphQL we can obtain entire data with one single quest from one end point.

Few advantages of GrapQL is, it’s much faster, strongly typed and follows hierarchical structure where relationships between objects are defined in a graphical structure. Many big companies are using GraphQL. As a front end developer it’s good learn about GraphQL as more and more businesses are moving towards GraphQL

6) Web Assembly

Web Assembly

Most of the time we use JavaScript for the web development. With web assembly developer can use code written in C and C++ in web browser. WebAssembly can help client apps to run on the web that previously was not possible. Sometimes we need to build app in lower level code like C, C++ etc. For example games or streaming apps. But it can’t run on web but with Web Assembly we can write apps in C, C++, RUST, Go Lang and run on the web with near-native performance. Web assembly works along with JavaScript in browser.

7) Machine Learning / Augmented Reality / Virtual Reality

How you can leverage the power of ML, AR & VR in your web app. To know more about this check out my session on Google DevFest India 2021 Day3

Hope you liked this blog about Frontend Development trends and keep exploring it more.