javascript - 将预测张量转换为图像

标签 javascript tensorflow tensorflow.js

使用tensorflow.js

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

在本例中,预测标准化为 -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);
          }
        }

这可行,尽管它不像我想要的那么快。尝试将事情保留在客户端。有什么想法吗?

最佳答案

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

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

关于javascript - 将预测张量转换为图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64483632/

相关文章:

python - 如何在Tensorflow中为张量的所有初始化权重添加一个常量?

python - tensorflow 无效参数错误 : You must feed a value for placeholder tensor with dtype float

javascript - 获取张量内特定索引的值?

javascript - React - 发送 ref 作为 Prop 不起作用

javascript - 是否可以在 Javascript 中映射或排序数组对象

javascript - 是否有在线 JSON 查看器/格式化程序可以显示属性的路径?

javascript - 通过 ajax 加载内容时 jQuery 的本地时间插件失败

python - 安装tensorflow时找不到版本

javascript - 使用 Tensorflow.js 开发游戏 AI

javascript - 未捕获( promise )TypeError : Cannot read property 'length' of null