0%

使用预训练模型进行图像识别

利用预先训练好的模型进行图像识别

Javascript代码

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
import * as tf from '@tensorflow/tfjs';
import {IMAGENET_CLASSES} from './imagenet_classes';
import { file2img } from './utils';

//加载模型
const MOBILENET_MODEL_PATH = 'http://127.0.0.1:8080/mobilenet/web_model/model.json';

//用预训练模型进行图片识别
window.onload = async () =>{
const model = await tf.loadLayersModel(MOBILENET_MODEL_PATH);
//console.log(model);
window.predict = async (file) => {
//对上传的图片进行处理
const img = await file2img(file);
document.body.appendChild(img);
const pred = tf.tidy(() => {
const input = tf.browser.fromPixels(img)
.toFloat()
.sub(255/2)
.div(255/2)
.reshape([1, 224, 224, 3]); //图片格式为224px * 224px
return model.predict(input); //使用模型进行预测
});

const index = pred.argMax(1).dataSync()[0];
setTimeout(() => {
alert(`预测结果:${IMAGENET_CLASSES[index]}`);
},0);
};
};

效果图: