forked from PaddlePaddle/Paddle.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
77 lines (70 loc) · 2.3 KB
/
index.ts
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
import Worker from './worker';
const img = document.querySelector('#image') as HTMLImageElement;
const resultDom = document.querySelector('#result') as HTMLLIElement;
const uploadDom = document.querySelector('#uploadImg') as HTMLInputElement;
const worker = new (Worker as any)();
registerWorkerListeners();
init();
uploadDom.onchange = (e: Event) => {
if (!e.target) {
return;
}
const reader = new FileReader();
reader.onload = () => {
img.src = URL.createObjectURL((e.target as HTMLInputElement).files[0]);
img.onload = () => {
createImageBitmap(img, 0, 0, img.naturalWidth, img.naturalHeight)
.then(imageBitmap => {
worker.postMessage({
event: 'predict',
data: imageBitmap
}, [imageBitmap]);
});
};
};
reader.readAsDataURL((e.target as HTMLInputElement).files[0]);
};
function registerWorkerListeners() {
worker.addEventListener('message', async msg => {
const {
event,
data
} = msg.data;
switch (event) {
case 'predict':
resultDom.innerText = data;
break;
case 'init':
createImageBitmap(img, 0, 0, img.naturalWidth, img.naturalHeight)
.then(ImageBitmap => {
worker.postMessage({
event: 'predict',
data: ImageBitmap
}, [ImageBitmap]);
});
document.getElementById('loading').style.display = 'none';
break;
default:
break;
}
});
}
async function init() {
const onscreen = document.createElement('canvas');
const offscreen = onscreen.transferControlToOffscreen();
if (offscreen) {
worker.postMessage({
event: 'init',
data: {
modelPath: 'https://paddlejs.cdn.bcebos.com/models/mobileNetV2Opt/model.json',
fill: '#fff',
feedShape: {
fw: 224,
fh: 224
},
mean: [0.485, 0.456, 0.406],
std: [0.229, 0.224, 0.225]
}
});
}
}