/
sketch.js
91 lines (80 loc) 路 2.19 KB
/
sketch.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// Copyright (c) 2019 ml5
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
/* ===
ml5 Example
Creating a regression extracting features of MobileNet. Build with p5js.
=== */
let featureExtractor;
let regressor;
let video;
let loss;
let slider;
let samples = 0;
let positionX = 140;
function setup() {
createCanvas(340, 280);
// Create a video element
video = createCapture(VIDEO);
// Append it to the videoContainer DOM element
video.hide();
// Extract the features from MobileNet
featureExtractor = ml5.featureExtractor("MobileNet", modelReady);
// Create a new regressor using those features and give the video we want to use
regressor = featureExtractor.regression(video, videoReady);
// Create the UI buttons
setupButtons();
}
function draw() {
image(video, 0, 0, 340, 280);
noStroke();
fill(255, 0, 0);
rect(positionX, 120, 50, 50);
}
// A function to be called when the model has been loaded
function modelReady() {
select("#modelStatus").html("Model loaded!");
}
// A function to be called when the video has loaded
function videoReady() {
select("#videoStatus").html("Video ready!");
}
// Classify the current frame.
function predict() {
regressor.predict(gotResults);
}
// A util function to create UI buttons
function setupButtons() {
slider = select("#slider");
// When the Dog button is pressed, add the current frame
// from the video with a label of "dog" to the classifier
select("#addSample").mousePressed(function() {
regressor.addImage(slider.value());
select("#amountOfSamples").html((samples += 1));
});
// Train Button
select("#train").mousePressed(function() {
regressor.train(function(lossValue) {
if (lossValue) {
loss = lossValue;
select("#loss").html(`Loss: ${loss}`);
} else {
select("#loss").html(`Done Training! Final Loss: ${loss}`);
}
});
});
// Predict Button
select("#buttonPredict").mousePressed(predict);
}
// Show the results
function gotResults(err, result) {
if (err) {
console.error(err);
}
if (result && result.value) {
positionX = map(result.value, 0, 1, 0, width);
slider.value(result.value);
predict();
}
}