【问题标题】:How do I encode a 2D Tensor to a PNG image with Tensorflow.js + Node.js?如何使用 Tensorflow.js + Node.js 将 2D 张量编码为 PNG 图像?
【发布时间】:2020-09-01 13:45:23
【问题描述】:

假设我有一个这样的张量:

let myTensor = tf.tensor([
    [1,2,3],
    [4,5,6],
    [7,8,9]
]);

根据 Tensorflow.js API 文档,我可以使用 tf.node.encodePng 将张量转换为 PNG。文档声称其参数是这样的:

参数:

  • image (Tensor3D) 形状为 [高度、宽度、通道] 的 3-D uint8 张量。
  • compression(数字)一个可选的整数。默认为 -1。压缩级别。可选

在这种情况下,我假设我可以像这样将我的张量编码为 PNG:

let myImage = await tf.node.encodePng(myTensor.cast("uint8"));

但是,这会导致以下崩溃:

Uncaught Error: Failed to cast to unknown dtype uint8
    at cast_ (.../node_modules/@tensorflow/tfjs-core/dist/tf-core.node.js:5093:15)
    at Object.cast (.../ingester/node_modules/@tensorflow/tfjs-core/dist/tf-core.node.js:4186:29)
    at Tensor.cast (.../ingester/node_modules/@tensorflow/tfjs-core/dist/tf-core.node.js:2181:26)

根据documentation for the cast methoduint8 不是张量的有效类型。

如何将float32 类型的 2D 张量转换为 PNG 图像?

【问题讨论】:

    标签: javascript node.js tensorflow tensor tensorflow.js


    【解决方案1】:

    uint8 不是 tf tensor 支持的类型。但是,当从后端下载数据时,它可以是 uint8 类型的 typedArray。

    tf.node.encodePng 的参数是一个 3d 张量。所以首先需要将 2d 张量重塑为 3d

    【讨论】:

      猜你喜欢
      • 2019-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多