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();
const predictions = await model.detect(img);
document.getElementById(“prediction”).innerHTML=`class:${predictions[0].class} score:${predictions[0].score}`;

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">
<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>
<img src="images/dog.jpg" id="dog" alt="">
<div id="prediction"></div>


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>
const img = new Image();
img.src = './cat.jpg';
cocoSsd.load().then(model => {
model.detect(img).then(predictions => {
console.log('Predictions: ', predictions);

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