xxxxxxxxxx
102
// Classifier Variable
let classifier;
// Model URL
let imageModelURL = 'https://teachablemachine.withgoogle.com/models/6esXcKnBy/';
// Video
let video;
let flippedVideo;
// To store the classification
let label = "";
let holeX;
let holeY;
let ballX;
let ballY;
// Load the model first
function preload() {
classifier = ml5.imageClassifier(imageModelURL + 'model.json');
}
function setup() {
createCanvas(320, 260);
// Create the video
video = createCapture(VIDEO);
video.size(320, 240);
video.hide();
flippedVideo = ml5.flipImage(video);
// Start classifying
classifyVideo();
placeHole();
initializeBall();
}
function placeHole() {
holeX = floor(random(width));
holeY = floor(random(height-20)) + 35;
}
function initializeBall() {
ballX = width/2 + 15;
ballY = height/2 + 15;
}
function draw() {
background(255);
// Draw the video
// image(flippedVideo, 0, 0);
push();
stroke("green");
noFill();
ellipse(holeX, holeY, 30, 30);
pop();
push();
fill("green");
ellipse(ballX, ballY, 30, 30);
pop();
if(ballX === holeX && ballY === holeY) {
placeHole();
initializeBall();
}
// Draw the label
fill(0);
textSize(16);
textAlign(CENTER);
text(label, width / 2, 20);
}
// Get a prediction for the current video frame
function classifyVideo() {
flippedVideo = ml5.flipImage(video)
classifier.classify(flippedVideo, gotResult);
flippedVideo.remove();
}
// 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;
if(label === "right") ballX += 1;
if(label === "left") ballX -= 1;
if(label === "up") ballY -= 1;
if(label === "down") ballY += 1;
// Classifiy again!
classifyVideo();
}