-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
79 lines (68 loc) · 2.47 KB
/
index.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
const webcamElement = document.getElementById('webcam');
let net;
document.getElementById('classify-webcam').addEventListener('click', async () => {
await setupWebcam();
while (true) {
const result = await net.classify(webcamElement);
document.getElementById('console').innerText = `
prediction: ${result[0].className}\n
probability: ${result[0].probability}
`;
await tf.nextFrame();
}
});
const fileElement = document.getElementById('file-input');
document.getElementById('classify-image').addEventListener('click', () => {
fileElement.click();
});
fileElement.addEventListener('change', (event) => {
const file = event.target.files[0];
const fileType = file['type'];
if (fileType.search('image') >= 0) {
const imageReader = new FileReader();
imageReader.addEventListener('load', (imageEvent) => {
const image = new Image();
image.src = imageEvent.target.result;
image.onload = async () => {
document.getElementById('preview-image').innerHTML
= '<img id="thumbnail" src="' + image.src + '" />';
document.getElementById('thumbnail').style.width = "250px";
document.getElementById('thumbnail').style.height = "250px";
const result = await net.classify(image);
document.getElementById('result').innerHTML = '<p>' +
JSON.stringify(result.reduce((prev, current) => {
return (prev.probability > current.probability) ? prev : current;
})) + '</p>'
};
});
imageReader.readAsDataURL(file);
}
});
async function app() {
console.log('Loading mobilenet..');
// Load the model.
net = await mobilenet.load();
console.log('Sucessfully loaded model');
document.getElementById('loading').style.visibility = 'hidden';
document.getElementById('classify-webcam').classList.remove('loading');
document.getElementById('classify-image').classList.remove('loading');
}
async function setupWebcam() {
return new Promise((resolve, reject) => {
const navigatorAny = navigator;
navigator.getUserMedia = navigator.getUserMedia ||
navigatorAny.webkitGetUserMedia || navigatorAny.mozGetUserMedia ||
navigatorAny.msGetUserMedia;
if (navigator.getUserMedia) {
navigator.getUserMedia({video: true},
stream => {
webcamElement.srcObject = stream;
webcamElement.addEventListener('loadeddata', () => resolve(), false);
},
error => reject());
} else {
reject();
}
});
}
app();