javascript - 如何在nodejs服务器上使用tensorflow js?

标签 javascript node.js image tensorflow artificial-intelligence

我想在服务器端与nodejs一起使用tensorflow js插件与cocossd和mobilenet。 我已经在客户端完成了一个脚本,当用户提交表单时,我运行 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)
            });
        })
    });
});

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

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

npm i @tensorflow-models/mobilenet

npm i @tensorflow-models/coco-ssd

然后我尝试为 Node 安装tensorflow js:

npm i @tensorflow/tfjs-node

但是当我这样做时:

npm i tensorflow

我收到此错误:

npm ERR! code EBADPLATFORM

npm ERR! notsup Unsupported platform for [email protected]: wanted {"os":"linux,darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

npm ERR! notsup Valid OS: linux,darwin

npm ERR! notsup Valid Arch: any

npm ERR! notsup Actual OS: win32

npm ERR! notsup Actual Arch: x64

npm ERR! A complete log of this run can be found in:

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

请有人帮助我🙏 谢谢

最佳答案

当我执行“npm i @tensorflow-models/mobilenet”时,我也遇到了不同的问题。
这是屏幕截图。
看来是包有问题。 enter image description here

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

所以我最终使用了 TensorFlow mobilenet 的 CDN
请参阅以下代码行

<script src="https://cdn.jsdelivr.net/npm/@tensorflow/<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ef9b89859cafdec1d8c1de" rel="noreferrer noopener nofollow">[email protected]</a>/dist/tf.min.js"> </script> //
<!-- Load the MobileNet model. -->
<script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="670a08050e0b02090213275549574953" rel="noreferrer noopener nofollow">[email protected]</a>/dist/mobilenet.min.js"> </script>

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

<script src="https://cdn.jsdelivr.net/npm/@tensorflow/<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="324654584172031c051c03" rel="noreferrer noopener nofollow">[email protected]</a>/dist/tf.min.js"> </script> //
<!-- Load the MobileNet model. -->
<script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bfd2d0ddd6d3dad1dacbff8d918f918b" rel="noreferrer noopener nofollow">[email protected]</a>/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
下面是该项目的工作截图。 enter image description here

更新:在 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);
}

预测截图 enter image description here

关于javascript - 如何在nodejs服务器上使用tensorflow js?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60245677/

相关文章:

javascript - 使用 Express 和 Node.js 的谷歌地图 API

javascript - 如何编写加载特定图像后消失的加载屏幕?

html - 页面顶部的奇怪边距

javascript - vue.js/vue-router - 创建单个文件组件的实例,并使用要路由到的 props

javascript - 调试 Angular

javascript/json 日期文字

html - 如何平均设置 flex 元素高度

javascript - 将 Dicom 文件显示为 HTML 中的图像序列列表

node.js - 插入 Mongoose 对象内部的数组

node.js - 如何在生产环境中运行 Tabler