首页 > 解决方案 > 如何在 nodejs 服务器上使用 tensorflow js?

问题描述

我想在带有nodejs的服务器端使用带有cocossd和mobilenet的tensorflow js插件。我已经在客户端完成了一个脚本,该脚本可以在用户提交表单时运行 tfjs:

const img = new Image(100, 100);
img.src = //base64 encoded image

// Load the model.
mobilenet.load().then(async model => {
    const post_predictions = []; 
    model.classify(img).then(classify_predictions => {
        classify_predictions.forEach(function(element){
            const each_class = element["className"].split(", ")
            each_class.forEach(function(this_element){
                post_predictions.push([this_element, (element.probability*100)]);
            })
        })
        cocoSsd.load().then(model => {
            // detect objects in the image.
            model.detect(img).then(predictions => {
                predictions.forEach(function(this_element){
                    post_predictions.unshift([this_element.class, (this_element.score*100)]);
                });
                post_predictions.sort(function(a, b) {
                    return b[1]-a[1];
                });

                console.log(post_predictions)
            });
        })
    });
});

我想在服务器端做同样的事情,但我知道模块需要什么模块或如何从它的 base 64 加载图像。

我尝试在我的服务器上下载 cocossd 和 mobilenet:

npm i @tensorflow-models/mobilenet

npm i @tensorflow-models/coco-ssd

然后我尝试为节点安装 tensorflow js:

npm i @tensorflow/tfjs-node

但是当我这样做时:

npm 我张量流

我收到此错误:

npm 错误!代码 EBADPLATFORM

npm 错误!notsup 不支持 tensorflow@0.7.0 的平台:想要 {"os":"linux,darwin","arch":"any"}(当前:{"os":"win32","arch":"x64"} )

npm 错误!notsup 有效操作系统:linux,darwin

npm 错误!notsup 有效拱门:任何

npm 错误!notsup 实际操作系统:win32

npm 错误!notsup 实际拱门:x64

npm 错误!可以在以下位置找到此运行的完整日志:

npm 错误!C:\Users\johan\AppData\Roaming\npm-cache_logs\2020-02-16T05_27_15_276Z-debug.log

请有人帮我谢谢

标签: javascriptnode.jsimagetensorflowartificial-intelligence

解决方案


当我执行“npm i @tensorflow-models/mobilenet”时,我也遇到了不同的问题。
这是屏幕截图。
好像是包有问题。 在此处输入图像描述

您可以尝试这样做作为替代方案。

所以我最终使用 TensorFlow mobilenet 的 CDN
参考下面的代码行

<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@1.7.1/dist/tf.min.js"> </script> //
<!-- Load the MobileNet model. -->
<script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/mobilenet@2.0.4/dist/mobilenet.min.js"> </script>

以下是步骤:
1. 使用 npm init 创建一个简单的节点项目。这将创建一个 package.json 文件。这是软件包所在或列出的位置。
2. 请注意,您需要在命令行中点击“npm install express --save”,以便将 express 包添加到 packages.json
3. 使用以下代码创建一个 index.html 文件。在 UI 方面,您将被要求上传一张图像,该图像将在控制台上进行评估或显示为警报消息。

<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@1.7.1/dist/tf.min.js"> </script> //
<!-- Load the MobileNet model. -->
<script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/mobilenet@2.0.4/dist/mobilenet.min.js"> </script>
<input type='file' />
<br><img id="myImg" src="#" alt="your image will be displayed here" >

<script>
  window.addEventListener('load', function() {
  document.querySelector('input[type="file"]').addEventListener('change', function() {
      if (this.files && this.files[0]) {
          var img = document.querySelector('img');  // $('img')[0]
          img.src = URL.createObjectURL(this.files[0]); // set src to blob url
          img.onload = imageIsLoaded;
      }
  });
});



async function run() {
    const img = document.getElementById('myImg');
    print(img)
    const version = 2;
    const alpha = 0.5;
    // Load the model.
    const model = await mobilenet.load({version, alpha});

    // Classify the image.
    const predictions = await model.classify(img);
    console.log('Predictions');
    console.log(predictions);

    // Get the logits.
    const logits = model.infer(img);
    console.log('Logits');
    logits.print(true);

    // Get the embedding.
    const embedding = model.infer(img, true);
    console.log('Embedding');
    embedding.print(true);
  }

function imageIsLoaded() { 
  run();
}

</script>

第 3 步:创建一个 server.js。该文件将用于使用 express npm 包在本地服务器上呈现索引文件。下面是代码:

const express = require('express');
app = express();

app.get('/',function(req,res) {
    res.sendFile('/demo/index.html', { root: __dirname });
});
const port = 3000
app.listen(port, function(){
    console.log(`Listening at port ${port}`);
})

第 4 步:转到浏览器并点击 localhost:3000
下面是该项目的工作截图。 在此处输入图像描述

UPDATE: LOADING ON NODEJS
看来问题出在安装顺序上
第 1 步:安装以下软件包

npm install @tensorflow/tfjs @tensorflow/tfjs-node --save
// or...
npm install @tensorflow/tfjs @tensorflow/tfjs-node-gpu --save

第 2 步:您现在可以安装 @tensorflow-models/mobilenet -save

npm install @tensorflow-models/mobilenet -save

第 3 步:Server.js 示例用法

const tf = require('@tensorflow/tfjs')
// Load the binding (CPU computation)
const mobilenet = require('@tensorflow-models/mobilenet');

// for getting the data images
var image = require('get-image-data')

image('./cup.jpg', async function (err, image) {

    const numChannels = 3;
    const numPixels = image.width * image.height;
    const values = new Int32Array(numPixels * numChannels);
    pixels = image.data
    for (let i = 0; i < numPixels; i++) {
        for (let channel = 0; channel < numChannels; ++channel) {
            values[i * numChannels + channel] = pixels[i * 4 + channel];
        }
    }
    const outShape = [image.height, image.width, numChannels];
    const input = tf.tensor3d(values, outShape, 'int32');
    await load(input)
});

async function load(img){
    // Load the model.
    const model = await mobilenet.load();

    // Classify the image.
    const predictions = await model.classify(img);

    console.log('Predictions: ');
    console.log(predictions);
}

预测截图 在此处输入图像描述


推荐阅读