什么是Tensorflow.js?
TensorFlow.js是一个开源的基于硬件加速的JavaScript库,用于训练和部署机器学习模型。谷歌推出的第一个基于TensorFlow的前端深度学习框架TensorFlow.js 是一个开源的用于开发机器学习项目的 WebGL-accelerated JavaScript 库。TensorFlow.js 可以为你提供高性能的、易于使用的机器学习构建模块,允许你在浏览器上训练模型,或以推断模式运行预训练的模型。TensorFlow.js 不仅可以提供低级的机器学习构建模块,还可以提供高级的类似 Keras 的 API 来构建神经网络。
Tensorflow.js的优点:
1)不用安装驱动器和软件,通过链接即可分享程序
2)网页应用交互性更强
3)有访问GPS,Camera,Microphone,Accelerator,Gyroscope等传感器的标准api(主要是指手机端)
4)安全性,因为数据都是保存在客户端的
本文使用TensorFlow.js实现任意图片中主要要素的识别提取:
代码如下:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!-- Load TensorFlow.js. This is required to use coco-ssd model. -->
<script src="tfjs.js"></script>
<!-- Load the coco-ssd model. -->
<script src="coco-ssd.js"></script>
</head>
<body>
<!-- Replace this with your image. Make sure CORS settings allow reading the image! -->
<div>
<img id="img" src="57410e4667f97362aa44af920924938c.jpeg"/>
</div>
<div>
<textarea id="result" style="width:500px;min-height: 300px;"></textarea>
</div>
<!-- Place your code in the script tag below. You can also use an external .js file -->
<script>
// Notice there is no 'import' statement. 'cocoSsd' and 'tf' is
// available on the index-page because of the script tag above.
const img = document.getElementById('img');
// Load the model.
cocoSsd.load().then(model => {
// detect objects in the image.
model.detect(img).then(predictions => {
console.log('Predictions: ', predictions);
var resultStr = "";
for (var item of predictions) {
resultStr += "\n检测到:" + item.class + " ,概率:" + item.score + "\n";
resultStr += "区域:" + item.bbox + "\n";
}
document.getElementById('result').value = resultStr;
});
});
</script>
</body>
</html>
效果: