3

I use model.predict()to output a tensor A(size:512*512*3) by tensorflow.js and then I reshape it to A.reshape(512*512*3). But now I want to convert this tensor to an array so I can use it with three.js. How to solve this problem?

1 Answer 1

5

To convert a tensor to an array, You can use

  • data() or dataSync() to have a flatten typedarray

But currently the supported types are float32, int32; therefore the corresponding typedArray will be Float32Array and Int32Array. The typedarray constructors can be used to change the type of the typedarray

a = tf.tensor([1, 2, 3, 4])

buffer = a.dataSync().buffer

console.log(new Uint8Array(buffer))

console.log(new Uint16Array(buffer))

console.log(new Float32Array(buffer))

// To retrieve easily uint8 type, one can cast the tensor to `int32`

a = tf.tensor([1, 2, 3, 4], undefined, 'int32')

console.log(a.dtype)

buffer = a.dataSync().buffer
console.log(new Uint8Array(buffer))
console.log(new Float32Array(buffer))
<html>
  <head>
    <!-- Load TensorFlow.js -->
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]"> </script>
  </head>

  <body>
  </body>
</html>

Sign up to request clarification or add additional context in comments.

3 Comments

Is data() OK? Because dataSync() will block the UI thread until the values are ready, which can cause performance issues.
You can use data()
After executing the data() function, is there any way to get the data after it is executed? Such as callback

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.