Appendix B. Chapter Challenge Answers

Chapter 2: Truck Alert!

The MobileNet model can detect all kinds of different trucks. You could solve this problem by going through the list of identifiable trucks, or you can simply search for the word truck in the given list of class names. For simplicity, the provided answer did the latter.

The entire solution with HTML and JavaScript is here:

<!DOCTYPE html>
<html>
  <head>
    <script
    src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@2.7.0/dist/tf.min.js">
  </script>
    <script
    src="https://cdn.jsdelivr.net/npm/@tensorflow-models/mobilenet@1.0.0">
  </script> 1
    <script>
      mobilenet.load().then(model => {
        const img = document.getElementById('myImage'); 2
        // Classify the image
        model.classify(img).then(predictions => {
          console.log('Predictions: ', predictions);
          // Was there a truck?
          let foundATruck
          predictions.forEach(p => {
            foundATruck = foundATruck || p.className.includes("truck") 3
          })
          // TRUCK ALERT!
          if (foundATruck) alert("TRUCK DETECTED!") 4
        });
      });
    </script>
  </head>
  <body>
    <h1>Is this a truck?</h1>
    <img id="myImage" src="truck.jpg" width="100%"></img> ...

Get Learning TensorFlow.js now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.