【问题标题】:convert prediction tensor to an image将预测张量转换为图像
【发布时间】:2020-10-22 23:14:28
【问题描述】:

使用 tensorflow.js

我已成功导入我的模型并从中返回了预测。接下来,我想将该预测从张量转换为图像。我的第一个想法是去张量 -> js 数组 -> 一些画布情况。不过,我敢打赌,有一种更简单的方法可以做到这一点。希望不必涉及节点,但我对此持开放态度。

在这种情况下,预测被归一化为 -1 -> 1,所以我首先做一些数学运算以将值设为 0 -> 255

到目前为止:

var a = model.predict(tf.ones([1, 100]));
// map values from -1 -> 1 to 0 -> 255
var b = tf.scalar(127);
a = a.mul(b);
a = a.add(b);
// a.print();

// float to int
var cast = a.asType('int32');

// finally, as an array
var values = cast.arraySync();

这给了我一个 JS 中的二维数组。然后我可以这样做:

        // draw to a canvas
        var canvas = document.createElement("canvas");
        canvas.height = 128
        canvas.width = 128;
        //canvas.style.visibility = "hidden";
        document.body.appendChild(canvas);

        // in case not converting 2d to 1d...
        var data = values;

        // Now that we have canvas to work with, we need to draw the image data into it:
        var ctx = canvas.getContext("2d");
        for (var y = 0; y < data.length; ++y) {
          for (var x = 0; x < data[y].length; ++x) {
            ctx.fillStyle = "rgb("+data[x][y][0]+","+data[x][y][1]+","+data[x][y][2]+")";
            ctx.fillRect(x, y, 1, 1);
          }
        }

这行得通,虽然它不像我想要的那样活泼。试图让事情保持在客户端。有什么想法吗?

【问题讨论】:

    标签: javascript tensorflow tensorflow.js


    【解决方案1】:

    tf.browser.toPixels 可用于将图像绘制到画布上。

    const canvas = document.createElement('canvas');
    canvas.width = tensor.shape.width
    canvas.height = tensor.shape.height
    await tf.browser.toPixels(tensor, canvas);
    

    【讨论】:

      猜你喜欢
      • 2018-12-14
      • 2020-08-28
      • 2018-04-27
      • 2021-05-25
      • 1970-01-01
      • 1970-01-01
      • 2017-04-13
      • 2023-02-10
      • 2020-06-13
      相关资源
      最近更新 更多