xxxxxxxxxx
67
// Machine Learning for Artists and Designers
// NYUSH F24 - gohai
let imageSize = 64; // the CNN will be created for 64x64 pixels
let imageChannels = 4; // and four color channels per pixel
let nn;
function setup() {
createCanvas(400, 400);
background(255);
// For this example to work across all browsers
// "webgl" or "cpu" needs to be set as the backend
ml5.setBackend("webgl");
let options = {
task: "imageClassification", // necessary
inputs: [imageSize, imageSize, imageChannels], // necessary
debug: true,
};
nn = ml5.neuralNetwork(options);
}
function draw() {
// simple drawing tool to demo
if (mouseIsPressed) {
fill(0);
noStroke();
ellipse(mouseX, mouseY, 50, 50);
}
}
function keyPressed() {
// resize the canvas to 64x64 pixels
let resizedImage = get();
resizedImage.resize(imageSize, imageSize);
if (key == "c") {
// classify
nn.classify({ image: resizedImage }, doneClassifying);
} else if (key == "e") {
// erase
background(255);
} else if (key == "t") {
// train
let options = {
epochs: 64,
};
nn.normalizeData();
nn.train(options, doneTraining);
} else {
// add label
nn.addData({ image: resizedImage }, [key]);
console.log("Added image for class " + key);
background(255);
}
}
function doneTraining() {
console.log("Done training!");
}
function doneClassifying(results) {
console.log(results[0].label + " @ " + results[0].confidence);
}