xxxxxxxxxx
92
let video;
let flippedVideo;
let sound;
let detector;
let detections = [];
let score = 0;
let maxScore = 500;
let running = false;
function preload() {
sound = loadSound("break.mp3");
}
function setup() {
createCanvas(480, 360);
video = createCapture(VIDEO);
video.size(width, height);
video.hide();
flippedVideo = ml5.flipImage(video);
detector = ml5.objectDetector("yolo", modelReady);
}
function modelReady() {
console.log("Model loaded");
detect();
}
function detect() {
flippedVideo = ml5.flipImage(video);
detector.detect(flippedVideo, gotResults);
}
function gotResults(err, results) {
detections = results;
for (let i = 0; i < detections.length; i++) {
if (detections[i].label == "person") {
if (running) {
score = score + detections[i].confidence;
}
break;
}
}
detect();
}
function draw() {
if (flippedVideo) {
image(flippedVideo, 0, 0, width, height);
}
for (let i = 0; i < detections.length; i++) {
if (detections[i].label == "person") {
noStroke();
fill(255);
text(
detections[i].label + " " + round(detections[i].confidence * 100) + "%",
detections[i].x + 4,
detections[i].y + 10
);
noFill();
strokeWeight(3);
stroke(0, 255, 0);
rect(
detections[i].x,
detections[i].y,
detections[i].width,
detections[i].height
);
}
}
noStroke();
fill(255, 0, 0);
rect(0, 10, width * (score / maxScore), 30);
text(round(score), width * (score / maxScore) + 10, 30);
}
function keyPressed() {
if (key == "b") {
// play sound
sound.play();
} else if (key == "r") {
// reset score
score = 0;
} else if (key == "s") {
// start or stop
running = !running;
}
}