I am trying to predict drawing made on html canvas element with the help of Teachable Machine tensorflow.js. However when I am trying to predict using model.predict(image) it is giving me the same output as [0.2351463884,0.76485371] . I have tried using an html image element and it is working fine. The problem is only when I use Html canvas element.
const URL = "https://teachablemachine.withgoogle.com/models/S5O-110Gl/";
let model, labelContainer, maxPredictions;
// predict drawing on canvas when button is pressed
document.getElementById('start').addEventListener('click', async function() {
const modelURL = URL + "model.json";
const metadataURL = URL + "metadata.json";
// load the model and metadata
// Refer to tmImage.loadFromFiles() in the API to support files from a file picker
// or files from your local hard drive
// Note: the pose library adds "tmImage" object to your window (window.tmImage)
model = await tmImage.load(modelURL, metadataURL);
maxPredictions = model.getTotalClasses();
var canvas = document.getElementById('myCanvas');
const prediction = await model.predict(image);
console.log(prediction)
});
The TensorFlow algorithm probably does not accept canvas
as a source, only image
elements. But you can draw a canvas back into an image.
<canvas id="canvas" width="640" height="360"></canvas>
let canvas = document.getElementById("canvas");
let image = new Image();
image.src = canvas.toDataURL();
document.appendChild(image);