-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
64 lines (57 loc) · 2.31 KB
/
Copy pathindex.js
File metadata and controls
64 lines (57 loc) · 2.31 KB
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
//dom elements
const form = document.querySelector("form");
const img = document.querySelector(".img-field");
const imageType = document.querySelector("#image-type");
const submitBtn = document.querySelector(".submit-btn");
const uploadText = document.querySelector(".upload-text");
const confTitle = document.querySelector(".conf-title");
const confText = document.querySelector(".confidence");
const resultContainer = document.querySelector(".result-container");
//initializing ml5 mobileNet model
let mobileNet = ml5.imageClassifier("MobileNet", () => {});
form.addEventListener("change", handleImageInput, false);
form.addEventListener("submit", handleImageSubmit);
//handling image submit
function handleImageSubmit(e) {
e.preventDefault();
imageType.innerText = "Loading ...";
//sending prediction request to mobileNet
mobileNet.predict(img, gotResult);
}
function handleImageInput(e) {
//modifying dom elements
resultContainer.classList.add("hidden");
resultContainer.classList.remove("show");
submitBtn.classList.remove("hidden");
imageType.innerText = "";
confTitle.textContent = "";
submitBtn.classList.add("show");
uploadText.innerText = "Upload Another Image";
confText.textContent = "";
//getting imported image url and adding it
img.src = window.URL.createObjectURL(e.target.files[0]);
}
function gotResult(error, result) {
if (error) {
alert("Cannot get Image Type" + "\n" + error);
} else {
//modifying dom elements
submitBtn.classList.add("hidden");
submitBtn.classList.remove("show");
resultContainer.classList.remove("hidden");
resultContainer.classList.add("show");
confTitle.textContent = "Confidence: ";
//displaying the result on the dom
const confidenceResult = Math.round(result[0].confidence * 100);
imageType.innerText = result[0].label;
confText.textContent = `${confidenceResult}%`;
//PREFERENCE: changing `confidence` border-color based on result
if (confidenceResult < 25) confText.style.borderColor = " #e8492a";
else if (confidenceResult < 50) confText.style.borderColor = "#f2ef3f";
else if (confidenceResult < 75) confText.style.borderColor = "#5fa5b8";
else confText.style.borderColor = "black";
}
}
//useful documentation:
// 1. https://learn.ml5js.org/docs/#/
// 2.https://ml5js.org/reference/api-ImageClassifier/