介绍
image-recognition
是一个基于 TensorFlow.js 的 npm 包,在浏览器中使用机器学习模型来识别图像。它提供了多种模型可以用于不同类型的图像识别任务。通过简单的几行代码,你就可以实现图像识别的功能。
安装
首先需要在项目中安装 image-recognition
。
使用 npm:
npm install image-recognition
使用 yarn:
yarn add image-recognition
使用
在你的项目中导入 image-recognition
。
import * as imagenet from 'image-recognition';
加载模型
首先需要加载一个预训练模型,可以通过 imagenet.load
方法进行加载。
const model = await imagenet.load();
load
方法需要一定的时间来加载模型。在模型加载完成前需要等待,可以使用 Promise
来解决。
预测
一旦加载了模型,你就可以使用它来进行预测了。
const image = getImageDataFromSomewhere(); // 获取图片数据 const topPredictions = await model.predict(image); console.log(topPredictions);
默认情况下,predict
方法将返回前五个预测结果及其概率,返回的对象结构如下:
-- -------------------- ---- ------- - ------------ - - ---------- ---------- ------------ --- -- - ---------- ---------- ------------ ---- -- - ---------- ---------- ------------ ----- -- - ---------- ---------- ------------ ----- -- - ---------- ---------- ------------ ----- - - -
在上面的代码中,getImageDataFromSomewhere
函数应该是获取图片数据的函数。在浏览器中,可以通过 Canvas
元素来获得图片数据:
const canvas = document.getElementById('my-canvas'); const ctx = canvas.getContext('2d'); const img = document.getElementById('my-image'); ctx.drawImage(img, 0, 0); const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); const image = imagenet.fromPixels(imageData);
在这个例子中,通过 fromPixels
方法将 ImageData
转换为 Tensor
。
指定模型
image-recognition
支持多种模型,你可以通过指定模型来进行图像识别。
使用 VGG16 模型:
const model = await imagenet.load(imagenet.Models.VGG16);
使用 MobileNetV1 模型:
const model = await imagenet.load(imagenet.Models.MobileNetV1);
使用 MobileNetV2 模型:
const model = await imagenet.load(imagenet.Models.MobileNetV2);
指定标签
image-recognition
默认使用预训练模型的标签进行预测。你也可以指定自己的标签文件。
const model = await imagenet.load(null, '/path/to/labels.txt');
标签文件应该是一个纯文本文件,每行一个标签。例如:
label_1 label_2 label_3
示例代码
下面是一个完整的示例代码,用于在浏览器中实现图像识别。
-- -------------------- ---- ------- ------ - -- -------- ---- -------------------- ----- -------- --------- - ----- ----- - ----- ---------------- ----- --- - ------------------------------------ ----- ------ - --------------------------------- ------------ - ---------- ------------- - ----------- ----- --- - ------------------------ ------------------ -- --- ----- --------- - ------------------- -- ------------- --------------- ----- ----- - ------------------------------- ----- -------------- - ----- --------------------- ---------------------------- - ----------
总结
本文介绍了 npm 包 image-recognition
的使用方法。通过 image-recognition
,你可以轻松地在浏览器中实现图像识别功能。它具有简单易用的 API,支持多种模型,可以根据需要指定标签文件。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/60056bdf81e8991b448e590c