xxxxxxxxxx
117
const myImageModelURL = 'https://teachablemachine.withgoogle.com/models/It0gZ1aI2/';
let myImageModel;
let resultDiv;
let serial;// variable to hold an instance of the serialport library
let portName = '/dev/tty.usbmodem1431301';// fill in your serial port name here
let outByte = 0;// for outgoing data
let video;
let label = "waiting...";
let classifier;
// let classifier;
function preload() {
classifier = ml5.imageClassifier(myImageModelURL+ 'model.json');
createCanvas(640, 520);
// video = createCapture(VIDEO);
// video.hide();
// classifyVideo();
}
function setup() {
createCanvas(640, 520);
video = createCapture(VIDEO);
classifyVideo();
// resultDiv = createElement('h1', '...');
serial = new p5.SerialPort(); // make a new instance of the serialport library
serial.on('error', serialError); // callback for errors
serial.open(portName); // open a serial port
// myImageModel.classify(video, gotResults);
// STEP 2: Start classifying
video.hide();
}
function classifyVideo() {
classifier.classify(video, gotResults);
}
function draw() {
background(0);
noStroke();
// Draw the video
image(video, 0, 0);
// STEP 4: Draw the label
textSize(32);
textAlign(CENTER, CENTER);
fill(255);
text(label, width / 2, height - 16);
noStroke()
// Pick an emoji, the "default" is train
let emoji = "🧐";
if (label == "Without Mask") {
emoji = "🤭";
stroke('red');
strokeWeight(10);
noFill();
rect(5, 5, 630, 470);
} else {
(label == "Mask")
emoji = "😷";
stroke('green');
strokeWeight(10);
noFill();
rect(5, 5, 630, 470);
}
// Draw the emoji
textSize(256);
text(emoji, width / 2, height / 2);
}
function serialError(err) {
console.log('Something went wrong with the serial port. ' + err);
}
function gotResults(err, results) {
if (err) console.log(err);
if (results) {
console.log(results);
// Wait for 0.5 second before classifying again
setTimeout(() => myImageModel.classify(video, gotResults), 500);
if (results[0].confidence < 0.7) return;
resultDiv.html('Result is: ' + results[0].label);
console.log(results[0].label);
if (results[0].label === 'Mask') {
outByte = 1;
} else if (results[0].label === 'Without Mask') {
outByte = 2;
} else {
outByte = 0;
}
// send it out the serial port:
console.log('outByte: ', outByte)
serial.write(outByte);
}
label = results[0].label;
classifyVideo();
}
function gotResults(error, results) {
// Something went wrong!
if (error) {
console.error(error);
return;
}
// Store the label and classify again!
label = results[0].label;
classifyVideo();
}