-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathmobilenet.html
103 lines (97 loc) · 4.71 KB
/
mobilenet.html
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
<html>
<head>
<title>mobilenet</title>
<meta charset="utf-8">
<script src="script/tfjs.1.3.1.js"> </script>
<script src="script/mobilenet.2.0.2.js"> </script>
</head>
<body>
<h1>图像分类</h1>
<div id="camera" style="display:none;width:640px;height:480px;position:relative;">
<video id="video" width="640" height="480" autoplay></video>
</div>
<div id="upload" style="display:none">
<input id="img_input" type="file" accept="image/*" onchange="uploadPic(event)"/>
<label for="img_input"></label>
<div id="preview"></div>
</div>
<div id="predict"></div>
<p>官方地址:<a href="https://github.com/tensorflow/tfjs-models/tree/master/mobilenet">https://github.com/tensorflow/tfjs-models/tree/master/mobilenet</a></p>
<p>前端智能DEMO合集:<a href="http://allan5.com/FE-AI/">http://allan5.com/FE-AI/</a></p>
<script>
let CAMERA = document.getElementById('camera')
let UPLOAD = document.getElementById('upload')
let net = null;
let video = null;
let PREDICT = document.getElementById('predict');
window.addEventListener("DOMContentLoaded", function() {
video = document.getElementById('video');
let mediaConfig = {
'audio': false,
'video': {
facingMode: 'user',
width: 640,
height: 480,
}
};
//加载模型
loadModel()
if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia(mediaConfig).then(function(stream) {
CAMERA.style.display = 'block';
setInterval(function(){
predict(video)
},500)
video.srcObject = stream;
video.play();
}).catch((e)=>{
//显示上传框
UPLOAD.style.display = 'block'
console.log('用户已禁用摄像头');
});
}else{
//显示上传框
UPLOAD.style.display = 'block';
}
}, false);
//图片
async function uploadPic(e){
let file = e.target.files[0];
if (!file.type.match('image.*')) return;
let reader = new FileReader();
let PREVIEW = document.getElementById('preview');
reader.readAsDataURL(file);
reader.onload = function(e){
PREVIEW.innerHTML = '';
PREVIEW.innerHTML = `<img id="pic" src='${e.target.result}' width="320" >`;
let image = new Image();
image.src= e.target.result;
image.onload = function () {
//预测
predict(image)
}
}
}
// 主逻辑
async function loadModel(){
PREDICT.innerHTML = '模型加载中..'
net = await mobilenet.load(
{
version:1.0,
modelUrl:'model/mobilenet/model.json'
}
);
PREDICT.innerHTML = '模型加载完成'
}
async function predict(o){
if(!net) return
const predict = await net.classify(o);
let tpl = ``;
predict.forEach(e=>{
tpl +=`<p>${e.className}:相似度${e.probability}</p>`
})
document.getElementById('predict').innerHTML = tpl;
}
</script>
</body>
</html>