xxxxxxxxxx
67
let capture;
let classifier;
let label = "";
let trainingCompleted = false;
let y = 0;
function setup() {
createCanvas(640, 480);
capture = createCapture(VIDEO);
capture.hide();
classifier = ml5.imageClassifier("MobileNet", capture, modelReady);
}
function modelReady() {
console.log("Model is ready!");
classifier.classify(gotResults);
}
function draw() {
background(255);
image(capture, 0, 0, 640, 480);
fill(0);
textSize(32);
textAlign(CENTER, CENTER);
text(label, width / 2, height - 16);
strokeWeight(4);
stroke(0, 255, 0);
line(0, y, width, y);
if (trainingCompleted) {
fill(0, 255, 0);
noStroke();
ellipse(width - 32, 32, 64);
}
}
function gotResults(error, results) {
if (error) {
console.error(error);
} else {
label = results[0].label;
classifier.classify(gotResults);
}
}
function mousePressed() {
if (!trainingCompleted) {
classifier.addImage(label);
y = y + 48;
if (y > height) {
trainingCompleted = true;
}
} else {
classifier.train((lossValue) => {
if (lossValue) {
console.error(lossValue);
} else {
console.log("Training complete");
classifier.classify(gotResults);
}
});
}
}