xxxxxxxxxx
87
// Classifier Variable
let classifier;
// Model URL (!!replace with your model URL!!)
let imageModelURL = 'https://teachablemachine.withgoogle.com/models/1fK5h8jX/';
// Video
let video;
let flippedVideo;
// To store the classification
let label = "";
let port;
let connect_button;
// Load the model first
function preload() {
classifier = ml5.imageClassifier(imageModelURL + 'model.json');
}
function setup() {
createCanvas(600, 600);
// Create the video
video = createCapture(VIDEO);
video.size(320, 240);
video.hide();
connect_button = createButton('connect arduino');
connect_button.position(width/2, height / 1.5);
connect_button.id('connect');
flippedVideo = ml5.flipImage(video)
// Start classifying
classifyVideo();
}
function draw() {
background(0);
// Draw the video
image(flippedVideo, 0, 0);
// Draw the label
fill(255);
textSize(16);
textAlign(CENTER);
text(label, width / 2, height - 4);
}
// Get a prediction for the current video frame
function classifyVideo() {
flippedVideo = ml5.flipImage(video)
classifier.classify(flippedVideo, gotResult);
}
// When we get a result
function gotResult(error, results) {
// If there is an error
if (error) {
console.error(error);
return;
}
// The results are in an array ordered by confidence.
// console.log(results[0]);
label = results[0].label;
data_to_send = new Uint8Array(1);
if (label === 'My Class Label 1') {
data_to_send[0] = 1;
}
else if (label === 'My Class Label 2') {
data_to_send[0] = 2;
}
else if (label === 'My Class Label 3') {
data_to_send[0] = 3;
}
if (port != undefined) {
port.send(data_to_send);
}
// Classifiy again!
classifyVideo();
}