Skip to content

Instantly share code, notes, and snippets.

@kotobuki
Last active October 15, 2018 03:43
Show Gist options
  • Save kotobuki/0e3354f70010092f0012b484a4f968e9 to your computer and use it in GitHub Desktop.
Save kotobuki/0e3354f70010092f0012b484a4f968e9 to your computer and use it in GitHub Desktop.
Load Custom Model File
<body>
<fieldset>
<legend>1. Load</legend>
<p>Load files of your custom model from your local.</p>
<div>
<label for="modelFiles">Model files:</label>
<input type="file" id="modelFiles" name="modelFiles" multiple />
</div>
</fieldset>
<fieldset>
<p>Choose an image to classify with the model.</p>
<legend>2. Classify</legend>
<div>
<label for="imageToTest">Image to test:</label>
<input type="file" id="imageToTest" name="imageToTest" multiple />
</div>
</fieldset>
<p><span id="status">Status</span></p>
</body>
console.clear();
let featureExtractor;
let classifier;
let status;
let canvas;
const imageSize = 224;
function setup() {
status = select("#status");
status.html("Loading the base model...");
document
.getElementById("modelFiles")
.addEventListener("change", handleModelFiles, false);
document
.getElementById("imageToTest")
.addEventListener("change", handleImageToTest, false);
canvas = createCanvas(imageSize, imageSize);
canvas.position(status.elt.offsetLeft, status.elt.offsetTop + 30);
featureExtractor = ml5.featureExtractor("MobileNet", () => {
status.html("Please upload model files");
});
classifier = featureExtractor.classification();
}
function handleModelFiles(evt) {
classifier.load(evt.target.files, () => {
status.html("Loaded");
});
}
function handleImageToTest(evt) {
var files = evt.target.files;
const numFiles = files.length;
for (let i = 0, f; (f = files[i]); i++) {
let reader = new FileReader();
reader.onload = function(event) {
img = loadImage(event.target.result, img => {
resetMatrix();
background(0);
image(img, 0, 0, width, height);
const src = canvas.elt.toDataURL();
let tmpImg = createImg(src, "Failed to create", () => {
tmpImg.class("image").size(224, 224);
classifier.classify(tmpImg.elt, (err, result) => {
if (err) {
console.error(err);
}
// I want to get multiple results, instead of the top one
status.html(result);
console.log(`${f.name}: ${result}`);
});
tmpImg.remove();
});
});
};
reader.readAsDataURL(f);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.2/p5.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.2/addons/p5.dom.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/ml5js/ml5-library@f471eec18b7b64347b355ced8bc40604827924b3/dist/ml5.min.js"></script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment