TensorFlow Image Classifier with 10 lines

What we need to see a prediction are only 10 lines like following. In this case, I used npm instead of script tag. (using webpack)

import * as cocoSsd from ‘@tensorflow-models/coco-ssd’;
const img = new Image();
img.src = ‘./images/dog.jpg’;
const prediction = async() => {
const model = await cocoSsd.load();
console.log(“loaded…”);
const predictions = await model.detect(img);
document.getElementById(“prediction”).innerHTML=`class:${predictions[0].class} score:${predictions[0].score}`;
}
prediction();

The following HTML, index.html was generated by Visual Studio Code(just added script tag, image tag, and div tag)

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="bundle.js"></script>
<title>Document</title>
</head>
<body>
<img src="images/dog.jpg" id="dog" alt="">
<div id="prediction"></div>
</body>
</html>

Result

If you use script tag, you will need to write around 11 lines in index.html.

<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/coco-ssd"></script>
<script>
const img = new Image();
img.src = './cat.jpg';
cocoSsd.load().then(model => {
model.detect(img).then(predictions => {
console.log('Predictions: ', predictions);
});
});
</script>

If you add an image upload function/webcam, you can make ml application easily.
something like this https://sleepy-maker.github.io/tensorflowjs-and-keras/image_classification/webcam/app/public/

Written by

#CreativeCoding #Art #PhysicalComputing #IoT #MachineLearning #python #creativetech

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store