使用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/