xxxxxxxxxx
134
// Copyright (c) 2019 ml5
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
/* ===
ml5 Example
Webcam Image Classification using a pre-trained customized model and p5.js
This example uses p5 preload function to create the classifier
=== */
// Classifier Variable
let classifier;
// Model URL
let imageModelURL = 'https://storage.googleapis.com/tm-model/Qzrq2aOi2/model.json';
// Video
let video;
let flippedVideo;
// To store the classification
let label = "";
// make an empty array
let bugs = [];
let numBugs = 40;
// Load the model first
function preload() {
classifier = ml5.imageClassifier(imageModelURL);
}
function setup() {
createCanvas(320, 260);
// Create the video
video = createCapture(VIDEO);
video.size(320, 240);
video.hide();
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);
// loop through all the bugs backwards
// looping backwards lets us see older particles on top
}
class Bug{
constructor(tempX, tempY, tempR) {
this.x = tempX;
this.y = tempY;
this.radius = tempR;
// pick a random color
this.color = color(255);
let r = random(3);
if(r < 1){
this.color = color(255,100,20,50); // orange
} else if(r >= 1 && r < 2 ){
this.color = color(255, 200, 10, 50); // yellow
} else if(r >= 2 ){
this.color = color(255, 80, 5, 50); // reddish
}
}
show() {
noStroke();
fill(this.color);
ellipse(this.x, this.y, this.radius);
}
move() {
this.x += random(-5, 5);
this.y -= random(1, 3);
}
shrink(){
// shrink size over time
this.radius-=0.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;
//print(results[0].label);
if (label == "Fire") {
for(let i = bugs.length -1; i>= 0; i--){
bugs[i].move();
bugs[i].show();
bugs[i].shrink();
if(bugs[i].radius <= 0 ){
//remove the dead ones
bugs.splice(i, 1);
}
}
// make more fire!!!
let x = 255;
let y = 185;
let radius = random(30,50);
let b = new Bug(x, y, radius);
bugs.push(b);
}
// Classifiy again!
classifyVideo();
}