-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathflower.html
75 lines (70 loc) · 3.43 KB
/
flower.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
<html>
<head>
<title>看图识花</title>
<meta charset="utf-8">
<script src="script/tfjs.1.3.1.js"> </script>
</head>
<body>
<h1>看图识花</h1>
<div id="upload" >
<input id="img_input" type="file" accept="image/*" onchange="uploadPic(event)"/>
<label for="img_input"></label>
<div id="preview"></div>
<div id="predictText">
</div>
</div>
<p>前端智能DEMO合集:<a href="http://allan5.com/FE-AI/">http://allan5.com/FE-AI/</a></p>
<script>
let model = null;
let predictText = document.getElementById('predictText')
const label = ['雏菊','蒲公英','玫瑰','向日葵','郁金香'];
loadModel()
//加载模型
async function loadModel(){
predictText.innerHTML = '加载模型'
model = await tf.loadGraphModel('model/flower/model.json');
predictText.innerHTML = '模型加载完成'
}
//预测
async function predict(pic) {
if(!model) return
let predictText = document.getElementById('predictText')
predictText.innerHTML = '预测中'
let tpl = ''
//初始输入信息
const image = tf.browser.fromPixels(pic);
const resized_image =
tf.image.resizeBilinear(image, [224,224]).toFloat();
const offset = tf.scalar(255.0);
const normalized = tf.scalar(1.0).sub(resized_image.div(offset));
const batchedImage = normalized.expandDims(0);
const result = await model.predict(batchedImage).data();
//输出预测结果
let text = label.map((label, index) => ({ label, score: result[index] })).sort((a,b)=>b.score - a.score)
console.log(label.map((label, index) => ({ label, score: result[index] })).sort((a,b)=>b.score - a.score))
text.forEach((e)=>{
tpl +=`<p>${e.label},评分${e.score}</p>`
})
predictText.innerHTML = tpl;
}
//图片
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)
}
}
}
</script>
</body>
</html>